← Back to FastAPI, page 3

fastapi-0055 · Easy fresher

When do you use the Request object in FastAPI, and what can you read from it (client address, URL, headers, raw body, app state)?

Declare a parameter typed as starlette Request to get the raw request: URL parts, client (host and port), headers, cookies, query parameters, path params, the raw body via await request.body() or JSON via await request.json(), plus request.app, request.state and request.scope. Use it for things the typed parameters cannot express; otherwise prefer typed Query, Header and body models, which validate input and appear in the OpenAPI docs.

Full answer

FastAPI passes a Request when a parameter is annotated with it. It is the Starlette object, so everything in the ASGI request is available:

  • request.method, request.url (with .path, .query_params, .scheme), request.base_url, request.url_for("name", ...).
  • request.client.host and .port (the TCP peer; behind a reverse proxy this is the proxy unless you run Uvicorn with --proxy-headers and trusted forwarded IPs).
  • request.headers (case-insensitive), request.cookies, request.query_params, request.path_params.
  • await request.body() (bytes), await request.json(), await request.form(), request.stream() for chunked reading.
  • request.app (the FastAPI instance, often with app.state holding shared clients) and request.state (a per-request namespace that middleware and dependencies can fill).
  • request.scope: the raw ASGI dictionary (route, root_path, server).

When to prefer typed parameters: they validate and document themselves. Parameters like x_token: Annotated[str, Header()] show up in /docs, while headers read from Request do not, and they are not validated.

Good uses of Request: raw body for webhook signature checks (the signature covers exact bytes), custom content types, client IP for logging, url_for to build links, and reading request.state set by middleware.

Cautions: the body can be read only once unless cached (await request.body() caches it in Starlette, but a dependency consuming request.stream() will exhaust it), and reading the whole body of a large upload into memory is risky; stream it instead.

python
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient

app = FastAPI()
app.state.service_name = "campus-api"


@app.middleware("http")
async def add_state(request: Request, call_next):
    request.state.request_source = request.headers.get("x-source", "unknown")
    return await call_next(request)


@app.post("/inspect/{item_id}")
async def inspect(item_id: int, request: Request):
    raw = await request.body()
    return {
        "method": request.method,
        "path": request.url.path,
        "query": dict(request.query_params),
        "path_params": request.path_params,
        "agent": request.headers.get("user-agent"),
        "client_is_set": request.client is not None,
        "raw_bytes": len(raw),
        "json": await request.json(),
        "service": request.app.state.service_name,
        "source": request.state.request_source,
        "url_for": request.url_for("inspect", item_id=7).path,
    }


c = TestClient(app)
print(c.post("/inspect/3?verbose=1", json={"a": 1}, headers={"user-agent": "demo", "x-source": "mobile"}).json())

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'method': 'POST', 'path': '/inspect/3', 'query': {'verbose': '1'}, 'path_params': {'item_id': '3'}, 'agent': 'demo', 'client_is_set': True, 'raw_bytes': 7, 'json': {'a': 1}, 'service': 'campus-api', 'source': 'mobile', 'url_for': '/inspect/7'}

Key points

  • A parameter typed as Request gives the raw Starlette request
  • client.host is the TCP peer; proxies need forwarded headers configured
  • request.state and app.state share per-request and per-app data
  • Raw body is needed for signature verification
  • Typed parameters validate and appear in docs; Request does not

Common mistakes

  • Reading headers through Request and losing validation and docs
  • Trusting client.host behind a proxy without configuring forwarded headers
  • Loading a huge body with request.body() instead of streaming
  • Assuming the raw body is available after a dependency already consumed the stream

Follow-ups

  • How do you get the real client IP behind a load balancer?
  • What is the difference between app.state and request.state?
  • Why does webhook verification need the raw body?

Tips

  • List what Request exposes
  • Contrast with typed parameters
  • Mention proxies