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. FastAPI vs Flask vs DRF Feature FastAPI Flask Django REST Framework Perfor...
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. The app is served by an ASGI server — Uvicorn is the standard choice. # main.py from fastapi import FastAPI app = FastAPI() @app . get( "/" ) def read_root (): return {...
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 the URL query string automatically. from fastapi import FastA...
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. If validation fails it returns a 422 with details. from fastapi import FastAPI from pydantic import BaseModel from typing impo...
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. Pydantic validates on instantiation, raising ValidationError for invalid data. FastAPI catches this and returns a 422 automatically. from pydantic import Ba...
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 JSON output. from fastapi import FastAPI fro...
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 = FastAPI() @app . get( "/i...
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() . FastAPI resolves the dependency tree automatically, handles async dependencies, and caches results per request. from fastapi import FastAPI...
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. # routers/items.py from fastapi import APIRouter, Depends router = APIRouter( prefix = "/items" , # all routes here...
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() . from fastapi import FastAPI, Request from ...
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. async def vs def in FastAPI Handler type How FastAPI runs it When to use async def Runs directly on...
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. from fastapi import FastAPI, BackgroundTasks from pydantic...
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
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. from fastapi import FastAPI, Depends, HTTPException, status from typing import Annotated from enum import Enum app = Fast...
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. # pip install sqlalchemy asyncpg from sqlalchemy.ext.asyncio import create...
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. This is essential for production databases — never rely solely on create_all() . # 1. Install and initialise Alembic # pip install alembic # ...
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. # app/main.py from fastapi import FastAPI, Depends from pydantic import BaseModel app = FastAPI() ...
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. from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from fastapi.exceptions import RequestVa...
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. from fastapi import FastAPI, Form, File, UploadFile from typing import Annotated app = FastAPI() # Form data (application/x-www-form-urlen...
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. # pip install pydantic-settings from pydantic_settings import BaseSettings, SettingsConfigDict from functools import lr...
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. from contextlib import asynccontextm...
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. from fastapi import FastAPI, WebSocket, WebSocketDisconnect from typing import List app = FastAPI() # Simple echo WebSocket @app...
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. # Dockerfile FROM python:3.12-slim AS base WORKDIR ...
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 o...
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. Pydantic v1 vs v2 key changes v1 (old) v2 (current) Notes .dict() .model_dump() Serialise model to dict .json() .model_dump_json() Serialise to...
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 import lru_c...
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. from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from pydantic import BaseModel, Field # App-level metadata a...
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). # pip install celery redis # celery_app.py from celery import Celery celery_app = Celery( ...
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. # 1. Measure with locust load testing # pip install locust # locustfile.py from locust import HttpUser,...
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. from fastapi import FastAPI, Depends, HTTPException from typing import Annotated app = FastAPI() #...
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. # pip install pytest pytest-asyncio httpx # conftest.py import pytest from httpx import AsyncClient, ASGITransport from app.m...
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 i...
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. # pip install strawberry-graphql[fastapi] import strawberry from strawberry.fastapi import GraphQLRouter from fastapi ...
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. from fastapi import FastAPI, Request from fastapi.exceptions import Re...
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. from contextlib import asynccontextmanager from fastapi import FastAPI, Depend...
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 . You can also set cookies on responses. from fastapi import FastAPI, Header, Cookie, Response from typing import Annotated app = FastAPI() # Read request hea...
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. FastAPI Production Best Practices Area Best Practice Project structure Separate concerns: routers/, models/, schemas/, dependencies/, services/ ...