This is a Python 3 HTTP/1.1 server bound to 127.0.0.1 on port 8000 using only the standard library.
I wanted a simple Python 3 web server using HTTP 1.1 that can perform simple HTTP operations and depends only on Python and standard library modules. I couldn't find an example so I made one.
The example demonstrates how to accept different methods, parse the url and query strings, read data sent to the server, parse and return json, return responses with different status codes and headers, handle graceful termination, and override the default error logging.
Start the server:
$ python3 app.py
Stop the server using ctrl-c. You can optionally specify the host and port to bind to using --host
and --port
command line arguments. By default the host "127.0.0.1" and port 8000 are used.
The GET endpoint demonstrates how to parse the query string and returns a message based on the name parameter.
$ curl -i '127.0.0.1:8000/hello?name=World'
HTTP/1.1 200 OK
Server: Tiny Http Server
Date: Fri, 21 May 2021 22:35:02 GMT
Content-Type: text/plain
Content-Length: 13
Hello, World
The POST endpoint demonstrates how to read content sent to the server and returns a message based on this content:
$ curl -X POST --data 'foo bar' -i '127.0.0.1:8000/echo'
HTTP/1.1 202 Accepted
Server: Tiny Http Server
Date: Fri, 21 May 2021 22:35:28 GMT
Content-Type: text/plain
Content-Length: 17
Accepted: foo bar
The same endpoint can also send and receive json by specifying the Content-Type
header:
$ curl -X POST -H 'Content-Type: application/json' -i --data '{"foo": "bar"}' '127.0.0.1:8000/echo'
HTTP/1.1 202 Accepted
Server: Tiny Http Server
Date: Sat, 22 May 2021 17:06:04 GMT
Content-Type: application/json
Content-Length: 64
{
"message": "Accepted",
"request": {
"foo": "bar"
}
}
Thanks AndyStanton, This is very helpful :)