Autocoder

FastAPI Interview Questions and Answers

Last updated 2026-11-19

FastAPI interviews check that you understand what the framework does for you from type hints: request parsing, validation, serialisation and OpenAPI docs. They also probe the places where it is easy to go wrong, such as blocking calls inside async routes, dependency scoping and handling database sessions.

This page uses Pydantic v2 and the current lifespan-based startup, plus the Annotated style for dependencies. If you are comparing with other Python frameworks, see the Flask and Django pages, and the backend developer questions for general API topics.

Version coveredFastAPI 0.11x on Pydantic v2 and Python 3.10 and later
Core topicsTyping, validation, dependencies, async, security, testing
Questions here17

The async question you should expect

A route declared with async def runs on the event loop, so any blocking call inside it, such as a synchronous database driver, requests.get or time.sleep, stalls every other request. A route declared with plain def is run in a thread pool by FastAPI, so blocking code there is fine. Interviewers love this because the wrong choice makes a service slower than a synchronous one.

Pydantic v2 vocabulary

FastAPI Interview Questions and Answers: questions with worked answers

  1. 1

    What makes FastAPI different from Flask?

    easy

    FastAPI is an ASGI framework built on Starlette and Pydantic. Type hints on path, query and body parameters drive validation, conversion and an automatic OpenAPI schema with interactive docs at /docs. It supports async natively, and invalid input returns a structured 422 response without extra code. Flask is WSGI, synchronous by default, and leaves validation to you.

    python
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/items/{item_id}")
    async def read_item(item_id: int, q: str | None = None):
        return {"item_id": item_id, "q": q}
  2. 2

    How do you declare request bodies and responses with Pydantic?

    easy

    Define a BaseModel for the body and use it as a parameter type. FastAPI parses the JSON and validates it. Set response_model or a return type annotation to filter the output, which is how you avoid leaking fields such as password hashes. Set status_code on the decorator. Use separate input and output models.

    python
    from pydantic import BaseModel, EmailStr, Field
    
    class UserIn(BaseModel):
        email: EmailStr
        password: str = Field(min_length=10)
    
    class UserOut(BaseModel):
        id: int
        email: EmailStr
    
    @app.post("/users", response_model=UserOut, status_code=201)
    async def create_user(user: UserIn):
        return await save(user)
  3. 3

    When do you use async def and when plain def?

    medium

    Use async def when the route awaits non-blocking I/O such as an async database driver or httpx.AsyncClient. Use def when you call blocking libraries, because FastAPI runs the function in a thread pool and the event loop stays free. Never call blocking code from async def. For CPU-heavy work use a process pool or a task queue, since neither option helps there.

  4. 4

    How does dependency injection work with Depends?

    medium

    A dependency is a callable that FastAPI calls for you and whose result is passed to the route. Dependencies can have their own dependencies, are cached per request by default, and may use yield to run cleanup after the response, which is the pattern for database sessions. They are also the place for authentication, pagination parameters and permission checks. Dependencies can be overridden in tests.

    python
    from typing import Annotated
    from fastapi import Depends
    
    async def get_db():
        async with SessionLocal() as session:
            yield session
    
    DbDep = Annotated[AsyncSession, Depends(get_db)]
    
    @app.get("/users/{uid}")
    async def get_user(uid: int, db: DbDep):
        return await db.get(User, uid)
  5. 5

    How do you handle startup and shutdown?

    medium

    Use a lifespan async context manager passed to FastAPI. Code before yield runs at startup, such as creating a connection pool, and code after runs at shutdown. The older on_event decorators are deprecated. Store shared resources on app.state and read them in dependencies.

    python
    from contextlib import asynccontextmanager
    
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        app.state.pool = await create_pool(DSN)
        yield
        await app.state.pool.close()
    
    app = FastAPI(lifespan=lifespan)
  6. 6

    How do you implement JWT authentication?

    medium

    Use OAuth2PasswordBearer to read the bearer token, a login route that checks a password hash and issues a signed token with an expiry, and a dependency that decodes it and loads the user. Use PyJWT or authlib, hash passwords with Argon2 or bcrypt, keep the secret in an environment variable, and return 401 with a WWW-Authenticate header on failure.

    python
    oauth2 = OAuth2PasswordBearer(tokenUrl="token")
    
    async def current_user(token: Annotated[str, Depends(oauth2)]):
        try:
            payload = jwt.decode(token, SECRET, algorithms=["HS256"])
        except jwt.PyJWTError:
            raise HTTPException(401, "invalid token", headers={"WWW-Authenticate": "Bearer"})
        return await users.get(payload["sub"])
  7. 7

    What are path, query and body parameters, and how are they told apart?

    medium

    A name that appears in the path template is a path parameter. A parameter of a scalar type that is not in the path is a query parameter, and giving it a default makes it optional. A parameter typed as a Pydantic model is read from the JSON body. Use Query, Path, Body and Header helpers for constraints such as ge, max_length and aliases. Several body models are embedded under their parameter names.

  8. 8

    How do you validate with Pydantic v2 validators?

    medium

    Use Field constraints for simple rules and field_validator or model_validator for custom logic. A field validator is a classmethod that returns the cleaned value or raises ValueError. model_validator with mode after checks relationships between fields. Validation errors become a 422 response listing the location and message for each failure.

    python
    from pydantic import BaseModel, field_validator, model_validator
    
    class Booking(BaseModel):
        start: int
        end: int
    
        @model_validator(mode="after")
        def check_range(self):
            if self.end <= self.start:
                raise ValueError("end must be after start")
            return self
  9. 9

    How do you handle errors and customise error responses?

    medium

    Raise HTTPException with a status code and detail for expected failures. Register exception handlers with app.exception_handler for custom exception classes or to reshape validation errors from RequestValidationError. Return a consistent error format. Unexpected exceptions result in a 500, so add logging middleware or a handler that logs the traceback without leaking it.

  10. 10

    What are BackgroundTasks and when are they not enough?

    medium

    BackgroundTasks run a function after the response is sent, in the same process, suited to small jobs like writing an audit log or sending a notification. They do not survive a crash or restart, have no retry or scheduling, and compete with request handling for resources. For reliable or heavy jobs use a queue and workers such as Celery, ARQ or a cloud queue.

  11. 11

    How do you test FastAPI apps?

    medium

    Use TestClient from FastAPI, which wraps httpx, for synchronous tests, or httpx.AsyncClient with ASGITransport for async ones. Override dependencies through app.dependency_overrides to inject a test database or fake user. Run with pytest, and use a transaction rollback per test to keep the database clean.

    python
    from fastapi.testclient import TestClient
    
    app.dependency_overrides[get_db] = lambda: fake_db
    client = TestClient(app)
    
    def test_read_item():
        r = client.get("/items/3?q=x")
        assert r.status_code == 200
        assert r.json() == {"item_id": 3, "q": "x"}
  12. 12

    How do you run FastAPI in production?

    hard

    Run Uvicorn, or Gunicorn with Uvicorn workers, behind a reverse proxy or load balancer, with several worker processes sized to CPU cores, since each process runs one event loop. FastAPI also provides a fastapi run command. Set timeouts, configure structured logging and health checks, and containerise. Do not use the reload flag or the docs endpoints unprotected if the API is private.

  13. 13

    How do you stream responses and use WebSockets?

    hard

    Return StreamingResponse with an async generator for large or incremental output such as server-sent events or file downloads. For two-way messaging declare a websocket route, accept the connection and loop receiving and sending messages, handling WebSocketDisconnect. With several workers you need a shared pub/sub such as Redis to broadcast to connections held by other processes.

    python
    from fastapi import WebSocket, WebSocketDisconnect
    
    @app.websocket("/ws")
    async def ws(socket: WebSocket):
        await socket.accept()
        try:
            while True:
                msg = await socket.receive_text()
                await socket.send_text("echo: " + msg)
        except WebSocketDisconnect:
            pass
  14. 14

    How do you use SQLAlchemy 2 asynchronously with FastAPI?

    hard

    Create an async engine with a driver such as asyncpg, an async_sessionmaker with expire_on_commit=False, and provide a session through a yield dependency. Use await session.execute(select(...)) and eager-load relationships with selectinload, because lazy loading triggers implicit I/O that fails in async code. Run migrations with Alembic.

  15. 15

    How do you version and organise a larger API?

    hard

    Split features into APIRouter modules with prefixes and tags and include them in the app. Version through a path prefix such as /v1, mounting sub-applications or routers per version, and keep response models stable within a version. Share dependencies for auth at router level with the dependencies argument. Document with OpenAPI summaries and examples.

  16. 16

    What is the difference between a Pydantic model and a database model?

    hard

    A Pydantic model validates and serialises data crossing the API boundary. An ORM model such as a SQLAlchemy class maps to a table and carries persistence behaviour. Keeping them separate lets the API shape evolve independently from the schema, and avoids exposing columns accidentally. Use model_config from_attributes=True to build the Pydantic output from an ORM object.

Frequently asked questions

Is FastAPI better than Flask or Django?

It depends. FastAPI suits typed JSON APIs with async I/O, Django suits full web apps with an admin and ORM, and Flask suits small flexible services.

Do I need to know async Python for FastAPI interviews?

Yes. Explain async versus sync routes, what blocks the event loop and how to use async clients and drivers.

What changed with Pydantic v2?

Faster Rust-based validation, renamed methods such as model_validate and model_dump, from_attributes instead of orm_mode, and new validator decorators.

Where does FastAPI get its docs from?

It generates an OpenAPI schema from route signatures and models, and serves Swagger UI at /docs and ReDoc at /redoc by default.

Related guides

More in Role-wise Interview Questions by Job and Tech Stack

See all in this section