On this page
  1. http
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Reusing a Persistent HTTPS Connection with http.client
  7. 2. Minimal Local JSON Server with http.server (Dev / Testing Only)
  8. Gotchas & Boundaries
  9. Classes & Objects

http

Prev: html | Up: stdlib_module | Next: idlelib
Rel: email, json, mailbox, mimetypes, base64
Ref: docs.python.org โ€” http
Tags: #public #python3 #stdlib


Import

import http

Overview

Package holding Python's HTTP protocol primitives: http.HTTPStatus and http.HTTPMethod enums, http.client (low-level persistent HTTP/1.1 connections), http.server (development/local HTTP servers), and http.cookies. Reach for HTTPStatus / HTTPMethod everywhere you deal with status codes or verbs; use http.client when you need explicit connection reuse over raw urllib.request.

Quick Start

from http import HTTPMethod, HTTPStatus

assert HTTPStatus.OK == 200
assert HTTPStatus.NOT_FOUND.phrase == "Not Found"
assert HTTPStatus.CREATED.is_success
assert HTTPMethod.GET == "GET"

Implementation Walkthrough

1. Reusing a Persistent HTTPS Connection with http.client

Unlike urllib.request.urlopen(), HTTPSConnection keeps the TCP/TLS socket open across requests to the same host:

import http.client
import ssl

ctx = ssl.create_default_context()
conn = http.client.HTTPSConnection("example.com", timeout=10, context=ctx)
try:
    conn.request("GET", "/", headers={"Host": "example.com"})
    resp = conn.getresponse()
    body = resp.read(65_536)
    status = resp.status
finally:
    conn.close()

2. Minimal Local JSON Server with http.server (Dev / Testing Only)

from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json

class HealthHandler(BaseHTTPRequestHandler):
    def do_GET(self) -> None:
        payload = json.dumps({"status": "ok"}).encode("utf-8")
        self.send_response(HTTPStatus.OK)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

# server = ThreadingHTTPServer(("127.0.0.1", 8000), HealthHandler)

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes