Creating A Pure Python Api (without Any Framework) Where Postman Client Can Successfully Post Json Requests
Solution 1:
You didn't show full error message and I don't use Windows to test it but SimpleHTTPRequestHandler
doesn't have function do_POST
to receive POST
request and this can make problem.
You will have to use SimpleHTTPRequestHandler
to create own class with do_POST
.
And this function will need to
- get header information
- read JSON string
- convert request data from JSON string to dictionary
- convert response data from dictionary to JSON string
- send headers
- send JSON string
so it will need a lot of work.
Minimal working server
import http.server
import socketserver
import json
PORT = 8000classMyHandler(http.server.SimpleHTTPRequestHandler):
defdo_POST(self):
# - request -
content_length = int(self.headers['Content-Length'])
#print('content_length:', content_length)if content_length:
input_json = self.rfile.read(content_length)
input_data = json.loads(input_json)
else:
input_data = Noneprint(input_data)
# - response -
self.send_response(200)
self.send_header('Content-type', 'text/json')
self.end_headers()
output_data = {'status': 'OK', 'result': 'HELLO WORLD!'}
output_json = json.dumps(output_data)
self.wfile.write(output_json.encode('utf-8'))
Handler = MyHandler
try:
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"Starting http://0.0.0.0:{PORT}")
httpd.serve_forever()
except KeyboardInterrupt:
print("Stopping by Ctrl+C")
httpd.server_close() # to resolve problem `OSError: [Errno 98] Address already in use`
And testing code
import requests
data = {'search': 'hello world?'}
r = requests.post('http://localhost:8000/api', json=data)
print('status:', r.status_code)
print('json:', r.json())
This example doesn't check if you run /api
or /api/function
or /api/function/arguments
because it would need much more code.
So pure python API without framework can need a lot of work and it can be waste of time.
The same code with Flask
. It is much shorter and it already checks if you send to /api
.
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api', methods=["GET", "POST"])defapi():
input_data = request.json
print(input_data)
output_data = {'status': 'OK', 'result': 'HELLO WORLD!'}
return jsonify(output_data)
if __name__ == '__main__':
#app.debug = True
app.run(host='0.0.0.0', port=8000)
BTW:
If you want to test post data then you can use portal http://httpbin.org and send POST
request to http://httpbin.org/post and it will send back all data and headers.
It can be used also for other requests and data.
This portal was created with Flask and there is even link to source code so you can install it on own computer.
It seems httpbin
is part of Postman
repo on GitHub.
Post a Comment for "Creating A Pure Python Api (without Any Framework) Where Postman Client Can Successfully Post Json Requests"