Bookmarks
ReferenceBackendVerified

FastAPI

FastAPI is a Python web framework for HTTP APIs with data validation based on type hints. In this reference: parameters, Pydantic models, dependencies, async, testing, deployment.

checked 5 Nov · next check 12 Nov · 48 min read

Sections
13
Reading
48 min
Current version
0.162.2
Written from
fastapi.tiangolo.com

Check status of the reference

Verified 5 Nov · next check 12 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What FastAPI is and how it works

FastAPI is a Python web framework for HTTP APIs. Type annotations on function parameters and Pydantic models define input validation, conversion of the response into JSON and the OpenAPI schema. From this schema, FastAPI generates the interactive documentation automatically.

FastAPI is a good fit for JSON APIs: the backend of web and mobile applications, microservices and internal services. It does not impose a database, an ORM or an authentication method — these are added as separate libraries through the dependency system. If you need a website with a built-in ORM, templates and an admin panel, see the comparison in the Django reference, section “What Django is and how it works”.

A request travels through the application along a pipeline. The ASGI server Uvicorn accepts the connection and passes the request to the application, and middleware process each request before the operation and each response after it. The path and method select the path operation. Its parameters and body are converted to the declared types and validated by Pydantic; then the dependencies and the function itself are called. The result passes through the response model: extra fields are cut off and the rest goes to the client as JSON. If the input fails validation, the function is not called and the client receives a 422 response.

Middleware see both the request and the finished response, including the 422 response.

How FastAPI differs from Starlette and Pydantic

FastAPI is assembled from ready-made parts, and the documentation and error messages mention all of them by name. The FastAPI class inherits from the Starlette class, so everything Starlette can do also works in FastAPI.

ComponentWhat it handles
StarletteASGI framework: routing, middleware, WebSockets, background tasks, startup and shutdown events, test client
Pydanticvalidation and serialization of data from type annotations, JSON Schema of the models
UvicornASGI server: accepts connections and runs the application; it has no routing
FastAPIon top of Starlette and Pydantic: parameters and body from declared types, dependency injection, security utilities, the OpenAPI schema and documentation

Code written for Starlette — middleware, responses, other tools — works in a FastAPI application without changes, and Pydantic models and libraries connect as they are.

What you need to know first

  • Python: type annotations, functions, async and await — see the Python reference, sections “Functions, arguments and scopes” and “asyncio, threads and processes”.
  • Virtual environments and packages — see the Python reference, section “Installation and first run”.
  • HTTP methods, response codes and JSON — see the HTTP and REST reference.

Section sources

the section is written from these pages

Cheat sheet

Declarations and commands for everyday use; each is explained in its own section.

Running

TaskHow to write it
Development server with auto-reloadfastapi dev main.py
The same in a uv projectuv run fastapi dev
Production mode on 0.0.0.0:8000fastapi run main.py
Multiple processesfastapi run --workers 4 main.py
Entry point in pyproject.toml[tool.fastapi] and the line entrypoint = "main:app"
Documentation and schema/docs, /redoc, /openapi.json

Parameters

TaskHow to write it
Path parameter@app.get("/items/{item_id}") and the argument item_id: int
Required query parameterq: str
Optional query parameterq: str | None = None
String lengthq: Annotated[str | None, Query(max_length=50)] = None
Number in a rangelimit: Annotated[int, Query(ge=1, le=100)] = 20
List ?tag=a&tag=btag: Annotated[list[str], Query()] = []
Header X-Tokenx_token: Annotated[str, Header()]
Cookiesession_id: Annotated[str | None, Cookie()] = None

Body and response

TaskHow to write it
JSON body from a modelclass Item(BaseModel) and the argument item: Item
Field constraintprice: float = Field(gt=0)
Response model-> ItemOut or response_model=ItemOut
Success status code@app.post("/items/", status_code=201)
Code as a constantstatus.HTTP_201_CREATED
Form fieldtoken: Annotated[str, Form()]
File uploadfile: UploadFile

Dependencies

TaskHow to write it
Dependencydb: Annotated[Session, Depends(get_session)]
AliasSessionDep = Annotated[Session, Depends(get_session)]
Class as a dependencypage: Annotated[Pagination, Depends()]
Release a resource after the responsea dependency with yield inside try/finally
Dependency without a value@app.get("/admin/", dependencies=[Depends(verify_key)])
For the whole applicationapp = FastAPI(dependencies=[Depends(verify_key)])
Without caching for the duration of the requestDepends(get_value, use_cache=False)

Errors

TaskHow to write it
404 responseraise HTTPException(status_code=404, detail="Item not found")
Header in an error responseHTTPException(status_code=401, headers={"WWW-Authenticate": "Bearer"})
Custom exception handler@app.exception_handler(OutOfStock)
Validation error code422, status.HTTP_422_UNPROCESSABLE_CONTENT

Tests

TaskHow to write it
Client without a serverclient = TestClient(app)
Request and assertionr = client.get("/"), then assert r.status_code == 200
JSON bodyclient.post("/items/", json={"name": "Pen", "price": 1.5})
Override a dependencyapp.dependency_overrides[get_session] = fake_session
Clear the overridesapp.dependency_overrides.clear()
Run lifespanwith TestClient(app) as client:

Section sources

the section is written from these pages

Installation and first run

FastAPI is installed as the fastapi[standard] package into the project’s virtual environment; the official guide does this with uv. The check is the fastapi dev command: it starts a server at http://127.0.0.1:8000 with the API documentation at /docs.

A project with uv

The FastAPI documentation recommends managing a project with uv: it creates the environment itself, installs packages and pins their versions. uv itself is installed following its official instructions.

bashon the host
uv init myapi --barecd myapiuv add "fastapi[standard]"

uv init --bare creates only pyproject.toml, with no sample code. uv add creates a .venv environment, writes FastAPI to pyproject.toml and pins the exact versions of all packages in uv.lock. From that file, the same set of packages is installed on another machine and when deploying. uv finds a suitable Python in the system or downloads one itself.

With venv and pip

If you manage the environment yourself, create and activate it, then install the package with pip. For details on environments, see the Python reference, the section “Installation and first run”.

bashon the host
python3 -m venv .venvsource .venv/bin/activatepip install "fastapi[standard]"

The essentials of fastapi[standard]

  • uvicorn[standard] — the server that runs the application, with packages for fast operation, such as uvloop.
  • fastapi-cli[standard] — the fastapi command, together with fastapi-cloud-cli for FastAPI Cloud.
  • httpx2 or httpx — for the test client TestClient.
  • python-multipart — form parsing and file uploads.
  • jinja2 — templates; email-validator — email address validation.

Without these packages, the fastapi package is installed; without the cloud CLI — fastapi[standard-no-fastapi-cloud-cli].

The first application

pythonmain.py
from fastapi import FastAPI app = FastAPI()  @app.get("/")async def root():    return {"message": "Hello World"}
bashin the project directory
uv run fastapi dev
textsample output
...INFO:     Will watch for changes in these directories: ['/home/user/myapi']INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)INFO:     Started reloader process [27178] using WatchFiles...INFO:     Application startup complete.

fastapi dev finds main.py, imports the app object from it and watches the files: after you save, the server restarts on its own. If the environment is activated, write fastapi dev without uv run. The file can be given explicitly: fastapi dev main.py.

Checking

bashin another terminal
curl http://127.0.0.1:8000/
jsonsample output
{"message":"Hello World"}

Open http://127.0.0.1:8000/docs in a browser — this is Swagger UI, where the operations can be called right from the page. At /redoc — the same documentation in ReDoc, at /openapi.json — the OpenAPI schema itself.

The entrypoint in pyproject.toml

tomlpyproject.toml
[tool.fastapi]entrypoint = "main:app"

Then fastapi dev and fastapi run find the application without arguments, as do the VS Code extension and FastAPI Cloud. For the app package from the tree below, the entrypoint is "app.main:app".

The project tree

textproject structure
myapi├── pyproject.toml├── uv.lock└── app    ├── __init__.py    ├── main.py    ├── dependencies.py    └── routers        ├── __init__.py        ├── items.py        └── users.py

Every directory with __init__.py is a Python package, so the modules import each other relatively: from .routers import items. The operations of each area live in their own module with an APIRouter — a “small FastAPI” with the same decorators and parameters.

pythonapp/routers/items.py
from fastapi import APIRouter router = APIRouter(prefix="/items", tags=["items"])  @router.get("/")async def read_items():    return [{"name": "Pen"}]  @router.get("/{item_id}")async def read_item(item_id: int):    return {"item_id": item_id}
pythonapp/main.py
from fastapi import FastAPI from .routers import items, users app = FastAPI()app.include_router(items.router)app.include_router(users.router)

The router’s prefix, tags and dependencies apply to all of its operations; the prefix is written without a trailing /. The modules are imported whole (items, users), not their router variables: otherwise the second router overwrites the first.

Section sources

the section is written from these pages

Path operations and parameters

A path operation is a function under a decorator such as @app.get("/items/{item_id}") that handles one HTTP method on one path. FastAPI fills its arguments from the path, the query string, headers and cookies, and validates them against type annotations.

There are decorators for all HTTP methods: @app.get, @app.post, @app.put, @app.delete and others. An argument whose name appears in curly braces in the path is a path parameter. The remaining arguments of simple types are query parameters, taken from the part of the URL after ?. Values arrive as strings, and FastAPI converts them to the declared types.

pythonmain.py
from enum import Enumfrom typing import Annotated from fastapi import FastAPI, Path, Query app = FastAPI()  class Sort(str, Enum):    new = "new"    price = "price"  @app.get("/shops/{shop_id}/items")async def list_items(    shop_id: Annotated[int, Path(ge=1)],    q: Annotated[str | None, Query(max_length=50)] = None,    sort: Sort = Sort.new,    limit: Annotated[int, Query(ge=1, le=100)] = 20,    in_stock: bool = False,):    return {        "shop_id": shop_id,        "q": q,        "sort": sort,        "limit": limit,        "in_stock": in_stock,    }
bashcheck
curl "http://127.0.0.1:8000/shops/7/items?q=pen&sort=price&in_stock=yes"
jsonexample output
{"shop_id":7,"q":"pen","sort":"price","limit":20,"in_stock":true}

The string 7 from the path became a number. A boolean parameter reads 1, true, on, yes as True and 0, false, off, no as False in any case. An empty or other value produces a 422 response. The allowed values of sort come from the Enum inherited from str: the documentation at /docs will list them.

Required and optional parameters

DeclarationWhere the value comes fromRequired
shop_id: int and {shop_id} in the pathpathalways
q: strqueryyes
q: str | None = Nonequeryno, defaults to None
skip: int = 0queryno, defaults to 0
tag: Annotated[list[str], Query()] = []query: ?tag=a&tag=bno
x_token: Annotated[str, Header()]x-token headeryes
session_id: Annotated[str | None, Cookie()] = Nonecookieno

Validation with Annotated

Constraints go into Query(), Path(), Header() or Cookie() inside Annotated, while the default value is set with a plain =. This way the function can be called without FastAPI too, and the editor will flag a missing required argument. The form q: str | None = Query(default=None) is the old style from versions before 0.95 and still appears in other people’s code.

ArgumentWhat it validates or sets
min_length, max_lengthstring length
patternregular expression for a string
gt, ge, lt, lenumber greater than, greater than or equal to, less than, less than or equal to
aliasname in the request when it is not valid for Python: item-query
title, descriptionlabels of the parameter in the documentation
deprecated=True“deprecated” mark in the documentation
include_in_schema=Falsethe parameter is left out of the OpenAPI schema
convert_underscoresonly in Header(): replace _ with - in the name, True by default
pythonmain.py
@app.get("/search")async def search(    q: Annotated[str, Query(min_length=3, pattern="^[a-z ]+$")],    tag: Annotated[list[str], Query()] = [],    item_query: Annotated[str | None, Query(alias="item-query")] = None,):    return {"q": q, "tag": tag, "item_query": item_query}

A list from the query string is declared only through Query(): without it FastAPI would expect list[str] in the request body. Headers and cookies are declared explicitly too — through Header() and Cookie(), otherwise the argument becomes a query parameter. With Header(), underscores in the name turn into hyphens: the argument x_token reads the x-token header.

Route order

Operations are matched in the order they are declared. Declare /users/me before /users/{user_id}: otherwise a request to /users/me will go to the second operation with user_id equal to "me". A second declaration of the same path and method never takes effect — the first one matches earlier.

pythonmain.py
@app.get("/users/me")async def read_me():    return {"user_id": "current"}  @app.get("/users/{user_id}")async def read_user(user_id: int):    return {"user_id": user_id}

Response status code

The successful response code is set by the decorator parameter status_code — as a number or as a constant from fastapi.status, which the editor will suggest. For codes without a body, such as 204, FastAPI describes the response that way in OpenAPI.

pythonmain.py
from fastapi import status  @app.post("/items/", status_code=status.HTTP_201_CREATED)async def create_item(name: str):    return {"name": name}

A 422 response on validation failure

If a parameter fails validation, the function is not called and the client receives 422 with a detail array. Each item contains the error type type, the location loc (where the value comes from and which field it is), the message msg and the received value input. For example, /shops/abc/items produces int_parsing with the message Input should be a valid integer, unable to parse string as an integer. This is what the response to /search without the required q looks like:

jsonexample output
{  "detail": [    {      "type": "missing",      "loc": ["query", "q"],      "msg": "Field required",      "input": null    }  ]}

Path inside a parameter

To make a parameter take the rest of the path together with the /, append the Starlette converter :path to it. OpenAPI has no such kind of parameter, but the documentation still works.

pythonmain.py
@app.get("/files/{file_path:path}")async def read_file(file_path: str):    return {"file_path": file_path}

Section sources

the section is written from these pages

Request body and response models

The request body is described with a Pydantic model — a class derived from BaseModel: FastAPI reads the JSON, validates it against the model and passes a ready object to the function. The response model works the other way round and exposes only the declared fields.

pythonmain.py
from fastapi import FastAPIfrom pydantic import BaseModel, Field app = FastAPI()  class Item(BaseModel):    name: str = Field(min_length=1, max_length=100)    price: float = Field(gt=0)    description: str | None = None    tags: list[str] = []  @app.post("/items/")async def create_item(item: Item) -> Item:    return item  @app.put("/items/{item_id}")async def update_item(    item_id: int, item: Item, notify: bool = False):    return {"item_id": item_id, "notify": notify, **item.model_dump()}
bashtest
curl -X POST http://127.0.0.1:8000/items/ \  -H "Content-Type: application/json" \  -d '{"name": "Pen", "price": 1.5}'
jsonsample output
{"name":"Pen","price":1.5,"description":null,"tags":[]}

A field without a default value is required, with None — optional. Inside the function the fields are ordinary attributes, and item.model_dump() turns the model into a dictionary. In update_item FastAPI figured out on its own where each argument comes from:

  • an argument named after the path segment — a path parameter (item_id);
  • an argument of a simple type — int, float, str, bool — a query parameter (notify);
  • an argument whose type is a Pydantic model — the request body (item).

Field constraints are set with Field — it is imported from pydantic, not from fastapi. It takes the same arguments as Query and Path: gt, max_length, title, description and others. Body validation errors arrive with a loc that starts with body.

The response model filters fields

The return type of the function or the decorator parameter response_model is what FastAPI uses to validate the response, describe it in the OpenAPI schema and strip out everything that is not in the model. If the response does not fit the model — for example, a required field is missing — the client gets a server error, not wrong data.

pythonmain.py
from pydantic import BaseModel, EmailStr  class UserBase(BaseModel):    username: str    email: EmailStr  class UserIn(UserBase):    password: str  @app.post("/users/")async def create_user(user: UserIn) -> UserBase:    # the password will not reach the client: it is not in UserBase    return user

The function returned UserIn with a password, but the client receives only username and email: FastAPI filters the data by the declared type, not by the class of the object. EmailStr needs the email-validator package.

If the function returns a dictionary or a database object, declare the model in the decorator and make the return type — Any. When both are declared, response_model wins.

pythonmain.py
from typing import Any from fastapi import HTTPException  class ItemOut(BaseModel):    name: str    price: float  @app.get("/items/{item_id}", response_model=ItemOut)async def read_item(item_id: int) -> Any:    if item_id != 1:        raise HTTPException(status_code=404, detail="Item not found")    # cost will not appear in the response    return {"name": "Pen", "price": 1.5, "cost": 0.7}
Decorator parameterWhat it does
response_model=ItemOutresponse model instead of the return type
response_model=Noneno response model: the return type remains only for the editor
response_model_exclude_unset=Truethe response keeps only the fields that were set explicitly
response_model_exclude_none=Truewithout fields whose value is None
response_model_include={"name"}, response_model_exclude={"tax"}keep or drop fields; the OpenAPI schema stays complete, so a separate model is preferable

Errors: HTTPException

An error is not returned to the client but raised: raise HTTPException(...). Execution stops immediately, even inside a helper function, and the client receives the status code and the JSON {"detail": "Item not found"}. detail accepts any value that can be turned into JSON, and headers — the response headers.

Custom exceptions and handlers

pythonmain.py
from fastapi import Requestfrom fastapi.responses import JSONResponse  class OutOfStock(Exception):    def __init__(self, name: str):        self.name = name  @app.exception_handler(OutOfStock)async def out_of_stock_handler(request: Request, exc: OutOfStock):    return JSONResponse(        status_code=409,        content={"detail": f"{exc.name} is out of stock"},    )

The handler is registered for an exception class and fires wherever that exception is raised. The default handlers can be replaced too: for validation errors — with the RequestValidationError class, for HTTPException — with starlette.exceptions.HTTPException, to catch exceptions coming from Starlette code as well.

Forms and files

Form fields and files do not arrive as JSON but in form encoding, so they are declared with Form() and File(). Parsing them needs the python-multipart package: uv add python-multipart.

pythonmain.py
from typing import Annotated from fastapi import File, Form, UploadFile  @app.post("/files/")async def create_file(    token: Annotated[str, Form()],    file: Annotated[bytes, File()],    upload: Annotated[UploadFile, File()],):    return {        "token": token,        "file_size": len(file),        "upload_type": upload.content_type,    }
DeclarationWhat the function receives
Annotated[str, Form()]the value of a form field
Annotated[bytes, File()]the file content as bytes
Annotated[UploadFile, File()]an UploadFile object: the file type in content_type, for example

Section sources

the section is written from these pages

Dependencies

A dependency is a function or class that FastAPI calls before a path operation and whose result it passes into the operation’s argument via Depends(). This way you write shared logic once: a database session, the current user, a permission check, common parameters.

A dependency accepts the same parameters as a path operation: query parameters, headers, the request body, other dependencies. FastAPI parses and validates them, and everything declared in dependencies ends up in the OpenAPI schema. A dependency can be an async def or a regular def — regardless of how the path operation is declared.

pythonmain.py
from typing import Annotated from fastapi import Depends, FastAPI app = FastAPI()  async def pagination(offset: int = 0, limit: int = 20):    return {"offset": offset, "limit": limit}  PageDep = Annotated[dict, Depends(pagination)]  @app.get("/items/")async def read_items(page: PageDep):    return {"page": page}  @app.get("/users/")async def read_users(page: PageDep):    return {"page": page}

You pass the function itself to Depends, without parentheses: FastAPI does the calling. PageDep is a plain type alias built with Annotated: the repeated Depends(...) disappears, while the editor still knows the argument’s type.

Nested dependencies and caching

A dependency can itself depend on others, to any depth; FastAPI resolves them bottom-up. If several dependencies in one request need the same one, FastAPI calls it once and hands the result to all of them. To have it called anew every time, write Depends(get_value, use_cache=False).

A class as a dependency

pythonmain.py
class Pagination:    def __init__(self, offset: int = 0, limit: int = 20):        self.offset = offset        self.limit = limit  @app.get("/orders/")async def read_orders(page: Annotated[Pagination, Depends()]):    return {"offset": page.offset, "limit": page.limit}

Any callable can be a dependency: for a class, FastAPI reads its __init__ parameters and passes the instance it creates to the path operation. Depends() with no argument takes the class from the annotation, so the name is not written twice.

Dependencies with yield

A dependency with yield instead of return runs code both before and after the path operation. Code before yield runs before the operation, the yielded value goes to the operation or another dependency, and code after yield runs once the response has been sent. This is how a database session is opened and closed; try and finally guarantee it is closed even when an exception occurs. A dependency has exactly one yield.

pythonmain.py
from fastapi import Header, HTTPExceptionfrom sqlmodel import Session, select from .models import User, engine  def get_db():    db = Session(engine)    try:        yield db    finally:        db.close()  DbDep = Annotated[Session, Depends(get_db)]  def get_current_user(db: DbDep, x_token: Annotated[str, Header()]):    statement = select(User).where(User.token == x_token)    user = db.exec(statement).first()    if user is None:        raise HTTPException(status_code=401, detail="Invalid token")    return user  @app.get("/profile/")def read_profile(user: Annotated[User, Depends(get_current_user)]):    return {"username": user.username}
This is how a dependency with yield works by default, with scope="request".
  1. The request arrives and FastAPI calls get_db.
  2. Code before yield opens the session.
  3. yield passes the session to get_current_user.
  4. get_current_user finds the user and passes it to the path operation.
  5. The path operation returns a result, and the response goes to the client.
  6. Code after yield in the finally block closes the session.

An exception raised in the path operation, including HTTPException, reaches the dependency with yield: you can catch it in except and replace it with another one, for example an HTTPException with a clear status code.

Code after yield usually runs after the response has been sent. If the resource is not needed after the path operation, write Depends(get_db, scope="function"): the dependency is torn down right after the function, before the response. By default a dependency with yield has scope="request", and its nested dependencies must be "request" too.

Dependencies without values and app-wide dependencies

pythonmain.py
async def verify_key(x_key: Annotated[str, Header()]):    if x_key != "change-me":        raise HTTPException(            status_code=400, detail="X-Key header invalid"        )  @app.get("/admin/", dependencies=[Depends(verify_key)])async def admin():    return {"ok": True}

Dependencies from the dependencies list run like ordinary ones: they check things, raise exceptions and show up in the documentation — but their value is not passed into the function. The same list on FastAPI(dependencies=[...]) applies to every path operation in the application, and on APIRouter — to the router’s path operations. In tests any dependency can be replaced via app.dependency_overrides — see the “Testing” section for details.

Section sources

the section is written from these pages

async def and def

Declare an operation as async def when everything it waits for is called with await. If it calls a blocking library without await, as most database drivers do, write a plain def. FastAPI will run such a function in a thread pool, and the server will not stall.

FastAPI runs an async def function directly on the event loop: while it waits at an await, the loop serves other requests. A plain def function is dispatched to a separate thread from the pool, and FastAPI waits for the result — called directly, such a function would block the server. That is why a blocking call inside async def, such as time.sleep() or a synchronous database driver, stops the event loop, and every other request waits.

FastAPI runs dependencies the same way: async def — on the event loop, def — in the thread pool.

How to choose

What the function doesHow to declare it
calls asynchronous libraries with awaitasync def
calls a blocking library without awaitdef
waits for nothing and computes quickly on the spotasync def: FastAPI does not spend a thread on it
uncleardef
pythonmain.py
import asyncioimport time from fastapi import FastAPI app = FastAPI()  @app.get("/async-wait")async def async_wait():    # await yields the event loop to other requests    await asyncio.sleep(1)    return {"ok": True}  @app.get("/sync-wait")def sync_wait():    # def runs in the thread pool    time.sleep(1)    return {"ok": True}  @app.get("/blocking")async def blocking():    # never do this: time.sleep() holds the event loop    time.sleep(1)    return {"ok": False}

def and async def can be mixed in one application, and the rule is the same for operations and dependencies. FastAPI leaves your own helper functions alone: you call a plain def directly, in the same thread, and an async def — with await. The asyncio module itself is covered in the Python reference, in the section “asyncio, threads and processes”.

Background tasks

pythonmain.py
from fastapi import BackgroundTasks  def write_log(message: str):    with open("log.txt", mode="a") as log:        log.write(message + "\n")  @app.post("/orders/{order_id}")async def create_order(order_id: int, tasks: BackgroundTasks):    tasks.add_task(write_log, f"order {order_id} created")    return {"order_id": order_id}

FastAPI creates an argument of the BackgroundTasks type itself; tasks from add_task() run after the response has been sent. A task — an ordinary def or async def function with any arguments. BackgroundTasks can be declared in dependencies too: all tasks of a request will be gathered together. For heavy computations that need separate processes or servers, use a task queue such as Celery with RabbitMQ or Redis.

Lifespan events

Code that has to run once before the first request and once at shutdown goes into a lifespan function passed to FastAPI(lifespan=...). This suits shared resources: a database connection pool, loading a model into memory.

pythonmain.py
from contextlib import asynccontextmanager from fastapi import FastAPI rates = {}  @asynccontextmanagerasync def lifespan(app: FastAPI):    # before yield: before requests are served    rates["usd"] = 12650.0    yield    # after yield: when the application shuts down    rates.clear()  app = FastAPI(lifespan=lifespan)  @app.get("/rates")async def read_rates():    return rates

Section sources

the section is written from these pages

Working with a database

FastAPI does not require any particular database. The official tutorial connects an SQL database through SQLModel — a library built on top of SQLAlchemy and Pydantic in which the same classes describe both the tables and the API data. A dependency with yield provides the session for the duration of a request.

SQLModel works with any database supported by SQLAlchemy: PostgreSQL, MySQL, SQLite, Oracle, Microsoft SQL Server. The examples below use SQLite: it is a single file, and Python supports it out of the box. For production, the tutorial recommends a server such as PostgreSQL. The SQL language and PostgreSQL itself are covered in the SQL and PostgreSQL references.

bashin the project directory
uv add sqlmodel

Models: the table and the API data

A class with table=True is a table model; without it, a data model — an ordinary Pydantic model. Inheritance removes field duplication, and the separate models solve two problems: the client neither sets id nor sees the internal fields.

pythonapp/main.py, models
from sqlmodel import Field, SQLModel  class ItemBase(SQLModel):    name: str = Field(index=True)    price: float  class Item(ItemBase, table=True):    id: int | None = Field(default=None, primary_key=True)    cost: float  class ItemPublic(ItemBase):    id: int  class ItemCreate(ItemBase):    cost: float  class ItemUpdate(SQLModel):    name: str | None = None    price: float | None = None    cost: float | None = None
ModelTablePurpose
ItemBasenofields shared by all models
Itemyesa table row: id is generated by the database, cost is an internal field
ItemPublicnothe response to the client: id is always there, cost is not
ItemCreatenothe body on creation: no id
ItemUpdatenothe PATCH body: all fields are optional

Engine, session and table creation

pythonapp/main.py, connection
from contextlib import asynccontextmanagerfrom typing import Annotated from fastapi import Depends, FastAPIfrom sqlmodel import Session, create_engine engine = create_engine(    "sqlite:///database.db",    connect_args={"check_same_thread": False},)  def get_session():    with Session(engine) as session:        yield session  SessionDep = Annotated[Session, Depends(get_session)]  @asynccontextmanagerasync def lifespan(app: FastAPI):    # for development; in production — migrations    SQLModel.metadata.create_all(engine)    yield  app = FastAPI(lifespan=lifespan)

The engine holds the connections to the database, and there is one for the whole application. A session keeps objects in memory, tracks their changes and writes them to the database through the engine; get_session provides a fresh session for each request. check_same_thread=False is needed for SQLite: a single request may run in several threads, for example inside dependencies.

CRUD operations

pythonapp/main.py, reading
from fastapi import HTTPException, Queryfrom sqlmodel import select  @app.post("/items/", response_model=ItemPublic, status_code=201)def create_item(item: ItemCreate, session: SessionDep):    db_item = Item.model_validate(item)    session.add(db_item)    session.commit()    session.refresh(db_item)    return db_item  @app.get("/items/", response_model=list[ItemPublic])def read_items(    session: SessionDep,    offset: int = 0,    limit: Annotated[int, Query(le=100)] = 100,):    statement = select(Item).offset(offset).limit(limit)    return session.exec(statement).all()
pythonapp/main.py, modifying
@app.patch("/items/{item_id}", response_model=ItemPublic)def update_item(item_id: int, item: ItemUpdate, session: SessionDep):    db_item = session.get(Item, item_id)    if not db_item:        raise HTTPException(status_code=404, detail="Item not found")    db_item.sqlmodel_update(item.model_dump(exclude_unset=True))    session.add(db_item)    session.commit()    session.refresh(db_item)    return db_item  @app.delete("/items/{item_id}")def delete_item(item_id: int, session: SessionDep):    db_item = session.get(Item, item_id)    if not db_item:        raise HTTPException(status_code=404, detail="Item not found")    session.delete(db_item)    session.commit()    return {"ok": True}

The operations are declared with def: the SQLModel session is blocking, so FastAPI runs them in a thread pool. The functions return the table model Item, and response_model=ItemPublic validates it and sends the client only the public fields. model_dump(exclude_unset=True) in PATCH takes only the fields the client actually sent, leaving the remaining values in place instead of overwriting them with defaults.

The test database

Tests must not touch the production database. Override the get_session dependency with a session for an in-memory SQLite database: the address sqlite:// with no file name, and poolclass=StaticPool, so that all threads see the same database.

pythonapp/test_main.py
import pytestfrom fastapi.testclient import TestClientfrom sqlmodel import Session, SQLModel, create_enginefrom sqlmodel.pool import StaticPool from .main import app, get_session  @pytest.fixture(name="session")def session_fixture():    engine = create_engine(        "sqlite://",        connect_args={"check_same_thread": False},        poolclass=StaticPool,    )    SQLModel.metadata.create_all(engine)    with Session(engine) as session:        yield session  @pytest.fixture(name="client")def client_fixture(session: Session):    app.dependency_overrides[get_session] = lambda: session    yield TestClient(app)    app.dependency_overrides.clear()  def test_create_item(client: TestClient):    data = {"name": "Pen", "price": 1.5, "cost": 0.7}    response = client.post("/items/", json=data)    assert response.status_code == 201    assert "cost" not in response.json()

Section sources

the section is written from these pages

Testing

TestClient calls the FastAPI application directly, without starting a server: tests are ordinary pytest functions with def, and the response is checked through status_code and json(). The client needs the httpx package; pytest is installed separately: uv add pytest.

pythonapp/main.py
from typing import Annotated from fastapi import Depends, FastAPI, Header, HTTPException app = FastAPI()items = {"foo": {"id": "foo", "title": "Foo"}}  async def get_current_user(x_token: Annotated[str, Header()]):    if x_token != "change-me":        raise HTTPException(            status_code=400, detail="Invalid X-Token header"        )    return {"username": "ann"}  CurrentUser = Annotated[dict, Depends(get_current_user)]  @app.get("/items/{item_id}")async def read_item(item_id: str, user: CurrentUser):    if item_id not in items:        raise HTTPException(status_code=404, detail="Item not found")    return items[item_id]  @app.get("/profile/")async def read_profile(user: CurrentUser):    return user
pythonapp/test_main.py
from fastapi.testclient import TestClient from .main import app client = TestClient(app)  def test_read_item():    response = client.get("/items/foo", headers={"X-Token": "change-me"})    assert response.status_code == 200    assert response.json() == {"id": "foo", "title": "Foo"}  def test_bad_token():    response = client.get("/items/foo", headers={"X-Token": "wrong"})    assert response.status_code == 400    assert response.json() == {"detail": "Invalid X-Token header"}
bashin the project directory
uv run pytest
textexample output
collected 2 items app/test_main.py ..                                [100%]

Test function names start with test_ — that is how pytest finds them. The test file lives in the same package as the application and imports it relatively: from .main import app.

What to passHow
path or query parameterin the address itself: client.get("/items/foo?q=pen")
JSON bodyjson={"name": "Pen"}
form fieldsdata={"username": "ann"}
headersheaders={"X-Token": "change-me"}
cookiescookies={"session_id": "abc"}

Overriding dependencies

The app.dependency_overrides dictionary replaces a dependency in tests: the key is the original function, the value is the replacement. The original dependency and its sub-dependencies are then not called. This is how an external login service, a paid API or a database is replaced. The override works wherever the dependency is declared: in an operation’s argument, in a decorator, in include_router().

pythonapp/test_main.py
import pytestfrom fastapi.testclient import TestClient from .main import app, get_current_user  def fake_user():    return {"username": "test"}  @pytest.fixturedef client():    app.dependency_overrides[get_current_user] = fake_user    yield TestClient(app)    app.dependency_overrides = {}  def test_profile(client):    response = client.get("/profile/")    assert response.json() == {"username": "test"}

A test with lifespan

Without with the client does not run the lifespan. For the startup and shutdown code to run, create the client in a with block: entering the block starts the application, leaving it shuts it down. The example tests the application with exchange rates from the “async def and def” section.

pythonapp/test_main.py
def test_rates():    with TestClient(app) as client:        response = client.get("/rates")        assert response.json() == {"usd": 12650.0}

Async tests

An async test is needed when the test itself makes calls with await, for example checking a record through an async database driver. Inside async def TestClient does not work, so requests are sent by httpx.AsyncClient through ASGITransport, and the @pytest.mark.anyio marker runs the test in the event loop.

pythonapp/test_main.py
import pytestfrom httpx import ASGITransport, AsyncClient from .main import app HEADERS = {"X-Token": "change-me"}  @pytest.mark.anyioasync def test_root():    async with AsyncClient(        transport=ASGITransport(app=app), base_url="http://test"    ) as ac:        response = await ac.get("/profile/", headers=HEADERS)    assert response.status_code == 200

AsyncClient does not run the lifespan; if the application needs it, use LifespanManager from the asgi-lifespan package. Fixtures, parametrisation and pytest markers are covered in the pytest reference; what to check in an API — in the API testing reference.

Section sources

the section is written from these pages

Deployment

In production FastAPI is started with the fastapi run command: it launches Uvicorn without auto-reload on 0.0.0.0:8000. HTTPS, starting on boot, restart after a crash and the number of processes are handled by external tools — a reverse proxy, systemd, Docker, Kubernetes or a cloud service.

The typical scheme: a reverse proxy accepts HTTPS, terminates TLS and passes requests over HTTP to one main Uvicorn process. It listens on a port and hands requests to workers — separate processes each running a copy of the application. Workers share no memory: each loads all of its own.

In a Kubernetes cluster, several containers with a single process are usually run instead of workers.

What to decide before deployment

QuestionHow it is solved
HTTPSa proxy that terminates TLS: Traefik, Caddy, Nginx with Certbot, HAProxy, Ingress in Kubernetes
Start on server bootDocker, Docker Compose, Kubernetes, systemd, Supervisor
Restart after a crashthe same tool that runs the application
Number of processes--workers or several containers in a cluster
Memoryeach process takes its own: a 1 GB model in 4 workers is 4 GB
Steps before the startmigrations — once and in one process, before the workers start

Uvicorn and workers

bashon the server
fastapi run --workers 4 main.py

--workers 4 starts a main manager process and four workers to use several CPU cores. The same run directly through Uvicorn requires an import string of the form main:app — the module and the application object in it:

bashon the server
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

Behind a reverse proxy

The proxy tells the application the client’s original address, protocol and host in the X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host headers. The server trusts them only from the addresses in --forwarded-allow-ips; otherwise, for example, a redirect from /items to /items/ would point to http:// instead of https://. If the proxy publishes the application under a prefix it strips off itself (/api/v1), pass it in --root-path: then /docs will find the schema at the right address.

bashon the server with a proxy
fastapi run main.py \  --forwarded-allow-ips="127.0.0.1" \  --root-path /api/v1

--forwarded-allow-ips="*" trusts all addresses — this is fine only if the proxy alone connects to the server. The root_path parameter in FastAPI() is deprecated: set the prefix with a server option instead. Configuring Nginx itself is covered in the Nginx reference, the “Reverse proxy” section.

The Docker image

The official guide builds an image from scratch on top of the official Python image. Dependencies of a uv project are exported to requirements.txt with the exact versions from uv.lock; the file is regenerated every time uv.lock changes.

bashon the host
uv export --format requirements-txt --no-dev \  --no-emit-project --output-file requirements.txt
dockerfileDockerfile
FROM python:3.14 WORKDIR /code COPY ./requirements.txt /code/requirements.txtRUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./app /code/app CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"]
bashon the host
docker build -t myapi .docker run -d --name myapi -p 80:80 myapi

Only requirements.txt is copied first: while it stays unchanged, the layer with the package installation is taken from the build cache. Write CMD in exec form — a list of strings: then the application shuts down gracefully and runs the lifespan shutdown code. --proxy-headers is needed behind a proxy such as Nginx or Traefik. The Dockerfile and the cache are covered in detail in the Docker reference.

  • In Kubernetes and other clusters, run a single Uvicorn process without --workers in the container: the cluster provides replicas and load balancing.
  • On a single server with Docker Compose, you can add --workers 4 to CMD.
  • The tiangolo/uvicorn-gunicorn-fastapi image is deprecated: Uvicorn manages workers itself, and a custom image takes just as many lines.

Migrations and other steps before the start

Database migrations are run once and in one process before the workers start: several processes would run them in parallel and could get in each other’s way. In Kubernetes this is done by an init container; on a plain server, by a script that performs the steps and then starts the application.

Section sources

the section is written from these pages

Security

The main threats to an API are operations without a permission check, leaked passwords and keys, and CORS that is too permissive. Schemes from fastapi.security extract the credentials from the request, and you write the check in a dependency that the protected operations declare.

ClassWhere it reads the dataWhat the dependency returns
OAuth2PasswordBearer(tokenUrl="token")Authorization: Bearer …the token string
OAuth2PasswordRequestFormthe form fields username and passworda form object
HTTPBasic()Authorization: Basic …HTTPBasicCredentials with username and password
HTTPBearer()Authorization: Bearer …HTTPAuthorizationCredentials
APIKeyHeader(name="x-api-key")a headerthe key string
APIKeyCookie, APIKeyQuerya cookie, a query parameterthe key string

Without credentials such a dependency aborts the request with an error by itself. With auto_error=False it returns None — that is how optional login, or login by one of several methods, is done. Every scheme appears in OpenAPI: in /docs you can log in and call the protected operations.

Store only the password hash

If the database is stolen, the hash will not reveal the password or let anyone log into other systems with it. The FastAPI tutorial hashes passwords with the pwdlib library and the Argon2 algorithm: uv add "pwdlib[argon2]".

pythonapp/security.py
from pwdlib import PasswordHash password_hash = PasswordHash.recommended()DUMMY_HASH = password_hash.hash("dummypassword")  def authenticate(users: dict, username: str, password: str) -> bool:    hashed = users.get(username)    if hashed is None:        # the same response time as for an existing username        password_hash.verify(password, DUMMY_HASH)        return False    return password_hash.verify(password, hashed)

Verifying the dummy DUMMY_HASH for a username that does not exist evens out the response time: brute force can no longer reveal which users exist (a timing attack).

Issue the token with a signature and an expiry

A JWT is not encrypted — anyone can read its contents — but it is signed, and tampering is visible from the signature. Put a unique user identifier in sub and the expiry time in exp. Take the signing secret from an environment variable, not from the code: create it with openssl rand -hex 32 and set it in SECRET_KEY. The JWT library is installed with uv add pyjwt.

pythonapp/security.py
from datetime import datetime, timedelta, timezone import jwtfrom pydantic_settings import BaseSettings  class Settings(BaseSettings):    secret_key: str    algorithm: str = "HS256"    token_minutes: int = 30  settings = Settings()  def create_access_token(username: str) -> str:    expire = datetime.now(timezone.utc) + timedelta(        minutes=settings.token_minutes    )    return jwt.encode(        {"sub": username, "exp": expire},        settings.secret_key,        algorithm=settings.algorithm,    )

BaseSettings from the pydantic-settings package reads environment variables case-insensitively and checks their types like a Pydantic model: SECRET_KEY ends up in secret_key.

Check the token in a dependency

pythonapp/security.py
from typing import Annotated from fastapi import Depends, HTTPException, statusfrom fastapi.security import OAuth2PasswordBearerfrom jwt.exceptions import InvalidTokenError oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")  async def get_current_user(    token: Annotated[str, Depends(oauth2_scheme)],) -> str:    unauthorized = HTTPException(        status_code=status.HTTP_401_UNAUTHORIZED,        detail="Could not validate credentials",        headers={"WWW-Authenticate": "Bearer"},    )    try:        payload = jwt.decode(            token, settings.secret_key, algorithms=[settings.algorithm]        )    except InvalidTokenError:        raise unauthorized    username = payload.get("sub")    if username is None:        raise unauthorized    return username  CurrentUser = Annotated[str, Depends(get_current_user)]

The POST /token operation accepts OAuth2PasswordRequestForm, checks the password and returns {"access_token": ..., "token_type": "bearer"}; the client then sends the token in the Authorization: Bearer header. Protected operations declare a user: CurrentUser argument. The token’s permissions are narrowed with OAuth2 scopes — via Security() instead of Depends() and SecurityScopes. The OAuth 2.0 and JWT protocols themselves are described in the “OAuth 2.0 and OpenID Connect” reference.

List the CORS origins explicitly

A browser lets JavaScript from a page of a different origin — protocol, domain and port — reach only an API that has allowed that origin. allow_origins=["*"] does not work with cookies and the Authorization header, and with allow_credentials=True none of allow_origins, allow_methods or allow_headers may be ["*"].

pythonthe wrong way
app.add_middleware(    CORSMiddleware,    allow_origins=["*"],    allow_credentials=True,)
pythonapp/main.py
from fastapi.middleware.cors import CORSMiddleware app.add_middleware(    CORSMiddleware,    allow_origins=["https://app.example.com"],    allow_credentials=True,    allow_methods=["GET", "POST"],    allow_headers=["Authorization", "Content-Type"],)

The CORSMiddleware defaults are strict: no origins are allowed, GET is the only method, and there are no extra headers; whatever the API needs is listed explicitly. The CORS mechanism itself is described in the HTTP and REST reference, section “CORS”.

Do not hide the documentation instead of securing the API

A hidden /docs does not protect the API: the operations remain at their addresses, together with the bugs in the code. What protects it is request and response models, permission checks in dependencies, password hashes and tokens. If the documentation still has to be switched off in some environment, set openapi_url from the settings: with an empty value /openapi.json, /docs and /redoc respond with 404.

pythonapp/main.py
class Settings(BaseSettings):    openapi_url: str = "/openapi.json"  settings = Settings()app = FastAPI(openapi_url=settings.openapi_url)

Section sources

the section is written from these pages

Common errors and troubleshooting

Start with the status code and the response body: with a 422 response the detail field says which field failed validation, where and why. Then look at the server log in the terminal: every request is there with its status code, along with tracebacks of unhandled exceptions.

Order of checks

  1. The status code and the body: for a 422, the detail entries with loc and msg.
  2. The Uvicorn log: whether the request arrived, with which status code, and whether there is a traceback.
  3. The operation description in /docs: which parameters it expects and where — in the path, query, headers or body.
  4. If a 422 is unclear, temporarily log the body of the failed request — the handler below.

What the client sent: the validation error log

pythonmain.py
from fastapi import FastAPI, Requestfrom fastapi.encoders import jsonable_encoderfrom fastapi.exceptions import RequestValidationErrorfrom fastapi.responses import JSONResponse app = FastAPI()  @app.exception_handler(RequestValidationError)async def log_validation_error(    request: Request, exc: RequestValidationError):    # log the errors and the body the client sent    print(request.url.path, exc.errors(), exc.body)    return JSONResponse(        status_code=422,        content=jsonable_encoder({"detail": exc.errors()}),    )

FastAPI raises RequestValidationError when the request data fails validation; exc.errors() is the list of errors, exc.body is the body it received. The handler above keeps the usual 422 response and adds a log entry.

Field required

Cause: a required parameter or body field did not arrive where FastAPI expects it. loc shows the place: ["query", "q"] means q was looked for in the query string. A common case is the client sending the value in the JSON body while the argument is declared with a simple type: FastAPI reads arguments that do not come from the path from the query string.

bashcheck
curl -s "http://127.0.0.1:8000/search" | python3 -m json.tool
jsonsample output
{    "detail": [        {            "type": "missing",            "loc": [                "query",                "q"            ],            "msg": "Field required",            "input": null        }    ]}
  • Pass the value where loc points: in the path, query, headers or body.
  • If the parameter is optional, give it a default value: q: str | None = None.
  • If the value must arrive in the body, declare the argument as a Pydantic model.

Input should be a valid integer, unable to parse string as an integer

Cause: the value cannot be converted to the declared type — for example, /items/abc when item_id: int. The same error occurs when a request lands on the wrong path operation: /users/me matches /users/{user_id} if the latter is declared earlier. Route order is covered in the section “Path operations and parameters”.

bashcheck
curl -s "http://127.0.0.1:8000/items/abc"
  • Send a value of the expected type.
  • If the identifier can be non-numeric, declare it as str.
  • Declare path operations with a fixed path before operations with a parameter.

The server stops responding while one request is running

Cause: a blocking call inside async def — time.sleep(), a synchronous HTTP client, a synchronous database driver. Such a function runs right in the event loop, and while it waits, the other requests stand in the queue.

bashcheck: the second waits for the first
curl -s http://127.0.0.1:8000/report &curl -s -o /dev/null -w "%{time_total}\n" http://127.0.0.1:8000/
pythonfix
# was async def: the blocking call held the event loop@app.get("/report")def report():    time.sleep(2)    return {"status": "done"}

Declare such a function with def: FastAPI will run it in a thread pool. Or replace the library with an asynchronous one and call it with await.

The browser blocks a request to the API: a CORS error

Cause: the page is open at a different origin — protocol, domain or port, for example http://localhost:5173 with the API at http://localhost:8000 — and the API has not allowed it. A second common cause is allow_origins=["*"] with requests that carry cookies or an Authorization header: the asterisk does not allow such requests.

bashcheck
curl -i -X OPTIONS http://127.0.0.1:8000/items/ \  -H "Origin: http://localhost:5173" \  -H "Access-Control-Request-Method: GET"

CORSMiddleware answers such a preflight request with 200 if the origin is allowed, and 400 if not. Add the page’s origin to allow_origins as an exact string with the protocol and port, and the methods and headers you need — to allow_methods and allow_headers.

The client got a 500 instead of data: ResponseValidationError

Cause: the returned value does not match the response_model or the return type — for example, the function returns an object without a required field. FastAPI validates the response before sending it and will not hand invalid data to the client: instead there will be a 500 response, and in the server log — fastapi.exceptions.ResponseValidationError with the list of errors. The error means the application code is broken, not that the client did something wrong.

bashcheck: the body says Internal Server Error, the final number is 500
curl -s -w "\n%{http_code}\n" http://127.0.0.1:8000/items/1
  • Compare the returned value with the response_model: the response model drops extra fields, and the error comes from a required field the object does not have.
  • Check that all required fields are filled in before returning.
  • Response models are explained in the section “Request body and response models”.

A 500 response Internal Server Error, and the log is empty

Cause: a dependency with yield caught the exception in an except block and did not raise it further. FastAPI never learns about the error: the client gets a 500, and the server log stays silent.

pythonfix
class InternalError(Exception):    pass  def get_username():    try:        yield "ann"    except InternalError:        print("internal error")        # without the raise the error would vanish from the log        raise

Raise the exception again with raise, or replace it with an HTTPException with a meaningful status code — the client will then get that code instead of a 500.

Section sources

the section is written from these pages

Versions and what is new

This reference covers FastAPI 0.162. The latest release is 0.162.2, from 7 November 2026 (0.162.1 and 0.162.2 are documentation only). Versions are still 0.x: new features and breaking changes arrive in minor releases (the second number), patch releases carry fixes only; only the latest versions are supported.

FastAPI has no branches with separate support periods. Minor releases come out often — twenty of them appeared in October 2026, from 0.143.0 to 0.162.0 — so pin the minor version and upgrade only after tests. The table lists the releases after which code changes are most common.

ReleaseDateWhat breaks on upgrade
0.162.023 October 2026an omitted boolean form field gets its declared default or a missing-field error instead of False; declare bool = False for a checkbox
0.160.022 October 2026extra of the query parameter, header, cookie and form models applies to every field of the same source: with extra="forbid" fields declared next to it are rejected too
0.155.020 October 2026Path, Query, Header, Cookie, Body, Form and File no longer accept arbitrary keyword arguments: a TypeError follows; pass custom schema properties through json_schema_extra
0.151.020 October 2026an explicit null in the JSON body differs from an omitted value: the default is applied only when the field is not sent at all
0.148.019 October 2026defaults of omitted parameters are not validated without validate_default=True and do not count as set in model_dump(exclude_unset=True)
textrequirements.txt
fastapi[standard]>=0.162.0,<0.163.0

This line accepts 0.162.x patch releases and rejects 0.163.0. Do not pin Starlette: each FastAPI version requires a suitable one itself. Pydantic can be capped at a major version, for example pydantic>=2.9.0,<3.0.0.

What changed over the last year

  • Request body and response models: the JSON body is read only when the request carries a JSON Content-Type header such as application/json (since 0.132.0); for older clients, FastAPI(strict_content_type=False).
  • Request body and response models: with a response model or return type, JSON is serialised by Pydantic, which is at least twice as fast (since 0.130.0).
  • Security: without credentials the fastapi.security classes respond with 401 instead of 403 (since 0.122.0).
  • Dependencies: Depends(..., scope="function") closes a yield dependency before the response is sent (since 0.121.0).
  • Path operations and parameters: streaming responses — JSON Lines and binary data via yield (since 0.134.0) and Server-Sent Events (since 0.135.0).
  • Deployment: built-in OpenTelemetry support (since 0.142.0); automatic exporter configuration from OTEL_* variables is enabled explicitly — FASTAPI_OTEL_AUTO_CONFIGURE=true (since 0.143.0).
  • Installation and first run: the tutorial moved to uv projects (0.140.0); the minimum Python version is 3.10 (since 0.129.0).

Deprecated and removed

  • Pydantic v1 is not supported since 0.126.0, and the pydantic.v1 compatibility layer was removed in 0.128.0; the minimum Pydantic version is 2.9.0 (since 0.135.2).
  • The root_path parameter of FastAPI() is deprecated since 0.146.0 — use fastapi run --root-path instead.
  • FastAPI() lost the deprecated openapi_prefix and **extra (0.145.0).
  • ORJSONResponse and UJSONResponse are deprecated since 0.131.0.
  • The fastapi-slim package is no longer published (0.129.2): install fastapi or fastapi[standard] instead.
  • Python 3.8 is not supported since 0.125.0, Python 3.9 — since 0.129.0.

How to upgrade

  1. Cover the application with tests — the “Testing” section.
  2. Read the Breaking Changes sections in the release notes of every minor release between the current and the new version.
  3. Bump the version in your dependencies and run the tests; fix whatever breaks.
  4. Pin the new minor version.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

9 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “FastAPI” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61