HTTP
HTTP is the request/response protocol of the web: a client sends a method, URL, headers, and optional body; the server replies with a status, headers, and a body. Python talks HTTP through urllib, http.client, Requests, and ASGI/WSGI apps.
Detailed Explanation
A request is GET /orders/11 HTTP/1.1 plus headers (Host, Accept, Authorization) and sometimes a body. A response is 200 OK plus headers (Content-Type, Set-Cookie) and a body. Methods have conventions: GET and HEAD are safe and should be free of side effects; PUT and DELETE are idempotent; POST creates or triggers work. The protocol does not enforce those conventions. Your API should.
URLs name the resource. Query strings (?page=2) filter. Path segments identify. Headers carry metadata, not the primary payload, though cookies and auth tokens live there. Bodies are bytes. JSON is a Content-Type: application/json body, not a different protocol.
HTTP/1.1 is text-oriented and often reused on one TCP connection. HTTP/2 multiplexes streams. TLS (HTTPS) encrypts the socket. Python clients hide the version; you still need to know redirects, timeouts, and streaming.
In Python, servers are WSGI or ASGI callable objects. Frameworks parse the request into an object (flask.request, FastAPI's parameters). Clients are urllib.request, httpx, or requests. Always set a timeout on outgoing calls. Always treat the body as untrusted until you parse and validate it.
Status codes tell the client what kind of answer it is. 2xx success, 3xx redirect, 4xx the client was wrong, 5xx the server was wrong. Do not return 200 with {"error": ...} if you can return 4xx; clients and caches look at the status first.
Code Examples
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
body = b'{"ok": true}\n'
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)from urllib.request import urlopen, Request
req = Request("https://example.com", headers={"Accept": "text/html"}, method="GET")
# with urlopen(req, timeout=5) as resp:
# print(resp.status, resp.read()[:20])Common Gotchas
No timeout on a client call
a hung peer ties up a thread or a task forever. Set `timeout`.
Trusting `Content-Length` or headers blindly
they are client-controlled. Cap the size you read.
GET with a body
allowed by some stacks, ignored by others. Put filters in the query or use POST.
`http.client` is low-level
most apps should use `requests` or `httpx`.