Python / FastAPI Basics Interview Questions
1. What is FastAPI and what are its key advantages over Flask or Django REST Framework?
FastAPI is a modern, high-performance Python web framework for building APIs, built on top of Starlette (for async web handling) and Pydantic (for data validation). It was created by Sebastián Ramírez and released in 2018....
2. How do you create and run a minimal FastAPI application?
A FastAPI app needs just a few lines. You create a FastAPI() instance and decorate Python functions with HTTP method decorators....
3. What is the difference between path parameters and query parameters in FastAPI?
Path parameters are part of the URL path itself, declared with curly braces in the decorator and as function arguments. Query parameters are declared as function arguments that do not appear in the path string — FastAPI reads them from...
4. How do you receive and validate a JSON request body in FastAPI?
Declare a Pydantic BaseModel as a function parameter. FastAPI automatically reads the JSON body, validates it against the model, and provides it as a typed Python object....
5. How do you use Pydantic models for data validation and what validation features does FastAPI support?
Pydantic is FastAPI's validation engine. Models are Python classes inheriting from BaseModel where each field is a type-annotated attribute.
6. What is the response_model parameter in FastAPI and why should you use it?
The response_model parameter on a route decorator tells FastAPI which Pydantic model to use for filtering and serialising the response. Even if the endpoint returns more data internally, only the fields defined in the response model are included in the...
7. How do you add validation constraints to path and query parameters using Path() and Query()?
FastAPI provides Path() and Query() functions (imported from fastapi ) to add metadata and validation constraints to individual parameters — the same constraints available in Pydantic's Field() . from fastapi import FastAPI, Path, Query from typing import Annotated app =...
8. How do you control HTTP status codes and return custom responses in FastAPI?
FastAPI lets you set the default response status code on the decorator, raise HTTPException for errors, and return Response subclasses for full control over headers and body. from fastapi import FastAPI, HTTPException, status from fastapi.responses import JSONResponse, Response, FileResponse app
9. What is FastAPI's dependency injection system and how do you use it?
FastAPI has a powerful built-in dependency injection (DI) system. You declare dependencies as functions and inject them into route handlers using Depends() ....
10. How do you organise a FastAPI application with multiple routers (APIRouter)?
APIRouter is FastAPI's equivalent of Flask Blueprints — it lets you group related routes in separate files, then include them in the main app. This keeps large codebases manageable....
11. What is middleware in FastAPI and how do you add custom middleware?
Middleware is a function that runs on every request before it reaches a route handler and on every response before it's sent to the client. FastAPI uses Starlette's middleware system — you can add it with @app.middleware('http') or app.add_middleware() ....
12. When should you use async def vs def for route handlers in FastAPI?
FastAPI supports both async def and plain def route handlers. The choice has real performance implications because of how FastAPI's underlying ASGI server (Uvicorn + Starlette) handles concurrency....
13. What are BackgroundTasks in FastAPI and when should you use them?
BackgroundTasks let you run work after returning a response to the client — for lightweight fire-and-forget tasks like sending emails or writing audit logs. The response is sent immediately and the task runs afterward in the same process....
14. How do you implement OAuth2 password flow with JWT tokens in FastAPI?
FastAPI provides OAuth2PasswordBearer and OAuth2PasswordRequestForm helpers for the standard username/password token flow. The pattern: client POSTs credentials → server returns a JWT → client sends JWT in Authorization: Bearer <token> header on subsequent requests.
15. How do you implement role-based access control (RBAC) using FastAPI dependencies?
FastAPI's dependency injection makes RBAC clean: create a higher-order dependency that checks the current user's role. Inject it into routes that require elevated permissions....
16. How do you integrate an async SQLAlchemy database with FastAPI?
For async database access, use SQLAlchemy 2.x with AsyncSession and create_async_engine paired with an async driver such as asyncpg (PostgreSQL) or aiosqlite (SQLite). The DB session is injected via a generator dependency....
17. How do you manage database schema migrations in a FastAPI project with Alembic?
Alembic is the standard database migration tool for SQLAlchemy. It tracks schema changes as versioned migration scripts that can be applied or rolled back....
18. How do you write tests for a FastAPI application using pytest and TestClient?
FastAPI provides TestClient (wrapping httpx ) for synchronous tests and AsyncClient for async tests. Dependencies can be overridden for testing to inject mocks instead of real databases or services....
19. How do you create custom exception handlers in FastAPI?
Use @app.exception_handler(ExceptionClass) to catch specific exception types globally and return custom JSON responses. This is cleaner than wrapping every route in try/except.
20. How do you handle form data and file uploads in FastAPI?
FastAPI handles HTML form data with Form() and file uploads with File() and UploadFile . Note: you need to pip install python-multipart for form/file support....
21. How do you manage environment variables and settings in FastAPI with Pydantic Settings?
Use pydantic-settings to define a typed settings class that reads from environment variables and .env files. Inject settings via a dependency so they can be overridden in tests....
22. How do you run startup and shutdown logic in FastAPI using lifespan?
FastAPI supports a lifespan context manager (introduced in FastAPI 0.93, replaces the deprecated on_event decorators) for running code at application startup and shutdown — e.g. creating DB connection pools, loading ML models, or connecting to message brokers....
23. How do you implement WebSocket endpoints in FastAPI?
FastAPI supports WebSockets natively via the WebSocket parameter type. Use await websocket.accept() to establish the connection, then loop to send and receive messages....
24. How do you containerise and deploy a FastAPI application with Docker?
Containerising FastAPI with Docker ensures consistent environments across development, staging, and production. Use a multi-stage build to keep the production image small, and run with Gunicorn + Uvicorn workers for production-grade concurrency.
25. What are the key production deployment considerations for a FastAPI application?
Production FastAPI deployments involve several layers beyond just running the app — a reverse proxy, TLS termination, process management, health checks, and observability. Production checklist Concern Solution Multiple CPU cores Gunicorn + UvicornWorker, or multiple containers HTTPS / TLS Nginx...
26. What are the key differences between Pydantic v1 and v2, and how does FastAPI use Pydantic v2?
FastAPI 0.100+ fully supports Pydantic v2, which is a complete rewrite in Rust offering 5–50× speed improvements. Several APIs changed between v1 and v2....
27. How do you add caching to FastAPI endpoints to improve performance?
FastAPI has no built-in cache, but several patterns work well: in-process caching with functools.lru_cache / cachetools , Redis-backed caching with fastapi-cache2 , and HTTP caching headers for client-side caching. # Option 1: In-process LRU cache for slow dependencies from functools...
28. How do you customise the OpenAPI documentation in FastAPI?
FastAPI auto-generates OpenAPI 3.x specs from your code. You can enrich the docs with metadata, examples, tags, and custom descriptions without any extra tooling....
29. How do you integrate FastAPI with Celery for reliable background task processing?
FastAPI's built-in BackgroundTasks is suitable for lightweight, lossy tasks. For tasks that must be reliable, retried, scheduled, or distributed across workers, use Celery with a broker (Redis or RabbitMQ)....
30. How do you measure and improve the performance of a FastAPI application?
FastAPI is already one of the fastest Python frameworks, but real-world performance depends on database queries, serialisation, and concurrency patterns. These are the key tools and techniques....
31. How do you use class-based dependencies and sub-dependencies in FastAPI?
Dependencies can be classes with a __call__ method, enabling stateful or configurable dependencies. Sub-dependencies are automatically resolved — FastAPI builds the full dependency tree per request.
32. How do you test async FastAPI endpoints and async dependencies?
Use httpx.AsyncClient with ASGITransport for async tests, and pytest-asyncio to run async test functions. Combine with app.dependency_overrides to mock async dependencies.
33. How do you stream large responses in FastAPI using StreamingResponse?
StreamingResponse lets you send data incrementally — essential for large file downloads, CSV exports, real-time data feeds, or AI token streaming — without loading everything into memory first. from fastapi import FastAPI from fastapi.responses import StreamingResponse import asyncio import csv...
34. How do you add GraphQL support to a FastAPI application with Strawberry?
Strawberry is a Python-first GraphQL library that uses type hints and dataclasses — a natural fit alongside FastAPI and Pydantic. It mounts a GraphQL endpoint on the FastAPI app....
35. How does FastAPI handle validation errors and how can you customise the error response format?
When a request fails Pydantic validation, FastAPI automatically returns a 422 Unprocessable Entity with a structured JSON body listing every field error. You can override this default behaviour with a custom exception handler....
36. What is the scope of a FastAPI dependency, and how do you share state across requests?
By default FastAPI dependencies are request-scoped — a new instance is created per request. For shared state (connection pools, caches, ML models) use module-level variables initialised in the lifespan context manager.
37. How do you read HTTP headers and cookies in FastAPI?
FastAPI provides Header() and Cookie() parameter types. Headers are automatically converted from HTTP's hyphen-case to Python's snake_case ....
38. What are the most important FastAPI best practices for a production-ready API?
A well-architected FastAPI project follows consistent patterns across structure, validation, security, and operations. Here is a consolidated reference.