Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a REST API without Flask in python

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)
like image 790
Slickmind Avatar asked Nov 07 '22 02:11

Slickmind


1 Answers

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

like image 110
ferdina kusumah Avatar answered Nov 15 '22 07:11

ferdina kusumah