0

I need to make a simple API using Python.

There are many tutorials to make a REST API using Django REST framework, but I don't need REST service, I just need to be able to process POST requests.

How can I do that? I'm new to Python.

Thank you!

2
  • you might like flask: flask.pocoo.org, easy to deploy using nginx Commented Jul 2, 2018 at 11:12
  • @hootnot I agree with you. You can also use simple HTTP requests Like requests.post() or requests.get(). Commented Jul 2, 2018 at 11:15

2 Answers 2

6

You can use HTTPServer module alongwith SimpleHTTPRequestHandler to create a simple webserver that serves your GET and POST request

from http.server import BaseHTTPRequestHandler,HTTPServer, SimpleHTTPRequestHandler

class GetHandler(SimpleHTTPRequestHandler):

        def do_GET(self):
            SimpleHTTPRequestHandler.do_GET(self)

        def do_POST(self):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.data_string = self.rfile.read(int(self.headers['Content-Length']))

            data = b'<html><body><h1>POST!</h1></body></html>'
            self.wfile.write(bytes(data))
            return

Handler=GetHandler

httpd=HTTPServer(("localhost", 8080), Handler)
httpd.serve_forever()
Sign up to request clarification or add additional context in comments.

Comments

0

Well if you don't need the whole DRF stuff than just don't use it.

Django is built around views which take HTTP requests (whatever the verb - POST, GET etc) and return HTTP responses (which can be html, json, text, csv, binary data, whatever), and are mapped to urls, so all you have to do is to write your views and map them to url.

3 Comments

So, is django even without django rest framework, actually fully capable of giving you means to make rest api? Because, it has url paths and functions which get executed on those paths, and it also has data models...
@ŽarkoTomičić a REST api is nothing but plain old HTTP requests and responses, so any techno able to receive HTTP requests and return HTTP response can be used to build a REST api. The "Django Rest Framework" is just a shortand that automates part of the job based on your models - and can actually get a bit involved when you don't have a 1:1 mapping between your models and your API (think of it as a REST version of the Django Admin). A more lightweight solution is Daniel Lindays's "restless" mini-framework. And you can of course just code the whole thing by yourself if it's a simple API.
So, then, it is?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.