9

I want to create a REST API without using Flask. I have created once using Flask as shown below but now I want to try without Flask. I came to know that urllib is one of the packages for doing it but not sure how to do. Even if there is some way other than urllib then that is also fine.

from werkzeug.wrappers import Request, Response
import json
from flask import Flask, request, jsonify
app = Flask(__name__)

with open ("jsonfile.json") as f:
    data = json.load(f)
    #data=f.read()

@app.route('/', methods=['GET', 'POST'])
def hello():
    return jsonify(data)

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 9000, app)
5
  • 3
    What's your question? Commented Sep 20, 2018 at 5:51
  • I want to create REST api to send my JSON data. I have already done it using Flask but now I want to do it without Flask, so I want to know how it could be done without using Flask? I came to know that through urllib it is possible but I do not know how to do it Commented Sep 20, 2018 at 5:55
  • Let me know if something is not clear! Thanks! Commented Sep 20, 2018 at 5:55
  • May I ask if there's a specific reason you don't want to/can't use flask? Doing this manually without flask or werkzeug would be very complicated and time consuming, they've covered a lot for you already. Also your code is not to best practices or per the flask documentation, if you're having issues I'd look into it more before writing off the framework completely. Commented Sep 20, 2018 at 5:56
  • 1
    my other teammates are not very comfortable with Flask. We have used http client to make a response client, now want to make request server without flask. Commented Sep 20, 2018 at 6:02

2 Answers 2

7

You can try something like this

import json
import http.server
import socketserver
from typing import Tuple
from http import HTTPStatus


class Handler(http.server.SimpleHTTPRequestHandler):

    def __init__(self, request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer):
        super().__init__(request, client_address, server)

    @property
    def api_response(self):
        return json.dumps({"message": "Hello world"}).encode()

    def do_GET(self):
        if self.path == '/':
            self.send_response(HTTPStatus.OK)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(bytes(self.api_response))


if __name__ == "__main__":
    PORT = 8000
    # Create an object of the above class
    my_server = socketserver.TCPServer(("0.0.0.0", PORT), Handler)
    # Star the server
    print(f"Server started at {PORT}")
    my_server.serve_forever()

And testing like this

→ curl http://localhost:8000
{"message": "Hello world"}%

but keep in mind that this code is not stable and just sample

Sign up to request clarification or add additional context in comments.

Comments

0

You shall take an existing web server and use WSGI compatible app, for example, for Apache HTTP 2.2

  1. Install mod_wsgi (just search how to install mod_wsgi in your operating system)

  2. Configure mod_wsgi in Apache httpd.conf

    LoadModule wsgi_module modules/mod_wsgi.so

    WSGIScriptAlias /wsgi /var/www/wsgi/myapp.wsgi

  3. Write myapp.wsgi

The code for myapp.wsgi must call the second argument once in this way:

def application(environ, start_response):
status = '200 OK'
output = b'{"message": "Hello world"}'

response_headers = [('Content-type', 'application/json'),
                    ('Content-Length', str(len(output)))]
start_response(status, response_headers)

return [output]

Comments

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.