Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python FastAPI Headers, Cookies, Forms, and File Uploads

Learn how to read headers and cookies, handle form data, and process file uploads in FastAPI with typed parameters and code examples.

~5 min readPython
#FastAPI#Python#HTTP Headers#File Uploads
Illustration of FastAPI request handling showing a document being uploaded through a gateway with header and cookie labels

FastAPI provides typed parameters for headers, cookies, form fields, and uploaded files. They all use the same dependency-injection pattern: import the helper for the request data you need, declare a parameter, and FastAPI supplies the value from the incoming request. This article explains the syntax and behavior for each type, and shows how to combine them in one endpoint.

Reading Headers with Header() and request.headers

When you declare a parameter with Header(), FastAPI maps your Python parameter name to the incoming HTTP header. It converts underscores to hyphens and compares header names case-insensitively. For example, a parameter named x_token reads the X-Token header:

python
from fastapi import FastAPI, Header app = FastAPI() @app.get("/items") def read_items(x_token: str = Header(...)): return {"token": x_token}

Inside the endpoint, the value is available as x_token. Header() also applies normal type validation for the parameter.

If you need raw access to headers without conversion, use the Request object directly:

python
from fastapi import FastAPI, Request app = FastAPI() @app.get("/items") def read_items(request: Request): return {"user_agent": request.headers.get("user-agent")}

request.headers is a Headers object that behaves like a case-insensitive dictionary. Use Header() when you want automatic name mapping and validation, and request.headers when you need dynamic header names or want to iterate over all headers. The two approaches are not mutually exclusive; a single endpoint can use both.

Reading and Setting Cookies

Cookies are read with the Cookie() function, which works similarly to Header():

python
from fastapi import FastAPI, Cookie app = FastAPI() @app.get("/profile") def read_profile(session_id: str = Cookie(default=None)): return {"session_id": session_id}

FastAPI reads the cookie from the Cookie request header and passes the value to the parameter. The default=None makes the cookie optional, which is important because not every client sends a session cookie. Without a default, FastAPI returns a 422 validation error when the cookie is missing.

To set a cookie in a response, declare a Response parameter and call set_cookie:

python
from fastapi import FastAPI, Response app = FastAPI() @app.post("/login") def login(response: Response): response.set_cookie( key="session_id", value="abc123", httponly=True, secure=True, samesite="lax", max_age=3600, path="/" ) return {"message": "logged in"}

The set_cookie method accepts the standard cookie attributes: httponly, secure, samesite, max_age, path, and domain. When you inject Response as a parameter, FastAPI populates it with the response that will be sent, and any modifications you make are merged into the final response. This is the simplest way to set cookies while still returning a normal JSON body.

Handling Form Data with Form()

Form data arrives in the request body as application/x-www-form-urlencoded or multipart/form-data. If you declare Form() or File() parameters, install python-multipart:

bash
pip install python-multipart

Declare form fields with Form():

python
from fastapi import FastAPI, Form app = FastAPI() @app.post("/submit") def submit_form(name: str = Form(...), email: str = Form(...)): return {"name": name, "email": email}

Unlike JSON body parameters, form fields must be declared with Form() explicitly. FastAPI does not infer form fields from plain type annotations; a bare name: str parameter is treated as a query parameter, which causes a 422 error when the client sends a form body. Each Form() parameter maps to one field in the form body, and the same type validation rules apply as for query parameters.

Handling File Uploads with UploadFile

File uploads use File() together with the UploadFile type:

python
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/upload") async def upload_file(file: UploadFile = File(...)): contents = await file.read() return {"filename": file.filename, "size": len(contents)}

UploadFile provides an async interface with read(), write(), seek(), and close(). The file is stored in a SpooledTemporaryFile, which keeps small files in memory and spills larger ones to disk automatically. Keep in mind that await file.read() returns the entire file contents, so for large uploads use the streaming pattern shown later instead of reading the whole file.

The UploadFile object also exposes filename, content_type, and headers, which are useful for validation before reading the content. For synchronous endpoints, you can access the underlying file object directly:

python
@app.post("/upload") def upload_file(file: UploadFile = File(...)): data = file.file.read() return {"filename": file.filename, "size": len(data)}

The sync approach is fine for small files, but the async read() method is preferred in async endpoints because it does not block the event loop.

Combining Forms and Files in One Request

A single endpoint can accept both form fields and file uploads. When you mix Form() and File() parameters, FastAPI automatically uses multipart/form-data encoding for the request body:

python
from fastapi import FastAPI, File, Form, UploadFile app = FastAPI() @app.post("/documents") async def create_document( title: str = Form(...), description: str = Form(default=""), file: UploadFile = File(...), ): contents = await file.read() return { "title": title, "description": description, "filename": file.filename, "size": len(contents), }

The form fields and the file are sent in the same multipart/form-data body. The order of parameters does not matter; FastAPI maps each Form() parameter to a text field and each File() parameter to a file part. You can also include multiple UploadFile parameters if the client sends several files in one request.

Security and Operational Considerations

File uploads require attention to size and content validation. FastAPI does not impose a default size limit on uploads, so a large file can consume significant memory or disk space. Avoid reading the entire file into memory when you only need to store it. Use a normal def endpoint so FastAPI runs the file copy in a threadpool, and stream the file to disk in chunks:

python
import shutil from pathlib import Path from fastapi import FastAPI, File, UploadFile app = FastAPI() UPLOAD_DIR = Path("uploads") @app.post("/upload") def upload_file(file: UploadFile = File(...)): safe_name = Path(file.filename or "upload").name destination = UPLOAD_DIR / safe_name with destination.open("wb") as out_file: shutil.copyfileobj(file.file, out_file) return {"filename": safe_name}

shutil.copyfileobj copies the file in fixed-size chunks, avoiding a full read into memory. Treat file.content_type and file.filename as client-supplied values: validate them against an allowlist before storing, and use a safe path inside your upload directory. The python-multipart dependency is required for both form and file endpoints; without it, FastAPI reports that the dependency must be installed.

Cookie security follows standard web rules. Setting httponly=True prevents JavaScript from reading the cookie, which reduces the impact of XSS attacks. The secure flag forces transmission over HTTPS only and should be enabled in production. The samesite attribute controls whether the cookie is sent with cross-site requests; lax is a reasonable default for session cookies.

Common Pitfalls with These Parameters

One frequent mistake is declaring a form field without Form(). FastAPI treats a plain annotation as a query parameter, and the request fails with a 422 error because the query parameter is missing. Always use Form() for form fields and File() for uploads.

Another issue is mixing File() with Form() in a request that uses application/x-www-form-urlencoded. File uploads require multipart/form-data, and FastAPI selects this encoding automatically when a File() parameter is present. Clients must use the same encoding when sending the request.

For optional files, use file: UploadFile | None = File(default=None). The parameter becomes optional, and you must check for None before accessing the file object. The same pattern applies to optional cookies and headers: provide a default value so FastAPI does not reject requests that omit them.

When reading headers with Header(), declare the parameter with underscores, for example x_api_key. FastAPI converts those underscores to hyphens and matches header names case-insensitively, so x_api_key reads the X-API-Key header. Do not try to use X-API-Key as a Python parameter name. If you need to work with original header names or dynamic header keys, use request.headers.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.