Skip to content

Interview PrepBasics · Basics

FastAPI Basics ​

The responses shown on these pages come from running the code with FastAPI 0.162, Pydantic 2.14 and Starlette 1.10 on Python 3.14.

1. What is FastAPI, and why is it fast? ​

The short answer

FastAPI is a Python web framework for building APIs, built on two libraries: Starlette for the web layer, routing, requests, WebSockets and middleware, and Pydantic for data validation and serialisation. You declare parameters and models with ordinary type hints, and FastAPI uses them to parse and validate requests, serialise responses, and generate OpenAPI docs automatically. It is fast in two senses: it runs on ASGI, so async endpoints handle many concurrent I/O-bound requests, and Pydantic's core is written in Rust, so validation and JSON encoding are quick. It is also fast to write, because the type hints do much of the work.

python
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class OrderIn(BaseModel):
    sku: str = Field(min_length=2, max_length=20)
    qty: int = Field(gt=0, le=99)

@app.post("/orders", status_code=201)                  # (1)
async def create_order(order: OrderIn) -> dict:       # (2)
    return {"sku": order.sku, "qty": order.qty}
  1. A path operation: the HTTP method, the path and the success status code.
  2. The type hint OrderIn does three jobs: FastAPI reads the JSON body, validates it against the model, and documents it in OpenAPI. Invalid input never reaches your code.

Run it with fastapi dev main.py in development, which reloads on changes, and fastapi run main.py in production.

PieceRole
StarletteASGI toolkit: routing, requests, responses, middleware, WebSockets
PydanticModels, validation and serialisation, with a Rust core
UvicornThe ASGI server that actually listens on the port
FastAPIGlue: type hints to validation, dependency injection, OpenAPI

2. What is ASGI, how does it differ from WSGI, and what is Uvicorn? ​

The short answer

WSGI is the older Python standard between web servers and frameworks, used by Flask and classic Django: each request is a synchronous function call that occupies a worker until it returns. ASGI is its asynchronous successor: the app is an async callable, so one worker can handle many requests concurrently while they wait on I/O, and it also supports WebSockets and long-lived streaming. Uvicorn is a fast ASGI server; it accepts connections and calls your FastAPI app. In production you run several Uvicorn worker processes to use all CPU cores.

WSGIASGI
Call styleapp(environ, start_response), synchronousawait app(scope, receive, send), asynchronous
Concurrency per workerOne request at a time, or threadsMany requests while they wait
WebSockets, SSENot nativelyYes
FrameworksFlask, Django (classic)FastAPI, Starlette, Django (async views)
ServersGunicorn, uWSGIUvicorn, Hypercorn, Granian
bash
fastapi run main.py --workers 4      # Uvicorn with 4 worker processes

3. How do path operations and routing work, and what is APIRouter? ​

The short answer

A path operation is a function decorated with an HTTP method and path, @app.get("/orders/{order_id}"). FastAPI matches requests to routes in the order they were declared, so a fixed path such as /orders/stats must come before /orders/{order_id}, or it will be captured as an ID. For a real app, group related endpoints in an APIRouter per area, with its prefix, tags and shared dependencies declared on the router itself, and include the routers in the main app.

python
# app/routers/orders.py
from fastapi import APIRouter, Depends
from app.deps import require_user

router = APIRouter(
    prefix="/orders",                         # (1)
    tags=["orders"],                          # (2)
    dependencies=[Depends(require_user)],     # (3)
)

@router.get("/stats")                         # (4)
async def order_stats() -> dict: ...

@router.get("/{order_id}")
async def get_order(order_id: int) -> dict: ...

# app/main.py
from fastapi import FastAPI
from app.routers import orders, products

app = FastAPI()
app.include_router(orders.router)
app.include_router(products.router)
  1. Every route in this file starts with /orders.
  2. Tags group the endpoints in the docs.
  3. Every route here requires a logged-in user, without repeating it on each function (router dependencies).
  4. Declared before /{order_id}, so /orders/stats is not parsed as an ID and rejected.

4. How do path, query, header and cookie parameters work? ​

The short answer

FastAPI decides where each parameter comes from by its declaration. A name that appears in the path, {order_id}, is a path parameter. Other simple types, int, str, bool, are query parameters; giving a default makes them optional. Use Annotated[type, Query(...)], Path(...), Header(...) and Cookie(...) to add validation, such as ge=1 or max_length=50, and documentation. Values are converted to the declared type, so ?page=2 arrives as the integer 2, and a bad value gives a 422 error. A list type collects repeated query parameters.

python
from typing import Annotated
from fastapi import FastAPI, Path, Query, Header, Cookie

app = FastAPI()

@app.get("/users/{user_id}/orders")
async def user_orders(
    user_id: Annotated[int, Path(ge=1)],                                  # (1)
    page: Annotated[int, Query(ge=1)] = 1,                                # (2)
    tags: Annotated[list[str] | None, Query()] = None,                    # (3)
    user_agent: Annotated[str | None, Header()] = None,                   # (4)
    session_id: Annotated[str | None, Cookie()] = None,
):
    return {"user": user_id, "page": page, "tags": tags}

# GET /users/7/orders?page=2&tags=shoes&tags=sale
# {"user": 7, "page": 2, "tags": ["shoes", "sale"]}
  1. From the path, converted to int, and at least 1. /users/0/orders returns 422.
  2. A query parameter with a default, so it is optional.
  3. A list collects repeated values: ?tags=shoes&tags=sale.
  4. From the User-Agent header: FastAPI converts underscores to hyphens.

Prefer Annotated over the older page: int = Query(1, ge=1) style: the function stays a normal Python function with a normal default, and the annotation can be reused (Annotated).

5. How does request body validation work, and what does a 422 error look like? ​

The short answer

A parameter typed as a Pydantic model is read from the JSON body. FastAPI parses the JSON, validates every field against the model's types and constraints, and passes your function a fully typed object. If anything is wrong, FastAPI responds 422 Unprocessable Content automatically, with a detail list giving, for each problem, its type, its location such as ["body", "qty"], a message and the input. Your endpoint code never runs for invalid input. Use model_config = ConfigDict(extra="forbid") to reject unknown fields too.

python
from pydantic import BaseModel, ConfigDict, Field

class OrderIn(BaseModel):
    model_config = ConfigDict(extra="forbid")      # (1)
    sku: str = Field(min_length=2, max_length=20)
    qty: int = Field(gt=0, le=99)
    coupon: str | None = None                      # (2)

@app.post("/orders", status_code=201)
async def create_order(order: OrderIn): ...

Sending {"sku": "a1", "qty": 0, "colour": "red"} returns 422 with:

json
{
  "detail": [
    { "type": "greater_than", "loc": ["body", "qty"], "msg": "Input should be greater than 0", "input": 0, "ctx": { "gt": 0 } },
    { "type": "extra_forbidden", "loc": ["body", "colour"], "msg": "Extra inputs are not permitted", "input": "red" }
  ]
}
  1. Reject fields the model does not define, which catches client typos such as colour for color.
  2. An optional field: None if missing.

Reading the error: every problem is reported at once, not just the first, and loc says exactly where it is, which lets a front end highlight the right form field.

6. How do return types, response models and status codes work? ​

The short answer

Declare the endpoint's return type, -> OrderOut, and FastAPI uses it to validate, filter, document and serialise the response; Pydantic does the serialisation in Rust, which is fast. Fields not in the declared type are dropped, which is how you keep a password_hash from leaking. When the function returns something different from the public shape, such as a database row, declare response_model=UserPublic in the decorator instead. Set the success code with status_code=201, and use HTTPException or a custom handler for errors.

python
class UserRow(BaseModel):             # what the database layer returns
    id: int
    email: str
    password_hash: str

class UserPublic(BaseModel):          # what clients may see
    id: int
    email: str

@app.get("/users/{user_id}", response_model=UserPublic)     # (1)
async def get_user(user_id: Annotated[int, Path(ge=1)]):
    return await users.get(user_id)                         # returns a UserRow

# GET /users/7  →  {"id": 7, "email": "a@shop.example"}     (2)
  1. response_model when the returned object's type is not the public schema.
  2. password_hash is gone: the response is filtered to UserPublic's fields.
You wantUse
Return a model and document it-> OrderOut
Return an internal object but expose a smaller shaperesponse_model=UserPublic
Createdstatus_code=201
No bodystatus_code=204 and return None
Custom headers or cookiesA response: Response parameter, then response.headers[...] = ...

Do not reach for ORJSONResponse. It is deprecated; declaring a return type already gives fast serialisation through Pydantic.

7. What documentation does FastAPI generate automatically? ​

The short answer

FastAPI builds an OpenAPI schema from your routes, parameters, models and return types, served at /openapi.json, plus interactive docs at /docs, Swagger UI, and /redoc. Everything you declare, types, constraints, descriptions, examples, tags and response models, appears there automatically, and stays in sync with the code because it is the code. Clients can be generated from the schema, for example a typed TypeScript client for a React front end. In production, you can disable or protect the docs with docs_url=None and openapi_url=None.

python
app = FastAPI(
    title="Shop API",
    version="1.4.0",
    docs_url="/docs" if config.ENV != "production" else None,     # (1)
)

class OrderIn(BaseModel):
    sku: str = Field(min_length=2, examples=["A1"], description="Product SKU")   # (2)
  1. Hide the docs in production if the API is not public.
  2. Examples and descriptions show up in /docs, making it a live reference for front-end developers.

Generating a typed client: tools such as openapi-typescript or @hey-api/openapi-ts read /openapi.json and produce TypeScript types and functions, so a renamed field breaks the front-end build instead of production.

8. How do you handle errors in FastAPI? ​

The short answer

For expected failures in an endpoint, raise HTTPException(status_code, detail), optionally with headers such as WWW-Authenticate. For your own domain exceptions, such as OutOfStock, register an exception handler with @app.exception_handler(OutOfStock) that turns them into a consistent JSON error, so business code does not import web concerns. Customise validation errors by handling RequestValidationError. Let unexpected exceptions become 500s, logged with the trace ID, and never leak stack traces to clients.

python
from fastapi import HTTPException, Request, status
from fastapi.responses import JSONResponse

class OutOfStock(Exception):
    def __init__(self, sku: str):
        self.sku = sku

@app.exception_handler(OutOfStock)                               # (1)
async def out_of_stock_handler(request: Request, exc: OutOfStock):
    return JSONResponse(status_code=409, content={"error": "out_of_stock", "sku": exc.sku})

@app.get("/stock/{sku}")
async def reserve(sku: str):
    if not await inventory.reserve(sku):
        raise OutOfStock(sku)                                    # (2)

@app.get("/orders/{order_id}")
async def get_order(order_id: int):
    order = await orders.get(order_id)
    if order is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "Order not found")   # (3)
    return order

# GET /stock/A1 when sold out  →  409 {"error": "out_of_stock", "sku": "A1"}
  1. One handler maps a domain error to HTTP everywhere it is raised.
  2. Service code raises a domain error, with no knowledge of HTTP.
  3. HTTPException for simple cases in the endpoint itself; the body becomes {"detail": "Order not found"}.

Error-shape design in general is in consistent API errors.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
FastAPI
Basics
Pydantic
Dependencies
Async
Data and security
Production
Other topics
Nothing picked yet