Accessing the Raw Request Object in FastAPI
Think of it as dropping to a lower level. Instead of FastAPI handing you validated data, you grab the raw Starlette HTTP request yourself. Use this for data not covered by standard declarations, like a client's IP.
WHY IT EXISTS: FastAPI excels at parsing requests based on type hints for path parameters, headers, and bodies. But sometimes, you need information that doesn't fit these categories, like the client's IP address, or you need to process the request in a non-standard way. Direct access provides an escape hatch for these scenarios.
THE MENTAL MODEL: Accessing the Request object is like opening the engine compartment of your car. Normally, you use the steering wheel and pedals (FastAPI's declarative parameters). But for special tasks, like checking the raw request body or getting the client's IP, you need to work directly with the underlying machinery—the Starlette Request object.
HOW IT WORKS: You can declare a dependency on the Request object by type-hinting a parameter in your path operation function or a dependency: def my_endpoint(request: Request):. FastAPI will inject the current request object. You can then access its attributes, like request.client.host for the IP address or await request.body() to get the raw body bytes.
WHEN TO USE IT: Use this for specific, advanced use cases. A common one is logging the client's IP address. Another is when you need to implement custom request body parsing logic, perhaps for a non-JSON format that FastAPI doesn't handle natively, or if you need to read the body more than once.
WHEN NOT TO USE IT: Avoid this for standard data extraction. If you just need a query parameter, a header, or a JSON body, stick to FastAPI's declarative syntax (Query(), Header(), Pydantic models). Using the Request object for these tasks re-introduces boilerplate and disables automatic validation and documentation.
ONE CANONICAL EXAMPLE: To get a client's IP address for logging, you would define your endpoint like this: from fastapi import FastAPI, Request; app = FastAPI(); @app.get("/") async def get_ip(request: Request): client_host = request.client.host; return {"client_host": client_host}. This injects the Request object and allows you to access its client attribute.
Read the original → fastapi.tiangolo.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.