Interview Q&A · questions with model answers

FastAPI Interview Questions

Ordered by how often they're asked. Most-asked answers are free to read in full; members see every answer and can rate their confidence on each.

  1. Most asked How does FastAPI distinguish path, query and body parameters?

    Parameters named in the path template are path parameters; simple-typed parameters not in the path are query parameters; parameters typed as Pydantic models are read from the JSON body.

  2. Most asked How does FastAPI use Pydantic for request validation?

    Request bodies, query models and settings are declared as Pydantic BaseModel classes. FastAPI parses incoming data into them, validates types and constraints, and returns a 422 response with…

  3. Most asked How does dependency injection with `Depends` work in FastAPI?

    You declare a parameter as Annotated[T, Depends(provider)]; FastAPI calls the provider per request (resolving its own dependencies recursively), caches the result within that request, and injects it.

  4. Most asked How do `yield` dependencies work and why are they used for database sessions?

    A dependency that yields provides the yielded value to the endpoint and runs the code after yield once the request is done, which suits opening and closing DB sessions or transactions.

  5. Most asked Walk through what happens to a request in FastAPI, from the ASGI server to the response.

    The ASGI server calls the app; Starlette's outer ServerErrorMiddleware wraps your middleware (the last added runs first), then ExceptionMiddleware applies your exception handlers; the router matches…

  6. Most asked How do you handle errors and customize error responses in FastAPI?

    Raise HTTPException(status_code, detail) for expected errors, define domain exceptions with @app.exception_handler(MyError) to map them to responses, and override RequestValidationError handling to…

  7. Most asked Explain coroutines, the event loop and tasks in Python asyncio, as they relate to FastAPI.

    A coroutine (async def) is a pausable function; the event loop runs coroutines, switching between them whenever one awaits I/O; a Task wraps a coroutine so it runs concurrently. FastAPI runs each…

  8. Most asked Can you use synchronous SQLAlchemy with FastAPI? What are the trade-offs?

    Yes: use plain def endpoints and a sync session dependency, and FastAPI runs them in a threadpool. It's simpler and mature, but concurrency is limited by the threadpool size (about 40 by default via…

  9. How does FastAPI generate OpenAPI docs, and how can you customize them?

    FastAPI builds an OpenAPI 3.1 schema from routes, parameters, Pydantic models and responses, served at /openapi.json with Swagger UI at /docs and ReDoc at /redoc.

  10. How do you handle field aliases (e.g., camelCase JSON with snake_case Python) in Pydantic v2?

    Use Field(alias=...) or a model-wide alias_generator (e.g., to_camel) with populate_by_name=True, and serialize with by_alias=True (FastAPI's response_model_by_alias defaults to true).

  11. How do class-based dependencies and dependencies with parameters work?

    A class can be a dependency (its init params are resolved like a function's), and a callable instance or factory function can create parameterized dependencies such as require_role('admin').

  12. How do OAuth2 scopes work with `Security()` in FastAPI?

    Use Security(dependency, scopes=[...]) instead of Depends; inside the dependency, a SecurityScopes parameter lists all required scopes, which you compare with scopes in the token to authorize…

  13. How do WebSockets work in FastAPI?

    Declare @app.websocket('/ws') with a WebSocket parameter, await websocket.accept(), then loop on receive_text()/send_text() (or JSON), handling WebSocketDisconnect.

  14. How do computed fields and custom serializers work in Pydantic v2?

    @computed_field exposes a property in serialized output and the schema; @field_serializer and @model_serializer customize how fields or whole models are dumped.

  15. If a FastAPI backend uses cookie-based auth for a browser SPA, what must you add?

    Set cookies as HttpOnly, Secure, SameSite=Lax/Strict, and add CSRF protection (double-submit token or custom header check) for state-changing requests, plus tight CORS with credentials.

  16. Can you serve GraphQL with FastAPI?

    Yes. Libraries like Strawberry provide a GraphQLRouter you mount in FastAPI, with type-hinted schemas, async resolvers and dependency injection through context.

  17. Can FastAPI render HTML and serve static files?

    Yes. Mount StaticFiles with app.mount('/static', StaticFiles(directory='static')) and render Jinja2 templates with Jinja2Templates returning TemplateResponse.

  18. How do you handle client disconnects or cancellations in long-running FastAPI requests?

    Check await request.is_disconnected() in loops (e.g., streaming) and stop work early. When the client disconnects, the server may cancel the request task, so clean up in finally blocks.

  19. How should a FastAPI API handle datetimes and money values?

    Use timezone-aware datetimes in UTC (AwareDatetime), serialize as ISO 8601, and use Decimal (or integer minor units) for money rather than floats.

  20. How should passwords be hashed in a FastAPI app?

    Use a slow, salted, memory-hard algorithm (Argon2id, or bcrypt) via libraries like pwdlib or argon2-cffi, and verify with the library's constant-time verify, rehashing when parameters change.

  21. How do frontend teams consume a FastAPI API safely?

    Generate a typed client from FastAPI's OpenAPI schema (e.g., openapi-typescript, orval, openapi-generator) in CI, so frontend types stay in sync with backend models and breaking changes surface at…

  22. How do you scale a FastAPI service on Kubernetes?

    Run stateless pods (often one Uvicorn worker each), set CPU/memory requests and limits, configure liveness/readiness probes, and use a Horizontal Pod Autoscaler on CPU or custom metrics like request…

Was this page helpful?

Report a mistake