Skip to main content

Request class

The Request object provides access to incoming HTTP request data. You can inject it into your route handlers by adding a request parameter.
from fastrapi import FastrAPI

app = FastrAPI()

@app.get("/info")
def get_info(request):
    return {
        "client": request.client,
        "headers": dict(request.headers)
    }

Constructor

Create a Request object from ASGI scope.
from fastrapi import Request

request = Request(scope, receive, send)

Parameters

scope
dict
required
The ASGI scope dictionary containing request metadata
receive
callable
default:"None"
The ASGI receive callable for reading request body
send
callable
default:"None"
The ASGI send callable for sending responses

Properties

client

Get client connection information.
@app.get("/client-info")
def client_info(request):
    return {
        "client": request.client,
        "host": request.client[0] if request.client else None,
        "port": request.client[1] if request.client else None
    }
client
tuple | None
A tuple of (host, port) for the client connection, or None if not available

headers

Access request headers.
@app.get("/headers")
def get_headers(request):
    user_agent = dict(request.headers).get(b'user-agent', b'').decode()
    return {
        "user_agent": user_agent,
        "all_headers": {k.decode(): v.decode() for k, v in request.headers}
    }
headers
list[tuple[bytes, bytes]]
A list of header tuples, where each tuple is (name, value) as bytes

path_params

Get path parameters extracted from the URL.
@app.get("/users/{user_id}/posts/{post_id}")
def get_post(request):
    return {
        "user_id": request.path_params.get("user_id"),
        "post_id": request.path_params.get("post_id")
    }
path_params
dict
Dictionary of path parameters extracted from the URL pattern

query_params

Get query string parameters.
@app.get("/search")
def search(request):
    query = request.query_params.get("q", "")
    page = int(request.query_params.get("page", 1))
    return {
        "query": query,
        "page": page,
        "results": []
    }
query_params
dict
Dictionary of query string parameters from the URL

cookies

Access request cookies.
@app.get("/session")
def get_session(request):
    session_id = request.cookies.get("session_id")
    return {
        "session_id": session_id,
        "authenticated": session_id is not None
    }
cookies
dict
Dictionary of cookies sent with the request

state

Access application state attached to the request.
@app.get("/state-info")
def state_info(request):
    # Middleware can attach data to request.state
    return {
        "user": getattr(request.state, "user", None),
        "request_id": getattr(request.state, "request_id", None)
    }
state
SimpleNamespace
A namespace object for storing arbitrary state data on the request

scope

Access the raw ASGI scope dictionary.
@app.get("/scope")
def get_scope(request):
    return {
        "method": request.scope.get("method"),
        "path": request.scope.get("path"),
        "type": request.scope.get("type")
    }
scope
dict
The ASGI scope dictionary containing all request metadata

Methods

body()

Read the request body as bytes. This is an async method.
@app.post("/upload")
async def upload_file(request):
    body_bytes = await request.body()
    return {
        "size": len(body_bytes),
        "received": True
    }
body
bytes
The raw request body as bytes
The request body can only be read once. Subsequent calls will raise a RuntimeError.

json()

Parse the request body as JSON. This is an async method.
@app.post("/data")
async def receive_data(request):
    data = await request.json()
    return {
        "received": data,
        "keys": list(data.keys())
    }
json
dict | list
The parsed JSON data from the request body

Complete example

from fastrapi import FastrAPI
from pydantic import BaseModel

app = FastrAPI()

class Item(BaseModel):
    name: str
    description: str

@app.get("/request-info")
def request_info(request):
    headers_dict = {k.decode(): v.decode() for k, v in request.headers}
    
    return {
        "client": request.client,
        "path_params": request.path_params,
        "query_params": request.query_params,
        "cookies": request.cookies,
        "user_agent": headers_dict.get("user-agent", "Unknown")
    }

@app.post("/items")
async def create_item(request):
    # Parse JSON body manually
    data = await request.json()
    
    return {
        "item": data,
        "client": request.client[0] if request.client else None
    }

@app.get("/search")
def search(request):
    query = request.query_params.get("q", "")
    limit = int(request.query_params.get("limit", 10))
    
    return {
        "query": query,
        "limit": limit,
        "results": []
    }

@app.get("/users/{user_id}")
def get_user(request):
    user_id = request.path_params.get("user_id")
    
    return {
        "user_id": user_id,
        "name": "John Doe"
    }

if __name__ == "__main__":
    app.serve("127.0.0.1", 8080)

Using with Pydantic models

While you can access the request object directly, FastrAPI automatically parses request data into Pydantic models:
from pydantic import BaseModel

class User(BaseModel):
    name: str
    email: str

@app.post("/users")
def create_user(user: User, request):
    # Pydantic model is automatically parsed
    # Request object is available for additional data
    return {
        "user": user.dict(),
        "client_ip": request.client[0] if request.client else None
    }

Build docs developers (and LLMs) love