Przejdź do treści

Główna treść tej strony jest po angielsku.Przetłumacz tę stronę

Umiejętności i technologie

FastAPI roadmap

FastAPI is the most popular modern Python web framework, especially for AI services. Learn routes, validation, databases, auth, testing and deployment.

Czas
⏱ 3–4 weeks
Level
Intermediate
Steps
6 steps
Architecture ↓Cheat sheet ↓6 interview Q&As ↓
Udostępnij

The roadmap

Click a step to open the full guide.

Best architecture: a production FastAPI service

How a FastAPI app is structured and deployed.

FastAPI service

  1. Reverse proxy / load balancer (TLS)
  2. FastAPI workers (Uvicorn)
  3. Routers → services → repositories
  4. PostgreSQL (pooled) · Redis
  5. Task queue workers

Why it's built this way

  • Split by routers per feature; inject dependencies with Depends.
  • Run multiple workers behind a load balancer.
  • Use async drivers and connection pooling.
  • Move slow work to a task queue.

FastAPI cheat sheet

The essentials on one screen. Bookmark it for revision.

Code patterns

Appapp = FastAPI()
GET route@app.get("/items/{id}")
Body modelclass Item(BaseModel): name: str
Response model@app.get(..., response_model=ItemOut)
Dependencydb: Session = Depends(get_db)
Errorraise HTTPException(404, "Not found")
Status code@app.post(..., status_code=201)
Routerrouter = APIRouter(prefix="/users")

Commands

Dev serverfastapi dev main.py
Productionfastapi run main.py --workers 4
Docs/docs (Swagger) and /redoc
New migrationalembic revision --autogenerate -m "msg"
Apply migrationsalembic upgrade head

Improve performance

  • Use async database drivers and HTTP clients in async def routes.
  • Use connection pooling for the database; don't open a connection per query.
  • Cache hot reads in Redis; return only needed fields (response models).
  • Paginate list endpoints; never return thousands of rows.
  • Move slow work (emails, reports, AI batch jobs) to a background queue.
  • Run multiple workers and enable gzip for large responses.

Security checklist

  • Hash passwords with bcrypt/Argon2; never store them in plain text.
  • Validate every input with Pydantic; use response models to avoid leaking fields.
  • Restrict CORS to known origins; use HTTPS everywhere.
  • Short-lived tokens, refresh tokens and role checks in dependencies.
  • Rate limit login and expensive endpoints.
  • Keep secrets in environment variables; disable debug in production.

Most important interview questions

Click a question to see a strong answer. Each step also has its own questions.

1Czym jest FastAPI built on?

Starlette (ASGI web toolkit) for the web layer and Pydantic for data validation and serialisation.

2How does FastAPI validate requests?

From type hints and Pydantic models on route parameters; invalid input automatically returns a 422 with details.

3Explain dependency injection in FastAPI.

Routes declare dependencies with Depends; FastAPI resolves them per request (and their sub-dependencies), handles clean-up, and lets you override them in tests.

4How do you structure a large FastAPI project?

Split into routers by feature, separate schemas, services and data access, centralise settings and dependencies, and keep tests per feature.

5How do you handle long-running tasks?

BackgroundTasks for quick follow-ups; a task queue (Celery, RQ, Arq or a cloud queue) for heavy or retryable jobs, returning a job ID to poll.

6FastAPI vs Django vs Flask?

FastAPI: modern async APIs with validation and docs. Django: full-stack framework with ORM and admin. Flask: minimal and flexible, more manual setup.

Related map drogowych

1

FastAPI · Step 1 of 6 · 3 days

First API and automatic docs

Routes, path and query parameters.

FastAPI uses Python type hints to validate input and generate interactive documentation at /docs. You can test your API in the browser without extra tools.

What you'll learn

  • Installing FastAPI and Uvicorn
  • GET and POST routes
  • Path and query parameters
  • The /docs page
  • Status codes

A request through FastAPI

  1. HTTP request
  2. Router matches path
  3. Validate inputs
  4. Your function
  5. Serialise response
  6. JSON reply

Key concepts

Route
A URL + HTTP method mapped to a Python function.
Path vs query parameter
Path identifies which resource (/users/7); query filters or options (?page=2).
OpenAPI docs
Interactive API docs FastAPI generates automatically at /docs.

Step by step

  1. 1.1

    Install

    pip install "fastapi[standard]" in a virtual environment.

  2. 1.2

    First route

    Create app = FastAPI() and a @app.get("/") function.

  3. 1.3

    Run

    fastapi dev main.py, then open /docs.

  4. 1.4

    Parameters

    Path params in the URL (/items/{id}), query params after ?.

from fastapi import FastAPI

app = FastAPI()

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

# run: fastapi dev main.py   then open http://127.0.0.1:8000/docs

Notes

  • Run with auto-reload while developing.

Tips & tricks

  • Use the /docs page constantly while learning.

Interview questions

Why is FastAPI popular?

It's fast (ASGI, async), uses Python type hints for validation, and generates OpenAPI docs automatically, which speeds up development and reduces bugs.

The quick way to study this

Build a hello-world API with three routes in an hour.

2

FastAPI · Step 2 of 6 · 3 days

Validation with Pydantic

Request and response models.

Pydantic models describe the shape of data. FastAPI validates incoming JSON against them and returns clear errors automatically.

What you'll learn

  • Request body models
  • Field validation
  • Response models
  • Nested models
  • Error responses

Separate input and output models

UserIn (request)

  • email
  • password
  • name

UserOut (response)

  • id
  • email
  • name
  • (no password!)

Key concepts

Pydantic model
A class describing data shape; FastAPI validates and converts input with it.
422 error
Returned automatically when input fails validation.

Step by step

  1. 2.1

    Request models

    Define a BaseModel and use it as a parameter for the JSON body.

  2. 2.2

    Field rules

    Field(min_length=2, gt=0) adds validation.

  3. 2.3

    Response models

    response_model=UserOut hides fields like passwords.

from pydantic import BaseModel, Field

class ProductIn(BaseModel):
    name: str = Field(min_length=2)
    price: float = Field(gt=0)

@app.post("/products", status_code=201)
def create(p: ProductIn):
    return {"id": 1, **p.model_dump()}

Notes

  • Use separate models for input and output to avoid leaking fields like passwords.

Tips & tricks

  • Add examples to models; they appear in /docs.

Interview questions

Why use separate input and output models?

Na avoid leaking sensitive fields (passwords, internal IDs) and to allow different validation rules for creating vs reading data.

The quick way to study this

Build POST and PUT endpoints with validated bodies.

3

FastAPI · Step 3 of 6 · 1 week

Databases and dependencies

Connect PostgreSQL with dependency injection.

FastAPI's dependency injection (Depends) gives each request what it needs, such as a database session, and cleans up afterwards.

What you'll learn

  • SQLAlchemy or SQLModel
  • Database sessions as dependencies
  • Migrations with Alembic
  • CRUD patterns
  • Async database drivers

Typical FastAPI app layers

  1. Routes (HTTP)
  2. Schemas (Pydantic)
  3. Services (business logic)
  4. Repositories / ORM
  5. PostgreSQL

Key concepts

Dependency injection
FastAPI provides what a route needs (DB session, current user) via Depends.
ORM
Maps database tables to Python classes.
Migration
A versioned script that changes the database schema safely.

Step by step

  1. 3.1

    Connect a database

    Create an engine and a session factory with SQLAlchemy or SQLModel.

  2. 3.2

    Session dependency

    def get_db(): yield session and db = Depends(get_db) in routes.

  3. 3.3

    Migrations

    Use Alembic to version schema changes.

  4. 3.4

    CRUD

    Create, read, update, delete endpoints with proper status codes.

Notes

  • Open one session per request and close it after.

Tips & tricks

  • Use migrations from the start, even for small projects.

Interview questions

What does `Depends` do?

It declares a dependency that FastAPI calls for each request and injects into the route, e.g. a database session or the current user, with automatic clean-up for yield dependencies.

The quick way to study this

Connect your API to PostgreSQL and implement full CRUD.

4

FastAPI · Step 4 of 6 · 4 days

Auth, errors and background tasks

Make it production-ready.

Protect endpoints with a dependency that checks the current user. Use background tasks for quick follow-up work and a real queue for heavy jobs.

What you'll learn

  • OAuth2 password flow and JWT
  • Password hashing
  • Custom exception handlers
  • Background tasks
  • CORS
  • Rate limiting

Login and protected request

  1. POST /login
  2. Verify password hash
  3. Return JWT
  4. Client sends Bearer token
  5. get_current_user checks it
  6. Route runs

Key concepts

JWT
A signed token that proves who the user is on each request.
CORS
Browser rule controlling which websites may call your API.
Background task
Quick work done after sending the response (e.g. send an email).

Step by step

  1. 4.1

    Hash passwords

    Use a slow hash such as bcrypt or Argon2.

  2. 4.2

    Issue tokens

    Log in → return a short-lived JWT; protect routes with a get_current_user dependency.

  3. 4.3

    Handle errors

    Raise HTTPException; add custom exception handlers for clean messages.

  4. 4.4

    CORS and limits

    Allow only your frontends; add rate limiting.

Notes

  • Enable CORS only for the frontends you trust.

Tips & tricks

  • Write a get_current_user dependency once and reuse it.

Interview questions

Where should JWTs be stored in a browser app?

Prefer HttpOnly, Secure cookies to protect against XSS stealing tokens, plus CSRF protection. Keep tokens short-lived with refresh tokens.

The quick way to study this

Add sign-up, login and a protected route.

5

FastAPI · Step 5 of 6 · 3 days

Streaming and AI endpoints

Serve LLM features well.

FastAPI is a natural fit for AI backends: async endpoints wait on model APIs efficiently and streaming responses show tokens as they arrive.

What you'll learn

  • Async endpoints
  • Streaming responses
  • Server-sent events
  • Calling LLM APIs
  • Timeouts and retries

Streaming an AI answer

  1. Client POST /chat
  2. FastAPI calls LLM (stream)
  3. Tokens arrive
  4. Forward each chunk
  5. Browser shows text live

Key concepts

ASGI
The async server interface FastAPI runs on (e.g. Uvicorn).
Server-sent events
A simple way to stream text to the browser.
Blocking call
Sync code inside async def that freezes the event loop. Avoid it.

Step by step

  1. 5.1

    Async endpoints

    Use async def when calling async clients (httpx, async DB drivers).

  2. 5.2

    Streaming

    Return a StreamingResponse or server-sent events for LLM tokens.

  3. 5.3

    Timeouts and retries

    Never wait forever on a model API.

Notes

  • Set timeouts on all model calls.

Tips & tricks

  • Stream long answers so users see progress immediately.

Interview questions

When should you use `def` vs `async def` in FastAPI?

Use async def when the route awaits async libraries. Use plain def na blocking code; FastAPI runs it in a thread pool. Never call blocking code inside async def.

The quick way to study this

Build a /chat endpoint that streams an LLM response.

6

FastAPI · Step 6 of 6 · 4 days

Testing and deployment

Test, containerise and ship.

FastAPI's TestClient makes API tests easy. Override dependencies to use a test database.

What you'll learn

  • TestClient and pytest
  • Overriding dependencies in tests
  • Docker
  • Production servers
  • Health checks
  • Environment config

Ship it

  1. Tests pass in CI
  2. Build Docker image
  3. Push to registry
  4. Deploy
  5. Health check OK

Key concepts

TestClient
Calls your app in-process for fast API tests.
Worker
A server process; run several to use multiple CPU cores.

Step by step

  1. 6.1

    Test with TestClient

    Call routes in pytest without running a server.

  2. 6.2

    Override dependencies

    app.dependency_overrides[get_db] = test_db.

  3. 6.3

    Containerise

    Slim Python image, install deps, run with fastapi run or Uvicorn workers.

  4. 6.4

    Health and config

    /health endpoint; settings via pydantic-settings and env vars.

Notes

  • Use settings classes (pydantic-settings) for configuration.

Tips & tricks

  • Add a /health endpoint for load balancers.

Interview questions

How do you scale a FastAPI app?

Run multiple workers per machine and multiple containers behind a load balancer, keep the app stateless, cache hot data, use connection pooling and move slow jobs to a queue.

The quick way to study this

Write tests for every route, build a Docker image and deploy it.

Udostępnij tę stronę