Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 50 ยท Request parameters

Headers, cookies, forms and uploads

Read request headers and cookies, accept HTML form fields, and receive file uploads with UploadFile in FastAPI. Learn what runs live here and what needs python-multipart.

Besides the URL and the JSON body, a request carries more information. Headers hold metadata such as the client's language or an API key. Cookies are small values a browser sends back automatically. Forms and file uploads use two older body formats that HTML pages have always used. FastAPI reads each of these with the same type-hint approach you already know, using the helpers Header, Cookie, Form and File.

This lesson also draws an honest line between what you can run live on this site and what you will only run on your own machine, because form parsing needs an extra package.

Four more places to read from

Header Metadata like user-agent or an API key.
Cookie Values the browser sends back.
Form HTML form fields, not JSON.
File Uploaded files in a multipart body.

Live here - Header and Cookie. Read-only - Form and File.

1 / 2

Headers

Declare a parameter with Header() and FastAPI reads the matching request header. HTTP header names use hyphens (user-agent) and are case-insensitive, while Python names use underscores. FastAPI converts for you: a parameter named user_agent reads the header user-agent.

Python Reading headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The header value is validated like any other parameter: "3" becomes the integer 3 and "latest" fails with a 422 whose loc starts with "header". We did not send a User-Agent in the second call, yet the default shown is the client's own, because httpx adds one. Do not rely on that when testing; always set the headers you care about.

If a header genuinely contains underscores, which some proxies silently drop, turn off the conversion with Header(convert_underscores=False).

Headers that appear more than once, such as X-Token: a and X-Token: b, can be received as a list by declaring Annotated[list[str], Header()].

Headers are not proof of identity. Anyone can send any header. Treat values like X-Forwarded-For or X-User-Id as untrusted unless your own proxy sets them and strips client-supplied copies. Authentication is covered in OAuth2 password flow and JWT.

Cookies

Cookies work the same way with Cookie(). The browser stores a cookie that the server set earlier and sends it back with each request. On the response side you set one with response.set_cookie; to do that without building a full response object, add a parameter typed Response, and FastAPI merges your changes into the final reply.

Python Reading and setting cookies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The httpx client keeps a cookie jar like a browser, so the second GET automatically carries the cookie. Look at the flags in the set-cookie header: HttpOnly hides the cookie from JavaScript, SameSite=lax limits cross-site sending, and Max-Age sets its lifetime. For anything sensitive, also use secure=True so the cookie only travels over HTTPS.

Forms

Browsers submit <form> elements as application/x-www-form-urlencoded (or multipart/form-data when files are included), not as JSON. Use Form() for these fields. A common place is the OAuth2 login endpoint, which by specification takes username and password as form fields.

Python
from typing import Annotated
from fastapi import FastAPI, Form

app = FastAPI()


@app.post("/login")
async def login(
    username: Annotated[str, Form()],
    password: Annotated[str, Form(min_length=8)],
):
    return {"username": username}

FastAPI needs the python-multipart package to parse form bodies. With pip install "fastapi[standard]" it is already included; otherwise run pip install python-multipart. Without it, FastAPI raises an error when it sees a Form or File parameter. For this reason the form code on this page is read-only.

You cannot declare both Form and JSON Body parameters in one endpoint, because a request has only one body encoding. Pick one per endpoint.

What a form body looks like

To see what Form() does for you, here is a live stand-in that parses a URL-encoded body by hand with the standard library. It is not how FastAPI does it internally, but the data format is the same:

Python A form body is just encoded text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The space in the password was encoded as +. A real Form() parameter does this decoding, plus the type conversion and the same 422 errors you have seen, with loc starting with "body".

File uploads

Files travel in a multipart/form-data body. FastAPI offers two ways to receive them:

Python
from typing import Annotated
from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/size")
async def size(data: Annotated[bytes, File()]):
    return {"bytes": len(data)}


@app.post("/upload")
async def upload(file: UploadFile, note: Annotated[str, Form()] = ""):
    content = await file.read()
    return {
        "filename": file.filename,
        "content_type": file.content_type,
        "size": len(content),
    }
Style What you get Best for
bytes with File() the whole file in memory tiny files
UploadFile a file-like object with filename, content_type, await read(), await write(), await seek() almost everything

UploadFile keeps small uploads in memory and spills larger ones to a temporary file on disk, so a big upload does not exhaust RAM. You read it in chunks with await file.read(1024 * 1024). Several files at once use list[UploadFile].

Never trust an upload. The filename and content_type come from the client and can be forged. Enforce a size limit (for example, stop reading after a maximum number of bytes, or limit the body at your reverse proxy), generate your own storage name instead of using the client's, and check the real file type when it matters. Never build a file path from file.filename directly.

Checking an upload stand-in

You can still practice the logic around uploads live: size limits and safe file names do not depend on multipart parsing. This example receives raw bytes in a normal body and applies the checks a real upload endpoint needs.

Python Upload safety checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The client's name ../../etc/notes.txt never touches the disk path: only its extension survives, and the stored name is generated. The fixed UUID keeps this demo's output deterministic; a real app would call uuid.uuid4().

Summary of where data comes from

Source Helper Notes
URL path Path() or none always required
Query string Query() or none usually optional
Header Header() underscores map to hyphens
Cookie Cookie() sent by browsers automatically
JSON body a model or Body() one JSON body per request
Form fields Form() needs python-multipart
Files File(), UploadFile needs python-multipart

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which header does the parameter x_request_id: Annotated[str, Header()] read?

    FastAPI converts underscores to hyphens, and header names are case-insensitive, so it reads X-Request-Id.
  2. 2. How can an endpoint set a cookie without building a Response object itself?

    FastAPI injects a temporary Response object and merges its headers and cookies into the final response.
  3. 3. Which package must be installed to use Form() and File()?

    python-multipart parses form and multipart bodies. It is included in fastapi[standard].
  4. 4. Why is UploadFile usually better than bytes for uploads?

    UploadFile keeps large uploads out of memory by using a temporary file. The filename it reports still comes from the client and is not trustworthy.
  5. 5. Can one endpoint declare both Form() fields and a JSON model body?

    A request body is either JSON or form-encoded, not both, so FastAPI does not allow mixing them in one endpoint.

Summary

  • Header() and Cookie() read request metadata; underscores in names map to hyphens for headers.
  • Set cookies through an injected Response parameter and use httponly, secure and samesite flags.
  • Form() reads HTML form fields; File() and UploadFile read uploads. Both need python-multipart, so they are read-only on this site.
  • Never trust uploaded names or types: enforce size limits, generate your own file names and validate content.
  • One request has one body encoding, so JSON and form fields cannot be mixed.

Next, learn the model features behind all of this in Pydantic models for APIs.