FastAPI Tutorial: Build and Deploy Python REST APIs with Docker

FastAPI Tutorial: Build and Deploy Python REST APIs with Docker

Table of content

This FastAPI tutorial covers how to build, validate, secure, and containerize a Python REST API using standard Python type hints, Pydantic models, and the official FastAPI CLI. Because FastAPI inherits directly from Starlette for web routing and relies on Pydantic for data serialization, you can define request validation and generate OpenAPI documentation from a single function signature.

Written for backend developers, software architects, and technical founders, this guide walks you through setting up a local project with uv, managing asynchronous and blocking endpoints, wiring up OAuth2 authentication, and packaging your application into a production-ready Docker image.

What is FastAPI and how does its architecture work?

FastAPI is an open-source, MIT-licensed Python web framework built on Starlette and Pydantic that uses standard Python type hints to validate data and generate OpenAPI documentation. Created by Sebastián Ramírez and maintained by a core team on GitHub, FastAPI is documented at the official FastAPI documentation. FastAPI ships new 0.x releases frequently (0.165.0 as of November 2026), so pin the version in your project and read the release notes before upgrading.

Rather than writing its own HTTP server or validation engine from scratch, FastAPI combines two core Python libraries: – Starlette handles the underlying ASGI web layer, with the FastAPI class inheriting directly from the Starlette class. – Pydantic powers all data validation, serialization, and schema extraction through standard Python type annotations.

Because every route definition is parsed against open API standards, FastAPI is fully compatible with OpenAPI (formerly Swagger) and JSON Schema out of the box. Whether you are reading a FastAPI tutorial for beginners or designing a distributed system, the same architectural primitives apply across workloads. Production systems running on FastAPI include machine learning prediction REST servers, crisis management orchestration frameworks, and core enterprise automation services, with documented production adoption at Microsoft, Uber, Netflix (for its Dispatch project), and Cisco.

How to install and run a FastAPI application with uv

You install FastAPI using uv add "fastapi[standard]" and launch the local auto-reloading Uvicorn server by running uv run fastapi dev. If you use traditional virtual environments instead of a fastapi uv install workflow, the equivalent command is pip install "fastapi[standard]".

Installing the fastapi[standard] distribution bundles the core framework alongside optional standard dependencies that most web APIs need: 1. uvicorn[standard] as the high-performance ASGI server. 2. fastapi-cli[standard], which provides the fastapi terminal command and includes fastapi-cloud-cli. 3. email-validator for Pydantic email type checks. 4. httpx, jinja2, and python-multipart for Starlette testing, templating, and form parsing.

If you want those standard libraries without installing fastapi-cloud-cli, run uv add "fastapi[standard-no-fastapi-cloud-cli]". If you prefer to manage every dependency manually, install the bare framework with uv add fastapi.

Once installed, create a main.py file with a basic route:

from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
async def check_health():
    return {"status": "ok"}

To run the application locally and inspect the FastAPI Swagger UI docs, follow these steps: 1. Run uv run fastapi dev in your terminal, which automatically detects the FastAPI instance inside main.py and starts a local Uvicorn development server at http://127.0.0.1:8000 with auto-reload enabled. 2. Open http://127.0.0.1:8000/docs in your browser to interact with the automatically generated Swagger UI interface, or visit http://127.0.0.1:8000/redoc to view the alternative ReDoc interface. 3. Switch from fastapi dev to fastapi run (for example, fastapi run app/main.py --port 80) when moving to a production environment so the server runs without development auto-reloading.

Understanding fastapi dev vs fastapi run prevents accidental deployment of development file watchers in production containers. For teams that want managed hosting instead of self-hosted servers, FastAPI Cloud (built by the same creator and team behind FastAPI and acting as the primary sponsor of the open-source project) lets you deploy an application with a single uv run fastapi deploy command. If you use AI coding assistants such as Claude Code, Cursor, GitHub Copilot, Codex, or Gemini CLI, FastAPI also bundles an official AI Agent Skill inside the package that you can install via uvx library-skills to keep generated code aligned with your installed FastAPI version.

Data validation and serialization with Pydantic BaseModel

Declaring path operation arguments as Pydantic BaseModel subclasses enables automatic JSON parsing, deep data validation, editor autocompletion, and OpenAPI schema generation from a single Python class. In any Python FastAPI REST API tutorial, this declarative model layer replaces manual dictionary inspection and repetitive try/except parsing blocks.

When a client sends a JSON payload to your endpoint, FastAPI passes the incoming body through your BaseModel definition. FastAPI Pydantic BaseModel validation works even for deeply nested JSON objects, converting input types to their declared Python equivalents, rejecting invalid payloads with structured error messages, and documenting the exact JSON Schema in Swagger UI at /docs and ReDoc at /redoc.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class WarehouseLocation(BaseModel):
    aisle: str
    bin_number: int

class InventoryItem(BaseModel):
    sku: str
    quantity: int
    unit_price: float
    tags: list[str] = []
    location: WarehouseLocation

@app.post("/items/")
async def create_item(item: InventoryItem) -> InventoryItem:
    return item

In the snippet above, declaring item: InventoryItem as a function argument gives you static type checks and full editor autocompletion when accessing attributes like item.location.bin_number. FastAPI handles both input conversion from the HTTP request and output conversion when serializing the response back to JSON.

When to use async def vs def in FastAPI path operations

Use async def for non-blocking coroutines or trivial compute-only endpoints, and use plain def for functions that perform blocking I/O so FastAPI runs them in an external threadpool without stalling the event loop. Under the hood, Starlette and FastAPI are built on AnyIO, which makes FastAPI compatible with both Python’s standard library asyncio and Trio.

Choosing between fastapi async def vs def depends on what happens inside the function body and how FastAPI dispatches the call. As detailed in the FastAPI concurrency and async/await guide, you can freely mix def and async def across path operation functions and dependencies within the same application: – When you declare a path operation function or a dependency with normal def, FastAPI executes it in an external threadpool and awaits the result, preventing synchronous database drivers or file reads from blocking the main server event loop. – When you declare a path operation function with async def, FastAPI runs it directly on the event loop as a coroutine. – If a path operation function performs only trivial in-memory computation and does not call any blocking I/O, define it with async def rather than plain def so you avoid the performance overhead of dispatching the call to an external threadpool. – Only path operation functions and dependencies managed by FastAPI are automatically sent to the external threadpool when declared with def; regular utility functions that you call directly inside your own code execute inline unless you offload them yourself.

from fastapi import Depends, FastAPI

app = FastAPI()

def sync_db_lookup():
    # Managed by FastAPI Depends(): runs in an external threadpool
    return {"db_status": "connected"}

@app.get("/compute")
async def fast_in_memory_check():
    # Trivial compute-only route: use async def to avoid threadpool overhead
    return {"ready": True}

@app.get("/records")
def read_blocking_records(status: dict = Depends(sync_db_lookup)):
    # Blocking I/O route: use def so FastAPI runs it in an external threadpool
    return status

Implementing OAuth2 password flow and JWT authentication

FastAPI provides built-in fastapi.security utilities like OAuth2PasswordBearer and OAuth2PasswordRequestForm that plug directly into its Depends() dependency injection system to secure endpoints over HTTPS. Beyond the OAuth2 password flow, fastapi.security also includes utilities for fine-grained OAuth2 scopes and HTTP Basic Auth.

When configuring FastAPI OAuth2 JWT authentication, keep two protocol requirements in mind. First, the OAuth2 specification requires sending the username and password fields as form data rather than a JSON body, which means your environment must have the python-multipart package installed. If you installed the framework via fastapi[standard], python-multipart is already included. Second, because OAuth2 does not encrypt network traffic by itself, you must serve the application over HTTPS in production.

from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.post("/token")
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
    if form_data.username != "admin" or form_data.password != "secret":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Incorrect username or password",
        )
    return {"access_token": form_data.username, "token_type": "bearer"}

@app.get("/users/me")
async def read_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
    return {"active_token": token}

Because oauth2_scheme is injected through Depends(), FastAPI automatically updates the OpenAPI schema and adds an interactive “Authorize” button to Swagger UI at /docs.

FastAPI Docker deployment: writing a production Dockerfile

A production FastAPI Docker image should start from the official Python base image, cache dependencies via requirements.txt before copying application code, and launch the server using the exec form of CMD ["fastapi", "run"]. Previously, many teams relied on the tiangolo/uvicorn-gunicorn-fastapi base image, but that image is now deprecated; the official FastAPI Docker deployment guide recommends building your container from scratch starting with an official Python image such as FROM python:3.14.

To prepare a FastAPI Dockerfile example that maximizes Docker build layer caching, follow this sequence: 1. If you manage dependencies with uv, export your lockfile to a flat requirements file by running uv export --format requirements-txt --no-dev --no-emit-project --output-file requirements.txt. 2. Copy requirements.txt into /code/requirements.txt and run pip install --no-cache-dir --upgrade -r /code/requirements.txt before copying the ./app directory, ensuring Docker only reinstalls packages when dependencies actually change. 3. Copy your ./app code into /code/app. 4. Define the startup command using the exec form CMD ["fastapi", "run", "app/main.py", "--port", "80"].

FROM python:3.14

WORKDIR /code

COPY ./requirements.txt /code/requirements.txt

RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

COPY ./app /code/app

CMD ["fastapi", "run", "app/main.py", "--port", "80"]

Always use the JSON array exec form for CMD rather than the shell form (such as CMD fastapi run app/main.py). Using the shell form is a common pitfall that stops process signals from reaching Uvicorn, which prevents graceful shutdown and blocks FastAPI lifespan events from triggering.

How you configure workers and proxy flags in a FastAPI Docker Compose deployment or container cluster depends on your infrastructure topology: – When deploying to a cluster environment such as Kubernetes, Docker Swarm Mode, or Nomad, run a single Uvicorn process per container and handle replication at the cluster level. – When running a single container on a single server that needs multiple processes to use available CPU cores, pass the --workers flag to fastapi run. – When running your container behind a TLS Termination Proxy or load balancer such as Nginx or Traefik, pass --proxy-headers to fastapi run so Uvicorn trusts the upstream headers indicating HTTPS.

FastAPI vs Flask vs Django for building REST APIs

FastAPI combines the unopinionated microframework flexibility of Flask with native ASGI concurrency, built-in Pydantic data validation, and automatic OpenAPI generation that neither Flask nor core Django provides out of the box. When evaluating fastapi vs flask vs django for a new Python backend, the architectural differences center on database coupling, protocol support, and serialization.

Criterion FastAPI Flask Django
Primary design goal High-performance APIs based on standard Python type hints Microframework for general web applications Full-stack framework built primarily to generate backend HTML
Execution model and protocol Native ASGI async performance built on Starlette and AnyIO (asyncio and Trio) Microframework without native ASGI validation/docs integration Monolithic web framework
Data validation and serialization Built-in via Pydantic Lacks built-in data validation Coupled to internal forms and relational models
Interactive API documentation Automatic OpenAPI schema with Swagger UI (/docs) and ReDoc (/redoc) Lacks automatic API documentation Lacks built-in OpenAPI generation
Database coupling Uncoupled microframework design Uncoupled microframework design Tightly coupled with relational databases
Best-fit workload REST APIs, ML prediction servers, orchestration and automation services Lightweight synchronous web services Database-driven applications rendering server-side HTML

Because Django is tightly coupled with relational databases and designed around server-rendered HTML, and Flask requires third-party extensions to add data validation or API documentation, FastAPI is purpose-built for teams shipping JSON REST APIs and microservices.

Frequently asked questions

Here are direct answers to the most common engineering questions about configuring, securing, and containerizing FastAPI services.

Why is the tiangolo/uvicorn-gunicorn-fastapi Docker image deprecated?

The tiangolo/uvicorn-gunicorn-fastapi image is deprecated because the official FastAPI recommendation is to build images directly from the official Python base image (such as FROM python:3.14) and invoke fastapi run. In cluster environments like Kubernetes, Docker Swarm Mode, or Nomad, process replication should be managed at the cluster level with a single Uvicorn process per container, while single-server deployments can pass --workers directly to fastapi run without needing a Gunicorn wrapper image.

What is the difference between fastapi dev and fastapi run?

fastapi dev starts a local Uvicorn server at http://127.0.0.1:8000 with auto-reload enabled for local development, whereas fastapi run starts the server in production mode without development auto-reloading. Both commands are provided by the FastAPI CLI and automatically detect the FastAPI application instance.

Why does my FastAPI Docker container ignore graceful shutdown signals?

Your container ignores termination signals if your Dockerfile uses the shell form of the CMD instruction instead of the exec form. Switching to the JSON bracket exec form, such as CMD ["fastapi", "run", "app/main.py", "--port", "80"], ensures the process receives OS signals directly so graceful shutdown and FastAPI lifespan events trigger properly.

Why does FastAPI OAuth2 password login require python-multipart?

OAuth2 password flow sends the username and password fields as HTTP form data rather than a JSON payload, and Starlette relies on python-multipart to parse incoming form data. Installing fastapi[standard] automatically includes python-multipart in your environment.

How do I view the automatic Swagger UI and ReDoc documentation?

Once your FastAPI server is running, go to /docs in your browser to open the interactive Swagger UI or /redoc to open ReDoc. Both interfaces are generated automatically from your Python type hints and Pydantic models using the OpenAPI and JSON Schema standards.

Taking a FastAPI service to production

A tutorial API becomes a production service once it has migrations, background jobs, observability, rate limiting, and a deployment pipeline around it. If you are building APIs or AI backends in Python, see our Python development page, or get in touch about our custom API development services.

Related case study

Custom Software Development Company for Travel and Hospitality
Travel and Hospitality
More than fifteen years of custom software for clubs, private travel organizations, and hospitality companies, covering operations, member management, and integrations.

Related articles

What Is an API Wrapper? A Business Guide to Building One
An API wrapper simplifies how your application communicates with external services- reducing complexity, improving reliability, and making your codebase easier to maintain and scale.
SDK vs API: What Are the Key Differences?
Understanding the difference between SDK and API is crucial for your project. Learn what a software development kit and API are to make the right choice.
What is API Development
Learn what is API development and why it's crucial. Discover how APIs act as intermediaries, allowing different software applications to communicate seamlessly.
API Software Development Services

Have a project in mind?

REST and GraphQL APIs that connect your apps and third-party services, documented and secure.