Backend

FastAPI

A modern Python API framework built on type hints, with automatic validation and OpenAPI docs.

What it is

FastAPI is built on Starlette (the web part) and Pydantic (data validation). You describe parameters and models with type hints, and the framework validates input and serializes output.

Interactive Swagger UI docs and an OpenAPI schema appear from the code automatically. That saves time and keeps docs current.

It supports async def and runs on ASGI servers (Uvicorn). It is widely used for ML services and microservices.

Use it when

  • REST APIs and microservices in Python.
  • Services around ML models.
  • You need auto-docs and strict data validation.

Avoid it when

  • A classic web app with pages, forms and an admin: Django is handier.
  • The team is not familiar with type hints and async.

Key concepts

Pydantic
A model library with validation based on type hints.
Dependency injection
Depends injects dependencies (DB session, current user).
ASGI
The async server interface Uvicorn runs on.
OpenAPI
The API schema docs and clients are generated from.

Example

A POST endpoint with body validation from a model.

Cheat sheet

FastAPI cheat sheet
Command or codeWhat it does
pip install 'fastapi[standard]'Installs FastAPI with the standard extras
fastapi dev main.pyDev server with reload
uvicorn main:app --reloadRuns through uvicorn
app = FastAPI()Creates the app
@app.get('/items/{id}')Route with a path parameter
async def read(id: int, q: str | None = None):Typed parameters
class Item(BaseModel): name: strPydantic model
def f(db = Depends(get_db)):Dependency injection
raise HTTPException(status_code=404)Return an error to the client
/docsAutomatic Swagger docs
TestClient(app).get('/')Tests an endpoint

How to learn it

  1. Learn Python: functions, type hints and async.
  2. Take the FastAPI course on ShortLesson and start a first endpoint.
  3. Understand routes, path and query parameters.
  4. Describe data models with Pydantic and get validation for free.
  5. Study Depends and dependency injection.
  6. Connect a database with SQLAlchemy or SQLModel.
  7. Add authentication and tests with TestClient.
  8. Deploy with uvicorn in Docker.

Interview questions

  1. 1. Where do the auto docs come from?

    FastAPI reads type hints and Pydantic models and builds an OpenAPI schema. Swagger UI is available at /docs with no extra code.

  2. 2. When to use async def and when def?

    async def for code that awaits I/O through async libraries. Plain def runs in a thread pool, so blocking code does not stall the event loop.

  3. 3. What does Depends do?

    It registers a dependency the framework creates and passes to the handler. Handy for DB sessions, auth and shared logic.

Comparisons with this technology

Logos belong to their owners and are used for identification only. Icons: Simple Icons (CC0), Devicon (MIT).