Pynions

FastAPI From First Endpoint to Production: A Tested 0.165 Guide

Learn FastAPI with code tested on 0.165.2: endpoints, Pydantic models, dependency injection, the async def trap, tests, body limits, and deployment.

Updated 14 min read
Python source code on a dark editor screen

FastAPI is a Python web framework for building APIs from standard type hints. Its documentation credits Starlette "for the web parts" and Pydantic "for the data parts": you annotate a function's parameters, and FastAPI validates requests, serializes responses, and writes OpenAPI docs from those annotations.

The current release is FastAPI 0.165.2, published on 5 December 2026, and the package logged 561,502,070 downloads in the last month as of 6 December 2026. Every code block in this guide ran on Python 3.15.2 with FastAPI 0.165.2, Starlette 1.10.0, Pydantic 2.14.4, and Uvicorn 0.55.0.

This guide goes from a first endpoint to request models, dependency injection, a measured async def mistake, tests, request limits, and deployment with workers.

Key Takeaways

  • Install fastapi[standard], not fastapi uvicorn. The extra brings the fastapi CLI, Uvicorn, HTTPX for tests, and the OpenTelemetry SDK.
  • Use fastapi dev while you code and fastapi run in production. Both start Uvicorn; only dev reloads on file changes.
  • A blocking call inside async def stalls every request. In our test, 10 concurrent requests took 10.0 seconds with time.sleep(1) in an async def handler and 1.0 second as a plain def.
  • Late-2026 releases added production guards: Depends(max_concurrency=...) in 0.163.0, max_body_size in 0.164.0, and form_limits in 0.165.0.
  • FastAPI 0.162.6 dropped Python 3.10. FastAPI 0.165.2 needs Python 3.11 or newer.

What Is FastAPI?

FastAPI is an ASGI framework: it runs on an async server such as Uvicorn and handles HTTP and WebSocket requests. The FastAPI home page describes it as "a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints."

You write plain functions and decorate them with an HTTP method and a path. FastAPI reads each parameter's type and default to decide where the value comes from: the path, query string, header, or JSON body. It converts the value, and when the input is wrong it returns a 422 error naming the exact field.

The project is free and MIT licensed, with 105,279 GitHub stars as of 6 December 2026. Sebastián Ramírez (@tiangolo) created it. The docs describe FastAPI Cloud as built "by the same author and team behind FastAPI" and as "the primary sponsor and funding provider for the FastAPI and friends open source projects."

Why FastAPI Matters in 2027

FastAPI turns type hints into validation and documentation without a second schema file. The home page quotes production users at Microsoft (ML services), Uber (Ludwig prediction serving), Netflix (its Dispatch crisis management tool), and Cisco.

The 2026 releases moved FastAPI toward operations work. Version 0.142.0 added native OpenTelemetry for request traces, metrics, and logs, and the 0.163 to 0.165 releases added limits for dependency concurrency, request body size, and form parsing. Tutorials written before those releases still work, but they skip the settings you need before real traffic arrives.

Package

Version tested

Role

fastapi

0.165.2

Routing, validation, dependency injection, OpenAPI

starlette

1.10.0

ASGI toolkit underneath (requests, middleware, WebSockets)

pydantic

2.14.4

Request and response models

uvicorn

0.55.0

ASGI server started by fastapi dev and fastapi run

fastapi-cli

0.0.34

The fastapi command

httpx

0.29.0

Powers TestClient

How FastAPI Works: Install, First Endpoint, and Errors

Three steps take you from an empty folder to a documented API: install the package, write one file, and start the dev server.

Install FastAPI 0.165.2

Create a virtual environment and install the standard extra. Keep the quotes so your shell does not read the square brackets:

Shell
python3 -m venv .venv
source .venv/bin/activate
pip install "fastapi[standard]==0.165.2"

With uv, the docs use uv add "fastapi[standard]" inside a project instead. FastAPI 0.165.2 requires Python 3.11 or newer, so check python3 --version first.

Your First FastAPI Endpoint

Save this as main.py. It is the example from the FastAPI home page:

Python
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}

Start the development server. fastapi dev finds the app object in main.py, starts Uvicorn on port 8000, and reloads when you save a file:

Shell
fastapi dev main.py

In a second terminal, call the endpoint:

Shell
curl "http://127.0.0.1:8000/items/5?q=somequery"
Text
{"item_id":5,"q":"somequery"}

item_id came from the path and was converted to an integer. q came from the query string because it is not in the path, and it is optional because its default is None.

Read a FastAPI Validation Error

Send a value that is not an integer:

Shell
curl "http://127.0.0.1:8000/items/foo"
Text
{"detail":[{"type":"int_parsing","loc":["path","item_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"foo"}]}

The response status is 422 Unprocessable Content. loc tells the client where the bad value was (path, then item_id), and type is a stable code you can match in client code. Your function never ran.

The Automatic Docs

Open http://127.0.0.1:8000/docs for Swagger UI or http://127.0.0.1:8000/redoc for ReDoc. Both read the OpenAPI 3.1 schema FastAPI serves at /openapi.json, so they update when you change a type hint.

FastAPI documentation home page

Request Bodies and Response Models With Pydantic

Path and query parameters cover reads. For writes, declare a Pydantic model as a parameter and FastAPI reads it from the JSON body. Save this as tasks.py:

Python
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field

app = FastAPI(title="Tasks API")


class TaskIn(BaseModel):
    title: str = Field(min_length=1, max_length=100)
    priority: int = Field(default=3, ge=1, le=5)
    internal_note: str | None = None


class TaskOut(BaseModel):
    id: int
    title: str
    priority: int
    done: bool = False


tasks: dict[int, dict] = {}


@app.post("/tasks", response_model=TaskOut, status_code=status.HTTP_201_CREATED)
def create_task(task: TaskIn):
    task_id = len(tasks) + 1
    tasks[task_id] = {"id": task_id, **task.model_dump()}
    return tasks[task_id]


@app.get("/tasks/{task_id}", response_model=TaskOut)
def read_task(task_id: int):
    if task_id not in tasks:
        raise HTTPException(status_code=404, detail="Task not found")
    return tasks[task_id]

Run it with fastapi dev tasks.py and create a task:

Shell
curl -X POST http://127.0.0.1:8000/tasks \
  -H "Content-Type: application/json" \
  -d '{"title": "Ship the API", "priority": 2, "internal_note": "only for admins"}'
Text
{"id":1,"title":"Ship the API","priority":2,"done":false}

Response Models Filter Output

The stored dict still holds internal_note, but the response does not. response_model=TaskOut makes FastAPI validate the return value against TaskOut and drop every field the model does not declare. Use a separate output model whenever a record holds something the client should not see, such as a password hash.

Constraints Become 422 Errors

Field(ge=1, le=5) limits priority. A value of 9 never reaches your function:

Shell
curl -X POST http://127.0.0.1:8000/tasks \
  -H "Content-Type: application/json" \
  -d '{"title": "Too urgent", "priority": 9}'
Text
{"detail":[{"type":"less_than_equal","loc":["body","priority"],"msg":"Input should be less than or equal to 5","input":9,"ctx":{"le":5}}]}

For a missing record, raise HTTPException. curl http://127.0.0.1:8000/tasks/42 returns status 404 with {"detail":"Task not found"}.

Keep the Content-Type: application/json header in your clients.

Since 0.132.0, FastAPI checks it by default (strict_content_type) and rejects JSON requests without a valid JSON content type. The strict Content-Type docs say the check "helps protect JSON endpoints against cross-site request forgery (CSRF)" for apps on localhost or an internal network. The Pydantic guide covers validators, strict mode, and serialization in depth.

FastAPI Dependency Injection With Depends

The dependencies tutorial calls this "a very powerful but intuitive Dependency Injection system." A dependency is a function whose parameters FastAPI resolves like an endpoint's, and whose return value it passes into your endpoint. Use dependencies for anything several routes share: pagination, authentication, and database sessions.

Save this as deps.py:

Python
import os
from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException

app = FastAPI()


def pagination(skip: int = 0, limit: int = 10) -> dict:
    return {"skip": skip, "limit": min(limit, 100)}


def require_api_key(x_api_key: Annotated[str, Header()]) -> None:
    if x_api_key != os.environ.get("API_KEY", "dev-key"):
        raise HTTPException(status_code=401, detail="Invalid API key")


class Session:
    def __init__(self):
        self.is_open = True

    def close(self):
        self.is_open = False
        print("session closed")


def get_session():
    session = Session()
    try:
        yield session
    finally:
        session.close()


Pagination = Annotated[dict, Depends(pagination)]
SessionDep = Annotated[Session, Depends(get_session, max_concurrency=5)]


@app.get("/tasks", dependencies=[Depends(require_api_key)])
def list_tasks(page: Pagination, session: SessionDep):
    return {"page": page, "session_open": session.is_open}

Call it with and without the key:

Shell
curl "http://127.0.0.1:8000/tasks?skip=20&limit=500" -H "X-API-Key: dev-key"
curl "http://127.0.0.1:8000/tasks" -H "X-API-Key: wrong"
Text
{"page":{"skip":20,"limit":100},"session_open":true}
{"detail":"Invalid API key"}

Annotated Aliases Keep Routes Short

Pagination and SessionDep are type aliases built with Annotated. Every route that takes page: Pagination gets the same query parameters and the same cap of 100. It also gets the same entry in the OpenAPI docs. Header() turns the x_api_key parameter into the X-API-Key header, and a request without it gets a 422 that names header and x-api-key.

Dependencies With yield Clean Up

get_session yields instead of returning. FastAPI runs the code before yield, injects the session, and runs the finally block after the endpoint finishes, so the server log prints session closed after each request that opened a session. That is the pattern for database sessions and file handles.

Limit Concurrency With max_concurrency

Depends(get_session, max_concurrency=5) was added in 0.163.0. The advanced dependencies docs describe it as a way to keep requests from opening more sessions than your database allows. A sixth request waits until one of the first five finishes, and "it doesn't occupy a worker thread" while it waits.

We checked the behavior with a 0.5 second async dependency and max_concurrency=2: six concurrent requests took 1.51 seconds, three waves of two. The limit is per Depends() object, so reuse one alias like SessionDep to share it across routes. Each worker process keeps its own count, so four workers allow up to 20 open sessions.

Async in FastAPI: The Blocking Call Trap

FastAPI accepts both def and async def endpoints and treats them differently. The async docs say a plain def endpoint "is run in an external threadpool that is then awaited," while an async def endpoint runs on the event loop itself. A blocking call inside async def therefore holds the whole loop.

We measured it. Save this as blocking.py:

Python
import asyncio
import time

from fastapi import FastAPI

app = FastAPI()


@app.get("/async-blocking")
async def async_blocking():
    time.sleep(1)  # blocks the event loop
    return {"ok": True}


@app.get("/sync-blocking")
def sync_blocking():
    time.sleep(1)  # runs in the threadpool
    return {"ok": True}


@app.get("/async-nonblocking")
async def async_nonblocking():
    await asyncio.sleep(1)  # yields to the event loop
    return {"ok": True}

Start it with fastapi run blocking.py, then save this load script as load.py and run python load.py in a second terminal:

Python
import asyncio
import time

import httpx


async def hit(path: str, n: int = 10) -> float:
    async with httpx.AsyncClient(base_url="http://127.0.0.1:8000", timeout=30) as client:
        start = time.perf_counter()
        await asyncio.gather(*(client.get(path) for _ in range(n)))
        return time.perf_counter() - start


async def main():
    for path in ("/async-blocking", "/sync-blocking", "/async-nonblocking"):
        print(f"{path:<20} 10 requests in {await hit(path):.1f}s")


asyncio.run(main())
Text
/async-blocking      10 requests in 10.0s
/sync-blocking       10 requests in 1.0s
/async-nonblocking   10 requests in 1.0s

All three runs on our 8 vCPU box gave the same numbers. The async def handler with time.sleep(1) served the 10 requests one after another. The plain def version ran them in parallel threads, and the async def version with await asyncio.sleep(1) let the loop interleave them.

Which One to Use

Your endpoint calls

Declare it as

Why

Async libraries you await (httpx.AsyncClient, asyncpg, async SQLAlchemy)

async def

Runs on the event loop with no thread overhead

Blocking libraries (requests, most sync database drivers, file I/O, time.sleep)

def

FastAPI moves it to a threadpool

Only quick in-memory work

async def

The docs recommend async def for trivial compute-only functions

You are not sure

def

The docs' rule: "If you just don't know, use normal def."

The same rule applies to dependencies: a def dependency also runs in the threadpool.

Organize a Bigger FastAPI App

One file stops working once you have more than a handful of routes. APIRouter groups routes under a prefix and tag, and you mount each router on the app. Save this as users.py:

Python
from fastapi import APIRouter, FastAPI

router = APIRouter(prefix="/users", tags=["users"])


@router.get("/")
def list_users():
    return [{"username": "ada"}, {"username": "linus"}]


@router.get("/{username}")
def read_user(username: str):
    return {"username": username}


app = FastAPI()
app.include_router(router)

curl http://127.0.0.1:8000/users/ada returns {"username":"ada"}, and both routes appear under a "users" section in /docs. In a real project, each router lives in its own module (app/routers/users.py) and main.py only creates the app and calls include_router. The bigger applications tutorial shows the full layout.

Startup and Shutdown With lifespan

Resources that live for the whole process, such as a connection pool, an HTTP client, or a loaded ML model, belong in a lifespan function. Save this as lifespan_app.py:

Python
from contextlib import asynccontextmanager

from fastapi import FastAPI

resources = {}


@asynccontextmanager
async def lifespan(app: FastAPI):
    resources["greeting"] = "loaded once at startup"
    print("startup complete")
    yield
    resources.clear()
    print("resources released")


app = FastAPI(lifespan=lifespan)


@app.get("/status")
async def status():
    return {"greeting": resources["greeting"]}

Run it with fastapi run lifespan_app.py.

The log prints startup complete before Uvicorn accepts requests, /status returns {"greeting":"loaded once at startup"}, and pressing Ctrl+C prints resources released before the process exits. The lifespan docs use the same pattern to load and unload a model. If context managers are new to you, the yield line is the boundary between startup and shutdown.

On r/Python, u/latkde wrote that "Where FastAPI really sucks is dealing with configuration and application state," and that "The correct solution is to define a Starlette-level lifespan context manager that yields an application state." That matches the docs: request-level resources go in dependencies, process-level resources go in lifespan.

Background Tasks

For small jobs that can finish after the response, such as writing a log line or sending a notification email, take a BackgroundTasks parameter. Save this as background.py:

Python
from fastapi import BackgroundTasks, FastAPI

app = FastAPI()


def write_log(message: str):
    with open("log.txt", "a") as log:
        log.write(message + "\n")


@app.post("/notify/{email}")
def notify(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_log, f"notification sent to {email}")
    return {"message": "Notification queued"}

curl -X POST http://127.0.0.1:8000/notify/[email protected] returns {"message":"Notification queued"}, and log.txt then contains notification sent to [email protected]. Background tasks run in the same process. For heavy work, the background tasks docs point you to "other bigger tools like Celery."

Test a FastAPI App With TestClient

TestClient calls your app in-process, with no server running. The testing docs note it "is based on HTTPX," which fastapi[standard] already installs. Add pytest with pip install pytest, then save this next to tasks.py as test_tasks.py:

Python
from fastapi.testclient import TestClient

from tasks import app

client = TestClient(app)


def test_create_task_hides_internal_note():
    response = client.post("/tasks", json={"title": "Write tests", "internal_note": "x"})
    assert response.status_code == 201
    assert "internal_note" not in response.json()


def test_priority_out_of_range_is_rejected():
    response = client.post("/tasks", json={"title": "Too urgent", "priority": 9})
    assert response.status_code == 422
    assert response.json()["detail"][0]["type"] == "less_than_equal"


def test_missing_task_returns_404():
    response = client.get("/tasks/999")
    assert response.status_code == 404
    assert response.json() == {"detail": "Task not found"}
Shell
pytest -q test_tasks.py
Text
...                                                                      [100%]
3 passed in 0.25s

The test functions are plain def, and client.post is a normal call with no await. Our pytest vs unittest comparison explains why pytest is the default here.

Production Settings: Limits, CORS, and Telemetry

A tutorial app accepts any body size and any origin. Set both before you expose the API.

Cap Request Body Size

Since 0.164.0, you can set max_body_size in bytes on the app, a router, or one route. If you set no limit anywhere, FastAPI leaves the body size unlimited, according to the request body limits docs. Save this as limits.py:

Python
from fastapi import FastAPI, UploadFile

app = FastAPI(max_body_size=1024 * 1024)  # 1 MiB for every route


@app.post("/items")
def create_item(item: dict):
    return {"keys": len(item)}


@app.post("/upload", max_body_size=20 * 1024 * 1024)  # 20 MiB here
def upload(file: UploadFile):
    return {"filename": file.filename, "size": file.size}

We posted a 2 MB JSON file to /items and got status 413 with the body Content Too Large. A 5,000,000-byte file sent to /upload returned {"filename":"report.bin","size":5000000} because that route has its own 20 MiB limit. Version 0.165.0 added form_limits for form parsing, with defaults of 1,000 fields, 1,000 files, and 1 MiB per text field.

Allow Only Your Frontend Origins

Browsers block cross-origin calls unless the API answers with CORS headers. Add Starlette's CORSMiddleware with an explicit list of origins. Save this as cors_app.py:

Python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173", "https://app.example.com"],
    allow_methods=["GET", "POST"],
    allow_headers=["Content-Type", "Authorization"],
)


@app.get("/ping")
def ping():
    return {"pong": True}

A preflight OPTIONS request from http://localhost:5173 returned 200 with access-control-allow-origin: http://localhost:5173. The same request from https://evil.example returned 400 with Disallowed CORS origin. The CORS docs cover wildcards and credentials.

Turn On OpenTelemetry Export

Since 0.142.0, FastAPI provides OpenTelemetry support by default for request traces, metrics, and logs, and you choose where to send them.

The OpenTelemetry docs set three environment variables: FASTAPI_OTEL_AUTO_CONFIGURE=true, OTEL_SERVICE_NAME for your app's name, and OTEL_EXPORTER_OTLP_ENDPOINT for your collector. Automatic exporter setup has been opt-in since 0.143.0, so FastAPI configures no exporter until you set them.

Creator Sebastián Ramírez put it this way on X: "You always want metrics, there's just not enough time to always set it all up. Now it's just there, by default."

Deploy FastAPI: fastapi run, Workers, and Containers

fastapi run is the production command. The FastAPI CLI docs say it disables auto-reload and listens on 0.0.0.0, and the manual deployment docs show it serving on port 8000. To use several CPU cores on one machine, start worker processes:

Shell
fastapi run --workers 4 main.py

The log shows Started parent process followed by four Started server process lines, one per worker. Each worker is a separate Python process with its own memory, its own lifespan, and its own max_concurrency counts.

Where you deploy

Command

Notes from the docs

One VM or bare server

fastapi run --workers 4 main.py

Workers use multiple cores; put a TLS proxy in front

Docker or Kubernetes

fastapi run app/main.py --port 80 per container

On Kubernetes, the docs say you "will probably not want to use workers" and run one Uvicorn process per container

Behind Nginx or Traefik

add --proxy-headers

Trusts the proxy's forwarded headers

FastAPI Cloud

fastapi deploy

The hosting service from FastAPI's own team

The Docker docs build from the official python:3.14 image, copy and install requirements.txt first for layer caching, then copy the app and run CMD ["fastapi", "run", "app/main.py", "--port", "80"]. You can also pin the entry point once in pyproject.toml with [tool.fastapi] and entrypoint = "main:app", as the FastAPI CLI docs show, so fastapi dev and fastapi run need no file argument.

Other ASGI servers work too: the docs list Hypercorn (HTTP/2 and Trio) and Granian (a Rust HTTP server) as alternatives to Uvicorn.

FastAPI vs Flask and Django

FastAPI is built for APIs. Flask is a smaller WSGI framework, and Django is a full framework with an ORM, admin, and templates.

The FastAPI benchmarks page cites independent TechEmpower benchmarks that show FastAPI under Uvicorn as "one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves." It also notes that FastAPI "cannot be faster than" Starlette because it runs on top of it.


FastAPI

Flask

Django

Built for

JSON APIs

Small web apps and APIs

Full web apps

Request validation

Built in (Pydantic)

Add a library

Forms, or Django REST Framework

API docs

Automatic OpenAPI, Swagger UI, ReDoc

Add a library

Add a library

Async endpoints

Native (ASGI)

async def views since 2.0 with flask[async]; each request still ties up one worker

Async views; the ORM runs queries asynchronously with some exceptions

ORM and admin

None, bring your own

None

Built in

On r/Python, one commenter wrote: "For a new backend today I would default to FastAPI, but existing Flask codebases are not going anywhere." The full trade-offs are in our FastAPI vs Flask and FastAPI vs Django comparisons.

Common FastAPI Mistakes to Avoid

Calling a Blocking Library Inside async def

requests.get(), a sync database driver, or time.sleep() inside async def blocks every other request, as the 10.0 second test above shows. Declare the endpoint with def, or switch to an async client such as httpx.AsyncClient.

Installing fastapi Without the standard Extra

With plain pip install fastapi, the fastapi command only prints To use the fastapi command, please install "fastapi[standard]", and Uvicorn, python-multipart, and email-validator are missing. Install "fastapi[standard]", or add uvicorn and python-multipart yourself if you need a minimal image.

Returning Database Rows Without a Response Model

Returning a full record sends every column, including password hashes and internal notes. Declare response_model (or a return type) with only the public fields, as TaskOut does above.

Storing Shared Resources in Module Globals Without lifespan

A connection pool created at import time is not closed on shutdown, and each worker creates its own copy. Open it in lifespan before yield and close it after.

Leaving Body Size Unlimited

With no max_body_size, FastAPI reads bodies of any size. Set an app-wide default and raise it only on the upload routes.

Frequently Asked Questions

Sources

Related Articles