HTTP headers
suggest changeEvery HTTP request and response carries headers: Name: value lines sent before the body. They describe the body (Content-Type, Content-Length), negotiate formats (Accept, Accept-Encoding), carry credentials (Authorization, Cookie), control caching (Cache-Control, ETag) and much more.
This is what a request and its response look like on the wire:
GET /api/users/42 HTTP/1.1
Host: api.example.com
User-Agent: my-app/1.0
Accept: application/json
Authorization: Bearer eyJhbGciOi...
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 27
Cache-Control: private, max-age=60
ETag: "a1b2c3"
{"id": 42, "name": "Ann"}
Rules worth remembering:
- Header names are case-insensitive.
content-type,Content-TypeandCONTENT-TYPEare the same header. HTTP/2 and HTTP/3 send them in lowercase. Never use a plaindictlookup on names you didn't write yourself. - A header can appear more than once. For most headers, repeated values mean the same as one header with the values joined by
,.Set-Cookieis the exception: you can't join it, so each cookie has to stay a separate header. - Values are text. You have to convert numbers to strings yourself, and a value can never contain a newline.
- Custom headers used to start with
X-(X-Request-Id). The prefix is no longer recommended for new headers, but it's still everywhere.
Common headers
| Header | Direction | Purpose |
|---|---|---|
Host |
request | Target host name and port (required in HTTP/1.1) |
User-Agent |
request | Identifies the client software |
Accept |
request | Media types the client wants, with q= preferences |
Accept-Encoding |
request | Compression the client understands (gzip, br, zstd) |
Authorization |
request | Credentials, e.g. Bearer <token> or Basic <base64> |
Cookie / Set-Cookie |
request / response | Cookies the client sends back / the server sets |
If-None-Match / ETag |
request / response | Conditional requests and cache validation |
Content-Type |
both | Media type of the body, e.g. application/json |
Content-Length |
both | Size of the body in bytes |
Content-Disposition |
response | attachment; filename="..." makes the browser download the body |
Cache-Control |
both | Caching rules (no-store, max-age=60, ...) |
Location |
response | Target of a redirect or a newly created resource |
Retry-After |
response | How long to wait after a 429 or 503 |
Link |
response | Related URLs, often used for pagination |
A local echo server for the examples
To get repeatable output without depending on a public website, the client examples talk to a small server built on http.server. It returns the request headers it received as JSON and sends back a few response headers, including two Set-Cookie headers:
# echo_server.py
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class EchoHandler(BaseHTTPRequestHandler):
def do_GET(self):
# self.headers is an http.client.HTTPMessage
body = json.dumps(dict(self.headers.items()), indent=2).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.send_header("Set-Cookie", "a=1; Path=/")
self.send_header("Set-Cookie", "b=2; Path=/")
self.send_header("X-Request-Id", "abc123")
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args):
pass # keep the output quiet
def start(port=8000):
server = ThreadingHTTPServer(("127.0.0.1", port), EchoHandler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
On the server side, self.headers holds the request headers and send_header() writes one response header. Calling it twice with the same name sends two headers. See Basic handling of GET POST PUT using BaseHTTPRequestHandler for more about this module.
Sending and reading headers with requests
requests (pip install requests) takes request headers as a dict in the headers argument. response.headers is a CaseInsensitiveDict:
import requests
import echo_server
echo_server.start()
r = requests.get(
"http://127.0.0.1:8000/",
headers={"User-Agent": "my-app/1.0", "Accept": "application/json", "X-Trace": "t-42"},
)
print(r.status_code)
print(r.headers["content-type"]) # lookup is case-insensitive
print(r.headers.get("Content-Length"))
print(r.headers.get("X-Missing", "default"))
print(r.headers["Set-Cookie"]) # repeated headers are joined
print(r.json()) # what the server received
200
application/json; charset=utf-8
181
default
a=1; Path=/, b=2; Path=/
{'Host': '127.0.0.1:8000', 'User-Agent': 'my-app/1.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': 'application/json', 'Connection': 'keep-alive', 'X-Trace': 't-42'}
requests added Host, Accept-Encoding and Connection on its own. Your User-Agent and Accept replaced its defaults (python-requests/2.x and */*). The Accept-Encoding value depends on which optional compression packages you have installed.
Note that r.headers["Set-Cookie"] joined the two cookies with , . Since cookie values can contain commas (in Expires=Sat, 17 Oct 2026 ...), splitting that string isn't reliable. Read cookies from r.cookies, or get the separate values from the underlying urllib3 response.
Session headers and removing default headers
Headers set on a Session are sent with every request made through it. Per-request headers are merged on top, and setting a header to None removes it for that one request:
import requests
import echo_server
echo_server.start()
session = requests.Session()
session.headers.update({"User-Agent": "my-app/1.0", "Authorization": "Bearer s3cret"})
# per-request headers are merged with session headers;
# a value of None removes a header for this request
r = session.get("http://127.0.0.1:8000/",
headers={"X-Trace": "t-1", "Accept-Encoding": None})
print(r.request.headers) # what was actually sent
print(r.json()["Accept-Encoding"])
# Set-Cookie is better read via the cookie jar or the raw urllib3 headers
print(r.cookies.get_dict())
print(r.raw.headers.getlist("Set-Cookie"))
{'User-Agent': 'my-app/1.0', 'Accept': '*/*', 'Connection': 'keep-alive', 'Authorization': 'Bearer s3cret', 'X-Trace': 't-1'}
identity
{'a': '1', 'b': '2'}
['a=1; Path=/', 'b=2; Path=/']
r.request.headers shows exactly what requests prepared, which helps when debugging. Even after you remove Accept-Encoding, the server still gets Accept-Encoding: identity: the lower-level http.client adds it when no such header is present.
urllib.request (standard library)
urllib.request.Request takes headers in its constructor or through add_header(). The response's headers attribute is an http.client.HTTPMessage, which comes from the email package and has helpers for parsing values:
import json
import urllib.request
import echo_server
echo_server.start()
req = urllib.request.Request(
"http://127.0.0.1:8000/",
headers={"User-Agent": "my-app/1.0", "Accept": "application/json"},
)
req.add_header("X-Trace", "t-7")
print(req.header_items())
with urllib.request.urlopen(req) as resp:
h = resp.headers # http.client.HTTPMessage
print(type(h).__name__)
print(h["content-type"])
print(h.get_content_type(), h.get_content_charset())
print(h.get_all("Set-Cookie"))
print(h.get("X-Missing"))
body = resp.read().decode(h.get_content_charset("utf-8"))
print(json.loads(body))
[('User-agent', 'my-app/1.0'), ('Accept', 'application/json'), ('X-trace', 't-7')]
HTTPMessage
application/json; charset=utf-8
application/json utf-8
['a=1; Path=/', 'b=2; Path=/']
None
{'Accept-Encoding': 'identity', 'Host': '127.0.0.1:8000', 'User-Agent': 'my-app/1.0', 'Accept': 'application/json', 'X-Trace': 't-7', 'Connection': 'close'}
Request stores names with str.capitalize() (User-agent), so use req.get_header("User-agent") or req.has_header(...) with that spelling. On the wire they are title-cased again. HTTPMessage.get_all() returns every value of a repeated header as a list, and get_content_charset() pulls the charset parameter out of Content-Type, so you can decode the body correctly.
See Simple web content download with urllib.request for more on urlopen.
httpx
httpx (pip install httpx) works like requests and also supports async. Its Headers type is case-insensitive and keeps repeated headers as a multi-dict:
import httpx
import echo_server
echo_server.start()
with httpx.Client(headers={"User-Agent": "my-app/1.0"}) as client:
r = client.get("http://127.0.0.1:8000/", headers={"X-Trace": "t-9"})
print(r.headers["CONTENT-TYPE"])
print(r.headers.get_list("set-cookie"))
print(r.headers.multi_items()[:3])
print(r.request.headers)
h = httpx.Headers([("Accept", "text/html"), ("Accept", "application/json")])
print(h["accept"], h.get_list("accept"))
application/json; charset=utf-8
['a=1; Path=/', 'b=2; Path=/']
[('server', 'BaseHTTP/0.6 Python/3.13.15'), ('date', 'Sat, 17 Oct 2026 17:27:14 GMT'), ('content-type', 'application/json; charset=utf-8')]
Headers({'host': '127.0.0.1:8000', 'accept': '*/*', 'accept-encoding': 'gzip, deflate', 'connection': 'keep-alive', 'user-agent': 'my-app/1.0', 'x-trace': 't-9'})
text/html, application/json ['text/html', 'application/json']
Indexing with [] joins repeated values with , . get_list() returns them separately. httpx lowercases all names, matching HTTP/2.
Parsing header values
Many header values have structure: a main value followed by ; name=value parameters, comma-separated lists, q= weights or dates. Don't parse them with ad-hoc split() calls. Quoted strings and odd spacing will break that code.
Content-Type and Content-Disposition
The standard library's email.message.Message parses and builds MIME-style parameters correctly, quoted values and non-ASCII filenames included:
from email.message import Message
def parse_content_type(value):
msg = Message()
msg["Content-Type"] = value
return msg.get_content_type(), dict(msg.get_params()[1:])
print(parse_content_type("text/html; charset=ISO-8859-1"))
print(parse_content_type('multipart/form-data; boundary="----abc123"'))
print(parse_content_type("Application/JSON"))
# building a header value with parameters
msg = Message()
msg.add_header("Content-Disposition", "attachment", filename="report 2026.pdf")
print(msg["Content-Disposition"])
msg2 = Message()
msg2.add_header("Content-Disposition", "attachment", filename=("utf-8", "", "zażółć.txt"))
print(msg2["Content-Disposition"])
('text/html', {'charset': 'ISO-8859-1'})
('multipart/form-data', {'boundary': '----abc123'})
('application/json', {})
attachment; filename="report 2026.pdf"
attachment; filename*=utf-8''za%C5%BC%C3%B3%C5%82%C4%87.txt
get_content_type() lowercases the media type. For non-ASCII filenames, the (charset, language, value) tuple produces the RFC 2231 filename*= form that browsers understand.
Dates and Retry-After
HTTP dates always use the format Sat, 17 Oct 2026 14:30:00 GMT. email.utils converts between that format and datetime:
from datetime import datetime, timezone
from email.utils import format_datetime, parsedate_to_datetime
dt = datetime(2026, 10, 17, 14, 30, 0, tzinfo=timezone.utc)
value = format_datetime(dt, usegmt=True)
print(value)
parsed = parsedate_to_datetime("Sat, 17 Oct 2026 14:30:00 GMT")
print(parsed, parsed == dt)
def retry_after_seconds(value, now=None):
"""Retry-After is either a number of seconds or an HTTP date."""
if value.isdigit():
return int(value)
now = now or datetime.now(timezone.utc)
return max(0, int((parsedate_to_datetime(value) - now).total_seconds()))
print(retry_after_seconds("120"))
print(retry_after_seconds("Sat, 17 Oct 2026 14:32:00 GMT", now=dt))
Sat, 17 Oct 2026 14:30:00 GMT
2026-10-17 14:30:00+00:00 True
120
120
format_datetime(..., usegmt=True) requires an aware datetime in UTC.
Accept, Cache-Control, lists and Link
Werkzeug (installed with Flask) ships well-tested parsers that you can use outside Flask too. requests can parse the Link header that many APIs, such as GitHub's, use for pagination:
from werkzeug.http import (parse_accept_header, parse_options_header,
parse_cache_control_header, parse_list_header)
from werkzeug.datastructures import MIMEAccept, ResponseCacheControl
import requests.utils
accept = parse_accept_header("text/html;q=0.9, application/json, */*;q=0.1", MIMEAccept)
print(list(accept))
print(accept.best_match(["text/html", "application/json"]))
print(accept.quality("image/png"))
print(parse_options_header('form-data; name="file"; filename="a b.txt"'))
cc = parse_cache_control_header("public, max-age=3600, must-revalidate",
cls=ResponseCacheControl)
print(cc.public, cc.max_age, cc.must_revalidate, cc.no_store)
print(parse_list_header('gzip, br, "x, y"'))
link = ('<https://api.example.com/items?page=3>; rel="next", '
'<https://api.example.com/items?page=10>; rel="last"')
print(requests.utils.parse_header_links(link))
[('application/json', 1), ('text/html', 0.9), ('*/*', 0.1)]
application/json
0.1
('form-data', {'name': 'file', 'filename': 'a b.txt'})
True 3600 True False
['gzip', 'br', 'x, y']
[{'url': 'https://api.example.com/items?page=3', 'rel': 'next'}, {'url': 'https://api.example.com/items?page=10', 'rel': 'last'}]
On a requests response you don't need to call parse_header_links yourself: r.links["next"]["url"] is already parsed.
Headers in Flask
In Flask, request.headers is a case-insensitive Werkzeug Headers object. Common headers also have parsed properties such as request.accept_mimetypes, request.authorization, request.if_none_match and request.content_type. You set response headers by returning a (body, status, headers) tuple or by changing response.headers:
from flask import Flask, request, jsonify, make_response
app = Flask(__name__)
@app.get("/info")
def info():
auth = request.authorization # parsed Authorization header
return {
"user_agent": request.headers.get("User-Agent"),
"trace": request.headers.get("X-Trace", "none"),
"best": request.accept_mimetypes.best_match(["application/json", "text/html"]),
"auth_type": auth.type if auth else None,
"token": auth.token if auth else None,
}
@app.get("/download")
def download():
# a tuple of (body, status, headers)
return "id,name\n1,Ann\n", 200, {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": 'attachment; filename="users.csv"',
}
@app.get("/custom")
def custom():
resp = make_response(jsonify(ok=True))
resp.headers["X-Request-Id"] = "abc123"
resp.headers.add("Link", '</custom?page=2>; rel="next"')
resp.headers.add("Link", '</custom?page=9>; rel="last"')
resp.cache_control.max_age = 60
resp.cache_control.public = True
return resp
client = app.test_client()
r = client.get("/info", headers=[("User-Agent", "curl/8.10"), ("x-trace", "t-1"),
("Accept", "text/html;q=0.5, application/json"),
("Authorization", "Bearer s3cret")])
print(r.json)
r = client.get("/download")
print(r.headers["Content-Type"], "|", r.headers["Content-Disposition"])
r = client.get("/custom")
print(r.headers.getlist("Link"))
print(r.headers["Cache-Control"], r.headers["X-Request-Id"])
{'auth_type': 'bearer', 'best': 'application/json', 'token': 's3cret', 'trace': 't-1', 'user_agent': 'curl/8.10'}
text/csv; charset=utf-8 | attachment; filename="users.csv"
['</custom?page=2>; rel="next"', '</custom?page=9>; rel="last"']
max-age=60, public abc123
headers["X"] = v replaces any existing value, while headers.add("X", v) appends another header with the same name. resp.cache_control builds the Cache-Control header from attributes. For more on the request object, see The Request Object. To read a bearer token and verify it, see JWT.
To add the same headers to every response, use an after_request hook or middleware instead of repeating code in each view. The HTTP middleware article shows how, including a middleware that adds security headers. CORS covers the Access-Control-* headers in detail.
Conditional requests with ETag
An ETag is a version identifier for a response. The client sends it back in If-None-Match, and if nothing changed the server answers 304 Not Modified with no body. That saves bandwidth and lets clients cache safely. Flask does the work for you:
from flask import Flask, request, make_response
app = Flask(__name__)
ARTICLE = {"title": "HTTP headers", "version": 3}
@app.get("/article")
def article():
resp = make_response(ARTICLE)
resp.add_etag() # ETag = hash of the body
resp.cache_control.no_cache = True # cache, but revalidate every time
return resp.make_conditional(request)
client = app.test_client()
r1 = client.get("/article")
etag = r1.headers["ETag"]
print(r1.status_code, etag, len(r1.data))
r2 = client.get("/article", headers={"If-None-Match": etag})
print(r2.status_code, len(r2.data))
ARTICLE["version"] = 4
r3 = client.get("/article", headers={"If-None-Match": etag})
print(r3.status_code, r3.headers["ETag"] != etag)
200 "4d76fb8c00fea511fbf3e84380b99e25d35e1a11" 37
304 0
200 True
Hashing the body still means generating it. If producing the body is the expensive part, compute the ETag from something cheaper, such as a row's version number or updated_at, and compare it against request.if_none_match before rendering. The Caching article covers caching on the application side.
Headers in FastAPI
FastAPI declares headers as function parameters with Header(). A parameter name like x_trace is converted to the header x-trace (underscores become hyphens, and matching ignores case). A list[str] parameter collects every value of a repeated header. For anything else, use request.headers, which is a case-insensitive multi-dict. You set response headers through an injected Response or pass headers= to a response class:
from typing import Annotated
from fastapi import FastAPI, Header, Request, Response
from fastapi.responses import PlainTextResponse
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/info")
def info(
user_agent: Annotated[str | None, Header()] = None, # reads User-Agent
x_trace: Annotated[str, Header()] = "none", # reads X-Trace
x_tag: Annotated[list[str], Header()] = [], # repeated header
):
return {"user_agent": user_agent, "trace": x_trace, "tags": x_tag}
@app.get("/raw")
def raw(request: Request):
return {"host": request.headers["host"],
"accept": request.headers.get("accept"),
"count": len(request.headers.getlist("x-tag"))}
@app.get("/custom")
def custom(response: Response):
response.headers["X-Request-Id"] = "abc123"
response.headers["Cache-Control"] = "private, max-age=30"
return {"ok": True}
@app.get("/download")
def download():
return PlainTextResponse("id,name\n1,Ann\n", headers={
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": 'attachment; filename="users.csv"',
})
client = TestClient(app)
headers = [("User-Agent", "curl/8.10"), ("X-Trace", "t-1"),
("X-Tag", "a"), ("X-Tag", "b")]
print(client.get("/info", headers=headers).json())
print(client.get("/raw", headers=headers).json())
r = client.get("/custom")
print(r.headers["x-request-id"], r.headers["cache-control"])
r = client.get("/download")
print(r.headers["content-type"], "|", r.headers["content-disposition"])
{'user_agent': 'curl/8.10', 'trace': 't-1', 'tags': ['a', 'b']}
{'host': 'testserver', 'accept': '*/*', 'count': 2}
abc123 private, max-age=30
text/csv; charset=utf-8 | attachment; filename="users.csv"
A required header is declared without a default (x_api_key: Annotated[str, Header()]). If it's missing, FastAPI answers 422 before your function runs. If you really need underscores in a header name, use Header(convert_underscores=False), but read the pitfalls below first.
Headers in raw WSGI
At the WSGI level, request headers are in the environ dict. A header named X-Trace becomes the key HTTP_X_TRACE: the name is upper-cased, - turns into _, and HTTP_ is prepended. Content-Type and Content-Length are special and appear as CONTENT_TYPE and CONTENT_LENGTH, without the prefix. Response headers are a list of (name, value) tuples passed to start_response:
from wsgiref.util import setup_testing_defaults
def app(environ, start_response):
trace = environ.get("HTTP_X_TRACE", "none")
ctype = environ.get("CONTENT_TYPE", "")
body = f"trace={trace} content-type={ctype}\n".encode()
start_response("200 OK", [("Content-Type", "text/plain"),
("Content-Length", str(len(body)))])
return [body]
environ = {"HTTP_X_TRACE": "t-5", "CONTENT_TYPE": "application/json"}
setup_testing_defaults(environ)
print(b"".join(app(environ, lambda status, headers: None)))
b'trace=t-5 content-type=application/json\n'
See Web Server Gateway Interface WSGI for the interface, and HTTP middleware for wrapping apps to read and add headers in one place.
Pitfalls
Header injection. If user input ends up in a header value and contains \r\n, an attacker can add headers of their own (Set-Cookie: admin=1) or even a body. Modern libraries refuse such values:
import requests
from flask import Flask
name = "report.pdf\r\nSet-Cookie: admin=1"
try:
requests.get("http://127.0.0.1:8000/", headers={"X-File": name})
except requests.exceptions.InvalidHeader as e:
print("requests:", e)
try:
requests.get("http://127.0.0.1:8000/", headers={"X-Count": 5})
except requests.exceptions.InvalidHeader as e:
print("requests:", e)
requests: Invalid leading whitespace, reserved character(s), or return character(s) in header value: 'report.pdf\r\nSet-Cookie: admin=1'
requests: Header part (5) from ('X-Count', 5) must be of type str or bytes, not <class 'int'>
Werkzeug raises ValueError: Header values must not contain newline characters., which Flask turns into a 500. Being refused is better than being injected, but validate or sanitize user input (filenames especially) before it gets that far. Build parameterized values with Message.add_header() as shown above, not with f-strings. The second error shows another common slip: header values must be strings, so write str(5).
Underscores in names. WSGI maps both X-Api-Key and X_Api_Key to HTTP_X_API_KEY. An attacker could use the underscore form to spoof a header that your proxy sets. That's why nginx drops headers containing underscores by default and recent Gunicorn versions drop them too. Stick to hyphens.
Case. Don't compare header names with ==, and don't copy headers into a plain dict and then look them up. Use the case-insensitive containers the libraries give you.
Repeated headers. headers["X"] either joins the values or returns only one of them, depending on the library. Use get_all() / getlist() / get_list() when a header may repeat, and always for Set-Cookie.
Trusting client headers. Anything in a request header can be forged: User-Agent, Referer, X-Forwarded-For, Host. Only trust X-Forwarded-* when a reverse proxy you control sets them, for example via Werkzeug's ProxyFix with the exact number of proxies.
Size limits. Servers limit header size (often 8 KB per line, or for all headers together) and reply 431 or 400 when it's exceeded. Large JWTs or many cookies can hit this limit.
Content-Length. If you set it yourself, it must be the length in bytes of the encoded body, not len() of the str. Frameworks compute it for you, so only set it in low-level code.
Summary
| Task | Code |
|---|---|
| Send headers (requests) | requests.get(url, headers={"Accept": "application/json"}) |
| Default headers for all requests | session.headers.update({...}) |
| Remove a default header | headers={"Accept-Encoding": None} |
| Read a response header | r.headers["content-type"] (case-insensitive) |
| All values of a repeated header | r.raw.headers.getlist(name), msg.get_all(name), httpx_headers.get_list(name) |
| See what was sent | r.request.headers |
| Charset from Content-Type | resp.headers.get_content_charset() (urllib) |
| Parse parameters | email.message.Message, werkzeug.http.parse_options_header |
| HTTP date | email.utils.format_datetime(dt, usegmt=True) / parsedate_to_datetime(s) |
| Pagination links | r.links["next"]["url"] |
| Flask: read | request.headers.get("X-Trace"), request.accept_mimetypes, request.authorization |
| Flask: write | return body, 200, {"X": "v"} or resp.headers["X"] = "v" |
| Flask: ETag / 304 | resp.add_etag(); resp.make_conditional(request) |
| FastAPI: read | x_trace: Annotated[str, Header()] |
| FastAPI: write | response: Response then response.headers["X"] = "v" |
| WSGI: read | environ["HTTP_X_TRACE"], environ["CONTENT_TYPE"] |