How do I create an API in Python without using any framework or external library?
-
I can create API using Django-RESTFramework. but I dont want to use any framework.just simple Python . code will contain - a local server on which we will hit API and then it will return JSON response. e.g input/headerbody - { name : xyz, email : } and JSON response we will get - { name : xyz, email : id : 1234 }
-
Answer:
Might want to use sqlite3 and an ORM (like sqlalchemy). Using only stdlib (although I don't know why you care that much): from BaseHTTPServer import HTTPServerfrom BaseHTTPServer import BaseHTTPRequestHandlerimport cgiimport jsonTODOS = [ {'id': 1, 'title': 'learn python'}, {'id': 2, 'title': 'get paid'},]class RestHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write(json.dumps({'data': TODOS})) return def do_POST(self): new_id = max(filter(lambda x: x['id'], TODOS))['id'] + 1 form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'] }) new_title = form['title'].value new_todo = {'id': new_id, 'title': new_title} TODOS.append(new_todo) self.send_response(201) self.end_headers() self.wfile.write(json.dumps(new_todo)) returnhttpd = HTTPServer(('0.0.0.0', 8000), RestHTTPRequestHandler)while True: httpd.handle_request()
Max Mautner at Quora Visit the source
Related Q & A:
- How should I use Youtube API?Best solution by Stack Overflow
- How do I create a Cocoa Touch Framework?Best solution by stackoverflow.com
- How do i create virtual subdomain using htaccess?Best solution by Stack Overflow
- How do I know whether my ball python is pregnant?Best solution by Yahoo! Answers
- How Can I Create an XML to Create a Menu?Best solution by Drupal Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.