Questions 1–20 of 100 · 0 of 20 on this page marked learned
1.fastapi-0001Easyfresher
What is FastAPI, and why is it called fast?
FastAPI is a Python web framework for building APIs with standard type hints. It is built on Starlette (the ASGI web layer) and Pydantic (data validation), so it runs on async servers like Uvicorn and validates input from type hints. "Fast" means two things: high runtime performance compared with traditional sync Python frameworks, and fast development, because one set of type hints gives validation, editor support and automatic OpenAPI docs.
Full answer
FastAPI is a framework for HTTP APIs. You declare an endpoint as a Python function, and the parameter types tell FastAPI where to read data from and how to validate it.
Its building blocks:
Starlette provides routing, requests and responses, middleware, WebSockets and background tasks. It speaks ASGI (Asynchronous Server Gateway Interface), the async successor to WSGI.
Pydantic (version 2, with a core written in Rust) parses and validates data from type hints and serialises responses.
An ASGI server such as Uvicorn runs the app.
Why "fast":
Runtime. On an async server, one process can handle many requests that are waiting on I/O (database, other APIs) at the same time. Pydantic v2's Rust core makes validation and serialisation cheap. FastAPI is among the quicker Python frameworks, though real speed depends mostly on your database and I/O patterns.
Development. Type hints drive request parsing, validation errors, editor autocomplete and an OpenAPI schema. The /docs page (Swagger UI) and /redoc come for free, which helps front-end and mobile teams start early.
What FastAPI does not include: an ORM, an admin panel, migrations or a template-first web stack. You pick libraries, commonly SQLAlchemy or SQLModel with Alembic for databases.
When to choose it: JSON APIs, microservices, ML model serving, and services with lots of concurrent I/O. When Django might fit better: content-heavy sites or back-office apps that benefit from the admin, ORM and auth out of the box.
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI(title="Canteen API")
class MenuItem(BaseModel):
name: str
price: float
veg: bool = True
@app.get("/menu/{item_id}")
def read_item(item_id: int) -> MenuItem:
return MenuItem(name="Masala Dosa", price=60.0)
client = TestClient(app)
print(client.get("/menu/1").json())
print(client.get("/menu/abc").status_code) # validated from the type hint
print(sorted(client.get("/openapi.json").json()["paths"])) # schema generated automatically
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'name': 'Masala Dosa', 'price': 60.0, 'veg': True}
422
['/menu/{item_id}']
Key points
Built on Starlette (ASGI) and Pydantic
Type hints drive parsing, validation and docs
Async server handles many I/O-bound requests concurrently
OpenAPI docs at /docs and /redoc automatically
No built-in ORM or admin; you choose libraries
Common mistakes
Claiming FastAPI is fast for every workload, including CPU-heavy ones
Thinking FastAPI includes an ORM or admin like Django
Using async def with blocking libraries and losing the benefit
Ignoring the generated OpenAPI schema as a contract for clients
Follow-ups
What is ASGI and how is it different from WSGI?
What role does Pydantic play in a request?
When would you choose Django over FastAPI?
Tips
Explain both meanings of fast
Name Starlette and Pydantic and what each does
Be honest that database and I/O design matter more than framework speed
2.fastapi-0002Easyfresher
How do path parameters work in FastAPI, and how does type conversion and validation happen?
Path parameters are parts of the URL declared in the route string, such as /students/{roll_no}, and received as function arguments with the same name. The type hint decides conversion and validation: roll_no: int turns "42" into 42 and returns a 422 error for "abc". Route order matters, so fixed paths like /students/me must be declared before /students/{roll_no}.
Full answer
A path parameter is a variable part of the URL path:
Starlette matches the route and extracts "42" as a string.
FastAPI sees the int annotation and asks Pydantic to convert it. roll_no arrives as the integer 42.
On GET /students/abc, conversion fails and FastAPI returns 422 Unprocessable Content with a JSON body describing the error (int_parsing, location ["path", "roll_no"]).
Supported types include int, float, str, bool, uuid.UUID, datetime.date, Enum subclasses and Literal. Extra constraints come from Path():
python
from typing import Annotated
from fastapi import Path
def get_student(roll_no: Annotated[int, Path(ge=1, le=9999)]): ...
Route order: routes are matched in the order they are declared. If /students/{roll_no} comes first, a request to /students/me tries to parse "me" as an int and fails with 422. Declare /students/me before the parameterised route.
Paths that contain slashes, such as file paths, need the :path converter: /files/{file_path:path}.
Path parameters are always required; a URL without that segment simply matches a different route or returns 404.
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'roll_no': 42, 'type': 'int'}
{'roll_no': 7, 'who': 'me'}
422 int_parsing ['path', 'roll_no']
Input should be greater than or equal to 1
{'file_path': 'reports/2026/term1.pdf'}
Key points
Declared in the route string and received by name
Type hints convert and validate; failure returns 422
Path() adds constraints like ge and le
Declare fixed routes before parameterised ones
Use {name:path} for values that contain slashes
Common mistakes
Declaring /students/{id} before /students/me
Expecting a 400 instead of 422 for a type mismatch
Validating ranges by hand instead of using Path(ge=..., le=...)
Forgetting {name:path} for values with slashes
Follow-ups
How would you restrict a path parameter to a fixed set of values?
What does the 422 response body contain?
How is a path parameter different from a query parameter?
Tips
Walk through the conversion step
Mention the route order trap with a concrete example
Use Annotated with Path for constraints, the current recommended style
3.fastapi-0003Easyfresher
How do query parameters work in FastAPI? How do you make them optional, give defaults, or accept a list?
Any function parameter that is not in the path and is a simple type becomes a query parameter. Without a default it is required; with a default it is optional; with a None default and a type like int | None it can be left out. Query() adds validation such as min_length or ge, and a list type with Query() accepts repeated keys like ?subject=maths&subject=science.
Full answer
Query parameters are the key=value pairs after ? in a URL: /students?class_name=10A&page=2.
FastAPI decides the source of each parameter from its declaration:
Name appears in the path: path parameter.
Simple type (int, str, bool, float, enum) not in the path: query parameter.
Pydantic model: request body (unless marked otherwise).
Other options: alias="class" lets the URL use a name that is a Python keyword, deprecated=True marks it in the docs, and include_in_schema=False hides it. Since FastAPI 0.115 you can group many query parameters into one Pydantic model with Annotated[Filters, Query()].
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'class': '10A', 'page': 1, 'search': None, 'subject': [], 'active': True}
{'class': '10B', 'page': 3, 'search': 'an', 'subject': ['maths', 'science'], 'active': False}
422 ['query', 'class'] Field required
Input should be greater than or equal to 1
Key points
Non-path simple types are query parameters
No default = required; default = optional
Annotated + Query() for validation
list[...] needs Query() to read repeated keys
alias handles names like class that are Python keywords
Common mistakes
Declaring list[str] without Query() and getting a body parameter
Sending ?subject=maths,science and expecting two items; FastAPI collects repeated keys, it does not split on commas
Leaving a query parameter without a default and being surprised by 422
Trying to name a parameter class without an alias
Follow-ups
How would you group ten filter parameters into one model?
How does FastAPI decide whether a parameter is from the path, query or body?
How do you mark a query parameter as deprecated in the docs?
Tips
State the source-detection rule clearly
Show required, default and optional side by side
Mention the list needs Query() gotcha
4.fastapi-0004Easyfresher
How do you accept a JSON request body in FastAPI using a Pydantic model?
Declare a class that inherits from pydantic.BaseModel and use it as a parameter type. FastAPI reads the JSON body, validates it against the model, and passes an instance to your function, returning 422 with details if validation fails. You can mix body, path and query parameters in one endpoint, and use model_dump() to turn the model into a dict.
Full answer
For POST, PUT and PATCH, data usually arrives as JSON in the request body. FastAPI uses Pydantic models to describe it:
python
class Admission(BaseModel):
name: str
age: int
email: str | None = None
subjects: list[str] = []
Reads the body as JSON (if the body is not valid JSON, 422 with type json_invalid).
Validates with Pydantic: required fields present, types correct. In the default "lax" mode Pydantic converts compatible values, such as "16" to 16, but rejects "sixteen".
Passes an Admission instance; you use attributes like admission.name.
Adds the model's JSON Schema to OpenAPI so /docs shows an example form.
class_id from the path, notify from the query, admission from the body.
Useful extras:
admission.model_dump() gives a dict (Pydantic v2; v1 used .dict()).
Body(embed=True) expects {"admission": {...}} instead of the bare object.
Several model parameters make FastAPI expect a body with one key per parameter.
A single plain value in the body needs Body(): priority: Annotated[int, Body()].
Extra unknown fields are ignored by default. Set model_config = ConfigDict(extra="forbid") to reject them, which catches client typos.
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
app = FastAPI()
class Admission(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str
age: int
email: str | None = None
subjects: list[str] = []
@app.post("/classes/{class_id}/admissions", status_code=201)
def create_admission(class_id: int, admission: Admission, notify: bool = False):
return {"class_id": class_id, "notify": notify, "data": admission.model_dump()}
c = TestClient(app)
r = c.post("/classes/9/admissions?notify=true", json={"name": "Aarav", "age": "16", "subjects": ["Maths"]})
print(r.status_code, r.json())
r = c.post("/classes/9/admissions", json={"name": "Diya", "age": "sixteen", "grade": "A"})
print(r.status_code, [(e["loc"], e["type"]) for e in r.json()["detail"]])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
201 {'class_id': 9, 'notify': True, 'data': {'name': 'Aarav', 'age': 16, 'email': None, 'subjects': ['Maths']}}
422 [(['body', 'age'], 'int_parsing'), (['body', 'grade'], 'extra_forbidden')]
Key points
BaseModel subclasses become JSON body parameters
Pydantic validates; failures return 422
Path, query and body can be combined
model_dump() replaces v1's dict()
extra='forbid' rejects unknown fields
Common mistakes
Using .dict() and .json() from Pydantic v1 instead of model_dump() and model_dump_json()
Sending a single value in the body without Body()
Assuming unknown fields cause an error by default
Reading request.json() manually instead of declaring a model
Follow-ups
What is the difference between lax and strict mode in Pydantic v2?
How would you accept a list of models in the body?
How do you add example values to the docs for a model?
Tips
Say where each parameter comes from in a mixed endpoint
Mention the v1 to v2 method renames
Bring up extra='forbid' as a practical safety net
5.fastapi-0005Easyfresher
What does response_model (or a return type annotation) do in FastAPI, and why does it matter for security?
A response model declares the shape of the response. FastAPI validates the returned data against it, serialises it, filters out fields that are not in the model and documents it in OpenAPI. That filtering prevents leaking fields like password hashes when you return a database object. You can declare it with a return type annotation or response_model=..., and tune output with response_model_exclude_unset.
If both are present, response_model wins. Use response_model when the function returns something else (for example a dict or an ORM object) that should be converted into UserOut.
What FastAPI does with it:
Validates the return value against the model. Returning wrong data is a server bug, so it raises an error (500), not a 422.
Filters: only fields in the model are included. If your internal object has password_hash, and UserOut does not, the hash never reaches the client.
Serialises with Pydantic (dates, UUIDs, decimals become JSON).
Documents the schema in OpenAPI.
A common pattern is separate models per direction:
UserCreate (input): name, email, password.
UserOut (output): id, name, email.
An internal or database model with the hash.
Options:
response_model_exclude_unset=True: leave out fields that were never set (good for PATCH-style responses).
response_model_exclude_none=True: drop None values.
response_model=list[UserOut] for lists.
Returning a Response object directly skips the response model entirely.
For ORM objects, give the output model model_config = ConfigDict(from_attributes=True) (v1 called this orm_mode) so Pydantic reads attributes.
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
app = FastAPI()
class UserInDB: # stands in for an ORM object
def __init__(self, id, name, email, password_hash, phone=None):
self.id, self.name, self.email = id, name, email
self.password_hash, self.phone = password_hash, phone
class UserOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
email: str
phone: str | None = None
DB = {1: UserInDB(1, "Sana", "sana@example.edu", "$argon2id$v=19$...")}
@app.get("/users/{user_id}", response_model=UserOut)
def get_user(user_id: int):
return DB[user_id] # has password_hash, but it is filtered out
@app.get("/users/{user_id}/compact", response_model=UserOut, response_model_exclude_none=True)
def get_user_compact(user_id: int):
return DB[user_id]
c = TestClient(app)
print(c.get("/users/1").json())
print(c.get("/users/1/compact").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'id': 1, 'name': 'Sana', 'email': 'sana@example.edu', 'phone': None}
{'id': 1, 'name': 'Sana', 'email': 'sana@example.edu'}
Key points
Response model validates, filters, serialises and documents output
Filtering stops sensitive fields from leaking
response_model= overrides the return annotation
Use separate input and output models
from_attributes=True reads ORM objects
Common mistakes
Returning ORM objects without a response model and leaking internal fields
Reusing the input model (with password) as the output model
Forgetting from_attributes=True when returning ORM objects
Expecting response validation errors to be 422; they are server errors
Follow-ups
How would you return different fields to admins and normal users?
What happens if your endpoint returns data that fails the response model?
What is the cost of response validation on very large lists?
Tips
Lead with the security benefit
Show separate input and output models
Mention from_attributes for ORM objects
6.fastapi-0006Easyfresher
How do you set status codes and return errors in FastAPI? Explain status_code and HTTPException.
Set the success status with the status_code argument on the route decorator, for example 201 for creation or 204 for no content. To return an error, raise HTTPException(status_code=..., detail=...); FastAPI stops the handler and sends a JSON body {"detail": ...}. Validation errors produce 422 automatically, and you can add headers to errors such as WWW-Authenticate for 401.
For 204 No Content, return nothing (None); the response must not have a body. For a code that depends on logic, accept a response: Response parameter and set response.status_code, or return a JSONResponse(status_code=...).
Errors
Raise, do not return:
python
raise HTTPException(status_code=404, detail="Book not found")
Raising stops the function immediately, even from deep inside helper functions or dependencies.
The client gets {"detail": "Book not found"}. detail can be any JSON-serialisable value, such as a dict with an error code.
headers={"WWW-Authenticate": "Bearer"} adds headers, needed for 401 responses.
Common codes for an API:
400 bad request (business rule violated), 401 not authenticated, 403 authenticated but not allowed, 404 not found, 409 conflict (duplicate or state clash), 422 validation error (automatic), 429 too many requests, 500 server error.
Use fastapi.status constants for readability. In current Starlette, 422's constant is HTTP_422_UNPROCESSABLE_CONTENT (the older HTTP_422_UNPROCESSABLE_ENTITY name is deprecated), so using the number 422 avoids churn.
Document error responses with responses={404: {"description": "Book not found"}} on the decorator so clients see them in /docs. For a consistent error format across the app, add custom exception handlers.
python
from fastapi import FastAPI, HTTPException, status
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
BOOKS = {1: "Wings of Fire"}
class BookIn(BaseModel):
title: str
def get_or_404(book_id: int) -> str:
if book_id not in BOOKS:
raise HTTPException(status_code=404, detail={"code": "BOOK_NOT_FOUND", "id": book_id})
return BOOKS[book_id]
@app.post("/books", status_code=status.HTTP_201_CREATED)
def create_book(book: BookIn):
if book.title in BOOKS.values():
raise HTTPException(status_code=409, detail="This title already exists")
new_id = max(BOOKS) + 1
BOOKS[new_id] = book.title
return {"id": new_id, "title": book.title}
@app.get("/books/{book_id}", responses={404: {"description": "Book not found"}})
def read_book(book_id: int):
return {"id": book_id, "title": get_or_404(book_id)}
@app.delete("/books/{book_id}", status_code=204)
def delete_book(book_id: int):
get_or_404(book_id)
del BOOKS[book_id]
c = TestClient(app)
r = c.post("/books", json={"title": "Ignited Minds"}); print(r.status_code, r.json())
r = c.post("/books", json={"title": "Ignited Minds"}); print(r.status_code, r.json())
r = c.get("/books/99"); print(r.status_code, r.json())
r = c.delete("/books/2"); print(r.status_code, repr(r.text))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
201 {'id': 2, 'title': 'Ignited Minds'}
409 {'detail': 'This title already exists'}
404 {'detail': {'code': 'BOOK_NOT_FOUND', 'id': 99}}
204 ''
Key points
status_code on the decorator sets the success code
Raise HTTPException for errors; it stops the handler
Error body is {'detail': ...}
204 responses must not have a body
Document errors with responses= for clients
Common mistakes
Returning an error dict with status 200 instead of raising HTTPException
Returning a body from a 204 endpoint
Using 401 when the user is logged in but not allowed (that is 403)
Not documenting error responses for API clients
Follow-ups
How would you return the same error format for every error in the app?
When is 409 better than 400?
How do you change the status code based on logic inside the handler?
Tips
Say raise, not return, and explain why
Map common situations to codes
Mention documenting error responses
7.fastapi-0007Easyfresher
How does FastAPI generate API documentation, and how can you customise or turn off /docs?
FastAPI builds an OpenAPI schema from routes, parameters, Pydantic models, response models and metadata, served at /openapi.json. Swagger UI at /docs and ReDoc at /redoc render it. You customise it with app metadata (title, version, description), route summary, description, tags and examples, and you can move or disable the docs with docs_url, redoc_url and openapi_url, for example in production.
Full answer
OpenAPI is a standard, machine-readable description of an HTTP API: paths, methods, parameters, request and response schemas, and security schemes. FastAPI creates it automatically on first request to /openapi.json by walking every route.
Where the information comes from:
Path, query, header and cookie parameters, with types and constraints from Path(), Query() and so on.
Request body and response schemas from Pydantic models (JSON Schema).
Status codes from status_code and responses=.
Security from dependencies such as OAuth2PasswordBearer (adds the Authorize button).
Docstrings become descriptions; summary=, description=, tags= and deprecated=True on decorators.
Field(examples=[...]) or model_config = {"json_schema_extra": {"examples": [...]}} add examples.
Two UIs render the schema: Swagger UI at /docs (you can try requests) and ReDoc at /redoc (reading-friendly).
openapi_url=None disables the schema and both UIs, a common choice for public production APIs that should not advertise every endpoint. Hiding docs is not security; endpoints still need authentication.
include_in_schema=False hides a single route.
The schema is useful beyond docs: generate typed clients (TypeScript, Kotlin) with tools such as openapi-generator, run contract tests, and diff the schema in CI to catch breaking changes before release.
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI(title="Library API", version="2.3.0", docs_url="/internal/docs", redoc_url=None,
openapi_tags=[{"name": "books", "description": "Catalogue operations"}])
class Book(BaseModel):
title: str = Field(examples=["Malgudi Days"])
copies: int = Field(ge=0, examples=[3])
@app.post("/books", tags=["books"], summary="Add a book", status_code=201)
def add_book(book: Book) -> Book:
"""Adds a book to the catalogue. Copies must be zero or more."""
return book
@app.get("/healthz", include_in_schema=False)
def health():
return {"ok": True}
c = TestClient(app)
schema = c.get("/openapi.json").json()
op = schema["paths"]["/books"]["post"]
print(schema["info"], list(schema["paths"]))
print(op["summary"], "|", op["description"], "|", op["tags"])
print(schema["components"]["schemas"]["Book"]["properties"]["copies"])
print(c.get("/internal/docs").status_code, c.get("/redoc").status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'title': 'Library API', 'version': '2.3.0'} ['/books']
Add a book | Adds a book to the catalogue. Copies must be zero or more. | ['books']
{'type': 'integer', 'minimum': 0.0, 'title': 'Copies', 'examples': [3]}
200 404
Key points
OpenAPI schema built from routes, types and models
Swagger UI at /docs, ReDoc at /redoc
Metadata via summary, description, tags, examples
docs_url, redoc_url, openapi_url move or disable docs
Use the schema for client generation and breaking-change checks
Common mistakes
Treating hidden docs as a security measure
Leaving models without descriptions or examples, so docs are hard to use
Breaking the schema with an unnoticed field rename
Hand-writing client code instead of generating it from the schema
Follow-ups
How would you detect breaking API changes in CI?
How do you add an Authorize button for JWT to /docs?
How would you version the documentation for v1 and v2?
Tips
List where each part of the schema comes from
Mention disabling docs in production and why that is not security
Show you know the schema is useful for codegen and contract tests
8.fastapi-0008Easyfresher
In FastAPI, when should you write an endpoint with async def and when with plain def?
Use async def when the endpoint awaits async libraries (httpx.AsyncClient, asyncpg, async SQLAlchemy). Use plain def when it calls blocking code (requests, sync database drivers, file I/O); FastAPI runs def endpoints in a thread pool so they do not block the event loop. The mistake to avoid is calling blocking code inside async def, which freezes every other request on that worker.
Full answer
FastAPI runs on an event loop: one thread that switches between tasks whenever a task is waiting (await). This is how one process serves many slow I/O requests at once.
How FastAPI treats each kind of endpoint:
async def: called directly on the event loop. While it awaits I/O, other requests run. While it does non-awaiting work, nothing else on that worker runs.
def: FastAPI sends it to a thread pool (via AnyIO, default 40 threads). Blocking calls inside only block that thread.
The rule:
Calling async libraries with await? Use async def.
Calling blocking libraries (requests, psycopg2, sync SQLAlchemy, time.sleep, heavy file reads)? Use def.
Not sure, or no I/O at all? Either works; def is the safer default if you might add blocking calls later.
The worst case is blocking inside async def:
python
@app.get("/report")
async def report():
time.sleep(2) # blocks the whole event loop for 2 seconds
Every request on that worker waits. The snippet shows three such requests taking about three times as long as three def requests.
Fixes when you must call blocking code from async code: await run_in_threadpool(func, args) (from Starlette) or await asyncio.to_thread(func, args).
CPU-heavy work (image processing, ML inference without a native async API) blocks in both styles because of the GIL and the thread pool size. Move it to a process pool, a task queue, or a separate service.
The same rules apply to dependencies: they can be async def or def and FastAPI treats them the same way.
python
import asyncio
import threading
import time
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/blocking-in-async")
async def bad():
time.sleep(0.3) # blocks the event loop
return {"ok": True}
@app.get("/blocking-in-def")
def good_sync():
time.sleep(0.3) # runs in the thread pool
return {"ok": True}
@app.get("/awaiting")
async def good_async():
await asyncio.sleep(0.3) # yields while waiting
return {"ok": True}
def timed(path, n=3):
with TestClient(app) as c:
start = time.perf_counter()
threads = [threading.Thread(target=c.get, args=(path,)) for _ in range(n)]
[t.start() for t in threads]
[t.join() for t in threads]
return time.perf_counter() - start
for path in ("/blocking-in-async", "/blocking-in-def", "/awaiting"):
took = timed(path)
print(f"{path}: {'concurrent' if took < 0.6 else 'serialised'}")
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Timing thresholds are generous so the output is stable; three 0.3 s requests take about 0.9 s when serialised and about 0.3 s when concurrent.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
/blocking-in-async: serialised
/blocking-in-def: concurrent
/awaiting: concurrent
Key points
async def runs on the event loop; def runs in a thread pool
Use async def only with awaitable libraries
Blocking calls in async def freeze the worker
run_in_threadpool or asyncio.to_thread for blocking code
CPU-heavy work needs processes or a task queue
Common mistakes
Calling requests.get or time.sleep inside async def
Marking everything async def because it sounds faster
Assuming def endpoints are slow; they run concurrently in threads
Running CPU-heavy work in either style and starving the server
Follow-ups
How large is FastAPI's default thread pool and can you change it?
What happens to async dependencies used by a def endpoint?
How would you call a sync SDK from an async endpoint?
Tips
State the rule in one sentence, then explain the event loop
Describe the blocking-in-async failure concretely
Mention run_in_threadpool or asyncio.to_thread as the fix
9.fastapi-0009Easyfresher
How do you add validation rules to Pydantic v2 model fields used in FastAPI?
Use Field() with constraints such as min_length, max_length, pattern, gt, ge, lt, le, multiple_of and max_digits, or Annotated types that bundle constraints for reuse. Pydantic types like EmailStr (with the email-validator package), HttpUrl, PositiveInt and constr-style Annotated types cover common cases. Invalid input yields a 422 response listing each failing field.
Full answer
Type hints check the type; Field() adds rules about the value.
Built-in special types: EmailStr (install email-validator), HttpUrl, PositiveInt, conint-style helpers (prefer Annotated in v2), UUID4, PastDate, FutureDate, SecretStr (hides the value in logs and repr).
Strict vs lax: by default Pydantic converts compatible input ("16" to 16). Field(strict=True) or ConfigDict(strict=True) accepts only the exact type, useful where silent conversion would hide client bugs.
String cleanup: ConfigDict(str_strip_whitespace=True) trims spaces before validation.
When rules need logic (cross-field checks, lookups), use field_validator or model_validator.
python
from decimal import Decimal
from typing import Annotated
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field
RollNo = Annotated[str, Field(pattern=r"^[A-Z]{2,4}-\d{2,4}$")]
Percent = Annotated[float, Field(ge=0, le=100)]
class Student(BaseModel):
model_config = ConfigDict(str_strip_whitespace=True)
name: str = Field(min_length=2, max_length=50)
roll_no: RollNo
age: int = Field(ge=5, le=25)
fee: Decimal = Field(gt=0, max_digits=8, decimal_places=2)
attendance: Percent
subjects: list[str] = Field(default_factory=list, max_length=6)
app = FastAPI()
@app.post("/students")
def add(student: Student):
return student
c = TestClient(app)
ok = {"name": " Rhea ", "roll_no": "BCA-17", "age": 19, "fee": "15000.50", "attendance": 92.5}
print(c.post("/students", json=ok).json())
bad = {"name": "R", "roll_no": "bca17", "age": 40, "fee": "0", "attendance": 101,
"subjects": ["a", "b", "c", "d", "e", "f", "g"]}
for err in c.post("/students", json=bad).json()["detail"]:
print(err["loc"][-1], "->", err["type"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'name': 'Rhea', 'roll_no': 'BCA-17', 'age': 19, 'fee': '15000.50', 'attendance': 92.5, 'subjects': []}
name -> string_too_short
roll_no -> string_pattern_mismatch
age -> less_than_equal
fee -> greater_than
attendance -> less_than_equal
subjects -> too_long
Special types: EmailStr, HttpUrl, SecretStr, PositiveInt
strict=True disables lax conversion
Common mistakes
Using v1 names like regex= or min_items= in Pydantic v2
Using a mutable default list instead of default_factory=list
Writing custom validators for rules Field() already supports
Forgetting to install email-validator before using EmailStr
Follow-ups
How would you validate that end_date is after start_date?
What does strict mode change?
How do you reuse the same constraint across ten models?
Tips
Name constraints for strings, numbers and lists
Show an Annotated reusable type
Mention the v1 to v2 renames
10.fastapi-0010Easyfresher
What is APIRouter in FastAPI, and how do you structure a larger app with include_router?
APIRouter is a mini application that groups related routes, usually one per feature module such as students.py or fees.py. You add the router to the main app with app.include_router(router, prefix="/students", tags=["students"], dependencies=[...]), so prefixes, tags, shared dependencies and responses apply to every route inside. Routers can include other routers.
Full answer
Putting every endpoint in main.py works for a demo and becomes unmanageable at 40 endpoints. APIRouter splits the app by feature.
What include_router and APIRouter(...) can set for all routes in the group:
prefix: path prefix (must start with / and not end with /).
tags: grouping in /docs.
dependencies: run for every route, such as authentication. Their return values are not passed to handlers; use them for checks.
responses: shared documented error responses.
deprecated, include_in_schema.
Values from both the router and the include_router call are combined, so you can set tags in the module and a version prefix like /api/v1 in main.py.
Routers can nest: an api_v1 router includes students and fees routers, and the app includes api_v1 with prefix /api/v1. That makes API versioning straightforward.
Keep routers thin: parse input, call a service function, return a response model. Business logic in services is easier to test and reuse from background jobs.
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'roll_no': 12, 'name': 'Kabir'}
403 {'due': 4500}
['/api/v1/fees/due', '/api/v1/students/{roll_no}']
Ending a prefix with a slash, which produces double slashes
Expecting router-level dependency return values to reach handlers
Importing the app object into router modules and creating circular imports
Follow-ups
How would you version an API as /api/v1 and /api/v2 with shared code?
Where would you put authentication that applies to a whole module?
How do you avoid circular imports between routers and dependencies?
Tips
Sketch a folder layout
Explain what include_router parameters apply to
Mention keeping business logic out of route functions
11.fastapi-0011Easyfresher
How do you handle form data and file uploads in FastAPI?
Install python-multipart, then declare form fields with Form() and files with UploadFile (or bytes with File()). UploadFile streams large files through a spooled temporary file and gives filename, content_type, and async read(), write() and close() methods. A request cannot have both a JSON body and form data, and you should check file size and type yourself.
Full answer
HTML forms and file uploads use application/x-www-form-urlencoded or multipart/form-data, not JSON. FastAPI needs the python-multipart package to parse them (included in fastapi[standard]).
Since FastAPI 0.113 a Pydantic model can describe all form fields: data: Annotated[LoginForm, Form()].
Files:
file: UploadFile: recommended. Data is kept in memory up to a limit (1 MB by default), then spooled to a temporary file on disk, so a 200 MB upload does not fill RAM. Attributes: filename, content_type, size, file (the file-like object). Async methods: await file.read(), await file.seek(0), await file.close().
file: Annotated[bytes, File()]: the whole file in memory as bytes. Fine for small files only.
Several files: files: list[UploadFile].
Optional file: file: UploadFile | None = None.
You can mix Form() fields and files in one endpoint. You cannot mix them with a JSON body model, because the request has one content type. To send structured data with a file, send it as form fields or a JSON string field.
Security checks you must add yourself:
Size: reject files over a limit (check file.size or count bytes while reading in chunks). Set limits at the proxy too (client_max_body_size in Nginx).
Type: do not trust content_type or the extension alone; inspect the first bytes ("magic numbers") for critical types.
Name: never use filename directly as a path; generate your own name to avoid path traversal (../../etc/passwd).
Store uploads in object storage, not the app server's disk.
python
from typing import Annotated
import uuid
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.testclient import TestClient
app = FastAPI()
MAX_BYTES = 1_000_000
PDF_MAGIC = b"%PDF-"
@app.post("/assignments")
async def submit_assignment(
roll_no: Annotated[str, Form(min_length=3)],
subject: Annotated[str, Form()],
file: UploadFile,
):
head = await file.read(5)
if head != PDF_MAGIC:
raise HTTPException(status_code=415, detail="Only PDF files are accepted")
await file.seek(0)
data = await file.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
raise HTTPException(status_code=413, detail="File larger than 1 MB")
stored_as = f"{uuid.uuid5(uuid.NAMESPACE_URL, roll_no + subject)}.pdf" # never reuse the client name
return {"roll_no": roll_no, "subject": subject, "original": file.filename,
"stored_as": stored_as, "bytes": len(data)}
@app.post("/avatar")
def small_file(file: Annotated[bytes, File()]):
return {"bytes": len(file)}
c = TestClient(app)
pdf = b"%PDF-1.7\n" + b"x" * 100
r = c.post("/assignments", data={"roll_no": "BCA-17", "subject": "DBMS"},
files={"file": ("../../etc/notes.pdf", pdf, "application/pdf")})
print(r.status_code, r.json())
r = c.post("/assignments", data={"roll_no": "BCA-17", "subject": "DBMS"},
files={"file": ("photo.pdf", b"\x89PNG....", "application/pdf")})
print(r.status_code, r.json())
print(c.post("/avatar", files={"file": ("a.png", b"12345", "image/png")}).json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install python-multipart`.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
200 {'roll_no': 'BCA-17', 'subject': 'DBMS', 'original': '../../etc/notes.pdf', 'stored_as': 'a51efe6d-9640-5871-884e-05f7869166a6.pdf', 'bytes': 109}
415 {'detail': 'Only PDF files are accepted'}
{'bytes': 5}
Key points
Forms and files need python-multipart
Form() for fields; UploadFile for files
UploadFile spools large files to disk
No JSON body together with form data
Validate size, type and never trust filename
Common mistakes
Forgetting to install python-multipart
Using bytes = File() for large uploads and filling memory
Trusting the client's content_type, extension or filename
Trying to send JSON body and files in one request
Saving uploads on the app server's local disk
Follow-ups
How would you upload a 2 GB video without holding it in memory?
How would you let clients upload straight to object storage?
What is path traversal and how do you prevent it in uploads?
Tips
Explain UploadFile versus bytes with the memory trade-off
List the security checks you would add
Mention python-multipart as a requirement
12.fastapi-0012Easyfresher
How do you read headers and cookies in FastAPI, and how do you set them on the response?
Read headers with Header() and cookies with Cookie() parameters; FastAPI converts underscores in header parameter names to hyphens, so user_agent reads User-Agent. To set values, accept a Response parameter and call response.headers[...] = ... or response.set_cookie(...), or return a Response object with headers. Use httponly, secure and samesite flags for cookies that carry sessions.
Header names are case-insensitive. FastAPI converts x_request_id to x-request-id automatically. Disable with Header(convert_underscores=False) (rarely needed; some proxies drop headers with underscores).
Add a response: Response parameter, then response.headers["X-Total-Count"] = "42" or response.set_cookie(...). FastAPI merges these into the final response, even when you return a dict or model.
Or return a JSONResponse and call methods on it.
Cookie flags matter for security:
httponly=True: JavaScript cannot read it, which limits damage from XSS.
max_age or expires: lifetime; response.delete_cookie("session_id") to log out.
If a browser front end on another origin reads custom headers like X-Total-Count, list them in CORS expose_headers, or the browser hides them from JavaScript. For cookies sent cross-site, samesite="none" requires secure=True and CORS with allow_credentials=True.
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'user_agent': 'CampusApp/2.1', 'request_id': 'abc-123', 'theme': 'dark'}
{'ok': True} 1
session_id=s-8f3a; HttpOnly; Max-Age=3600; Path=/; SameSite=lax; Secure
Key points
Header() and Cookie() read request values
Underscores convert to hyphens for header names
A Response parameter lets you set headers and cookies
Use httponly, secure and samesite on session cookies
Expose custom headers via CORS for browser clients
Common mistakes
Expecting header parameter names with underscores to match exactly without conversion
Setting session cookies without httponly and secure
Forgetting CORS expose_headers so the browser hides custom headers
Creating a new Response object and losing the headers you set on the injected one
Follow-ups
How would you implement logout with cookies?
Why do some proxies drop headers that contain underscores?
When should you choose cookies over bearer tokens for a web app?
Tips
Mention the underscore to hyphen conversion
Name all three cookie security flags and why
Bring up CORS expose_headers for browser clients
13.fastapi-0013Easyfresher
How do you run a FastAPI application in development and in production?
In development, run fastapi dev main.py (from fastapi[standard]) or uvicorn main:app --reload, which restart on code changes. In production, run fastapi run or uvicorn without --reload, with several worker processes (--workers N, or Gunicorn managing Uvicorn workers, or one process per container scaled by Kubernetes), behind a reverse proxy or load balancer that handles TLS. Pass --proxy-headers so client IP and scheme are correct behind the proxy.
Full answer
FastAPI is an ASGI application object. A separate ASGI server runs it.
Development:
pip install "fastapi[standard]" installs the fastapi CLI, Uvicorn and common extras.
fastapi dev main.py starts Uvicorn with auto-reload on 127.0.0.1:8000.
Equivalent: uvicorn main:app --reload (main is the module, app the variable).
Production:
fastapi run main.py (Uvicorn without reload, listening on 0.0.0.0) or uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4.
Each worker is a separate process with its own event loop and memory. Use several to use all CPU cores. A starting point is one worker per core, then load test.
Alternatives: Gunicorn as process manager with -k uvicorn_worker.UvicornWorker; or in Kubernetes, one worker per container and scale with replicas, letting the orchestrator restart crashed pods.
Put a reverse proxy or load balancer in front for TLS, request size limits and buffering. Run with --proxy-headers and --forwarded-allow-ips set to the proxy's address so request.client.host and request.url.scheme reflect the real client.
Never use --reload in production; it watches files and runs a single process.
Containers: base on an official Python slim image, install dependencies first (better layer caching), run as a non-root user, and use the exec form CMD ["fastapi", "run", "app/main.py", "--port", "80"] so signals reach the server for graceful shutdown.
Running programmatically (uvicorn.run(app) inside if __name__ == "__main__":) is handy for debugging in an IDE.
python
import socket
import threading
import time
import httpx
import uvicorn
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/healthz")
def health(request: Request):
return {"status": "ok", "scheme": request.url.scheme}
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
port = free_port()
config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning",
proxy_headers=True, forwarded_allow_ips="127.0.0.1")
server = uvicorn.Server(config)
thread = threading.Thread(target=server.run)
thread.start()
while not server.started:
time.sleep(0.05)
print(httpx.get(f"http://127.0.0.1:{port}/healthz").json())
print(httpx.get(f"http://127.0.0.1:{port}/healthz", headers={"X-Forwarded-Proto": "https"}).json())
server.should_exit = True
thread.join()
print("server stopped cleanly")
# Command-line equivalents (not run here):
# fastapi dev main.py
# uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4 --proxy-headers --forwarded-allow-ips 10.0.0.5
Standalone script. It starts a real Uvicorn server on a free local port in a thread, calls it with httpx, and shuts it down. The CLI commands are shown as comments and were not run.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'status': 'ok', 'scheme': 'http'}
{'status': 'ok', 'scheme': 'https'}
server stopped cleanly
Key points
fastapi dev or uvicorn --reload for development
fastapi run or uvicorn --workers for production
Each worker is a separate process
Reverse proxy for TLS; --proxy-headers for real client info
Never use --reload in production
Common mistakes
Running uvicorn --reload in production
Running one worker on a multi-core machine and wondering why CPU sits idle
Forgetting --proxy-headers so every request appears to come from the proxy IP over http
Using the shell form of CMD in Docker so shutdown signals do not reach the server
Follow-ups
How many workers would you run on a 4-core machine, and why?
What is the difference between Gunicorn with Uvicorn workers and Kubernetes replicas?
How does graceful shutdown work for in-flight requests?
Tips
Separate dev and production commands clearly
Explain what a worker is
Mention proxy headers, a frequent production bug
14.fastapi-0014Easyfresher
How do you test a FastAPI application with TestClient?
TestClient wraps your app and lets you send requests with an httpx-style API (client.get, client.post with json=, params=, headers=) without starting a server. Write plain pytest functions that assert on response.status_code and response.json(). Use with TestClient(app) as client so lifespan startup and shutdown run, and app.dependency_overrides to swap databases or auth for tests.
Full answer
fastapi.testclient.TestClient is Starlette's test client. It calls the ASGI app in-process, so tests are fast and need no network. It is built on HTTPX; Starlette 1.x prefers the httpx2 package (same API, pip install httpx2) and warns when only the older httpx is installed.
A typical test file:
python
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_create_book():
r = client.post("/books", json={"title": "Godan", "copies": 2})
assert r.status_code == 201
assert r.json()["title"] == "Godan"
Run with pytest. Test functions are normal def functions even if endpoints are async def; TestClient handles the event loop.
Lifespan: with TestClient(app) as client: runs startup and shutdown code (opening a database pool, loading a model). A module-level client without with skips lifespan.
Dependency overrides: app.dependency_overrides[get_db] = get_test_db and app.dependency_overrides[get_current_user] = lambda: fake_user. Clear them after each test (app.dependency_overrides.clear()), ideally in a fixture.
Fixtures: a pytest fixture that yields a client and a clean database per test.
Validation tests: send bad input and assert 422 and the error loc.
Auth tests: assert 401 without a token and 403 with the wrong role.
For tests that must be async themselves (calling async database code directly in the test), use httpx.AsyncClient with ASGITransport and an async test runner such as pytest-anyio or pytest-asyncio.
Aim tests at behaviour (status, body, side effects in the database), not at internal function calls.
python
import pytest
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class BookIn(BaseModel):
title: str = Field(min_length=1)
copies: int = Field(ge=0)
def get_store():
raise RuntimeError("real database not available in tests")
def current_user():
raise HTTPException(status_code=401, detail="Not authenticated")
@app.post("/books", status_code=201)
def create_book(book: BookIn, user: str = Depends(current_user), store: dict = Depends(get_store)):
store[book.title] = book.copies
return {"title": book.title, "copies": book.copies, "added_by": user}
@pytest.fixture
def client():
store = {}
app.dependency_overrides[get_store] = lambda: store
app.dependency_overrides[current_user] = lambda: "librarian"
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
def test_create_book(client):
r = client.post("/books", json={"title": "Godan", "copies": 2})
assert r.status_code == 201
assert r.json() == {"title": "Godan", "copies": 2, "added_by": "librarian"}
def test_rejects_negative_copies(client):
r = client.post("/books", json={"title": "Godan", "copies": -1})
assert r.status_code == 422
assert r.json()["detail"][0]["loc"] == ["body", "copies"]
def test_requires_login():
r = TestClient(app).post("/books", json={"title": "Godan", "copies": 1})
assert r.status_code == 401
if __name__ == "__main__":
code = pytest.main([__file__, "-qq", "-p", "no:cacheprovider", "-p", "no:warnings"])
print("pytest exit code:", int(code))
Standalone pytest file. Run it with `python file.py` or `pytest file.py`; it needs `pip install pytest httpx2`. Dependencies resolve in parameter order, so current_user is listed first and an anonymous request fails with 401 before the store is touched.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, pytest 9.2.0):
... [100%]
pytest exit code: 0
Key points
TestClient calls the app in-process without a server
httpx-style API: json=, params=, headers=
Use 'with TestClient(app)' to run lifespan
dependency_overrides swap DB and auth in tests
Async tests use httpx.AsyncClient with ASGITransport
Common mistakes
Creating the client without 'with' and wondering why startup code did not run
Leaving dependency_overrides set and leaking fakes into other tests
Testing against a shared real database that tests pollute
Asserting only status codes and not the response body
Follow-ups
How would you give each test a fresh database?
When do you need httpx.AsyncClient instead of TestClient?
How do you test an endpoint that sends an email?
Tips
Show a fixture with dependency overrides
Mention the lifespan and 'with' detail
Cover a validation test and an auth test, not only the happy path
15.fastapi-0015Easyfresher
How do you restrict a FastAPI parameter to a fixed set of allowed values?
Declare the parameter with a str-based Enum or a Literal type. FastAPI validates the value, returns 422 listing allowed values when it is wrong, and shows a dropdown in /docs. Enums give a named type you can reuse and compare (Grade.A), while Literal["asc", "desc"] is lighter for one-off options.
Full answer
Free-text strings let clients send anything. When only a few values make sense (exam terms, sort orders, report formats), declare them as types.
Enum:
python
class Term(str, Enum):
mid = "mid"
final = "final"
supplementary = "supplementary"
@app.get("/results/{term}")
def results(term: Term): ...
Subclassing str (or using StrEnum from Python 3.11+) makes values JSON-friendly and comparable to strings.
Inside the function, term is a Term member: compare with term is Term.final or read term.value.
OpenAPI shows the allowed values, and Swagger UI renders a dropdown.
Wrong value gives 422 with type enum and a message listing the options.
Both work for path, query, header and body fields (in Pydantic models too).
Tips:
Use enums for values shared across several endpoints and models, so a new value is added in one place.
Keep enum values stable; they are part of the public API contract. Renaming a value is a breaking change.
For case-insensitive input, normalise with a validator or a custom _missing_ method on the enum, rather than adding duplicate members.
python
from enum import Enum
from typing import Literal
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class Term(str, Enum):
mid = "mid"
final = "final"
supplementary = "supplementary"
class ReportRequest(BaseModel):
term: Term
format: Literal["pdf", "csv"] = "pdf"
@app.get("/results/{term}")
def results(term: Term, order: Literal["asc", "desc"] = "asc"):
return {"term": term.value, "is_final": term is Term.final, "order": order}
@app.post("/reports")
def make_report(req: ReportRequest):
return req
c = TestClient(app)
print(c.get("/results/final?order=desc").json())
err = c.get("/results/annual").json()["detail"][0]
print(err["type"], "|", err["msg"])
print(c.post("/reports", json={"term": "mid", "format": "csv"}).json())
print(c.get("/openapi.json").json()["components"]["schemas"]["Term"]["enum"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'term': 'final', 'is_final': True, 'order': 'desc'}
enum | Input should be 'mid', 'final' or 'supplementary'
{'term': 'mid', 'format': 'csv'}
['mid', 'final', 'supplementary']
Key points
Enum or Literal restricts values
Wrong value gives 422 listing allowed options
Docs show a dropdown
str-based Enum is reusable and JSON-friendly
Enum values are part of the API contract
Common mistakes
Accepting any string and validating with if-statements in the handler
Using a plain Enum (not str-based) and getting awkward serialisation
Renaming enum values and breaking existing clients
Comparing an enum member to a string with 'is'
Follow-ups
How would you accept case-insensitive enum values?
When would you choose Literal over Enum?
How do enum changes affect API versioning?
Tips
Show both Enum and Literal
Mention the docs dropdown and 422 message
Treat enum values as a contract
16.fastapi-0016Easyfresher
Why does FastAPI recommend Annotated for parameters, as in Annotated[int, Query(ge=1)], instead of q: int = Query(...)?
Annotated keeps the real type and the default value separate from FastAPI metadata. The function stays a normal Python function with correct defaults, so it can be called directly in tests or other code, and type checkers see the true type. Annotated aliases also let you reuse the same parameter or dependency declaration in many endpoints. FastAPI has recommended this style since version 0.95.
Full answer
Older FastAPI code puts the metadata in the default value:
The default is a real default. In the old style, the default value is a Query object. Calling list_books() from a test or a script gives page a Query instance, not 1. With Annotated, list_books() gets page=1.
Type checkers and editors understand it. Annotated[int, ...] is just int to mypy and Pyright; the extra items are metadata that other tools ignore.
This removes copy-paste across dozens of endpoints and keeps rules consistent.
4. Required parameters are clearer. Without a default, it is required. No need for the old Query(...) with an Ellipsis.
The same pattern applies to Path, Body, Header, Cookie, Form, File and Depends.
Pydantic uses Annotated the same way for Field constraints, so one style covers models and endpoints.
Rules: put the default after =, not inside Query() when using Annotated (FastAPI raises an error if you do both). Parameters without defaults must come before those with defaults, as in any Python function, so reusable dependency aliases without defaults go first.
python
from typing import Annotated
from fastapi import Depends, FastAPI, Query
from fastapi.testclient import TestClient
PageParam = Annotated[int, Query(ge=1, le=500)]
def get_current_user() -> str:
return "librarian"
CurrentUser = Annotated[str, Depends(get_current_user)]
app = FastAPI()
@app.get("/old-style")
def old_style(page: int = Query(1, ge=1)):
return {"page": page}
@app.get("/books")
def list_books(user: CurrentUser, page: PageParam = 1):
return {"page": page, "user": user}
c = TestClient(app)
print(c.get("/books?page=3").json(), c.get("/books?page=0").status_code)
# Calling the functions directly, as a test or script might
print("old style default is:", type(old_style()["page"]).__name__)
print("Annotated default is:", list_books(user="tester")["page"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'page': 3, 'user': 'librarian'} 422
old style default is: Query
Annotated default is: 1
Key points
Annotated separates type, metadata and default
Functions stay callable with real defaults
Type checkers see the true type
Aliases like CurrentUser remove repetition
Recommended since FastAPI 0.95
Common mistakes
Putting the default inside Query() while also using Annotated
Calling old-style endpoint functions directly and getting Query objects as values
Copy-pasting the same Query constraints across endpoints instead of an alias
Ordering parameters with defaults before parameters without defaults
Follow-ups
How would you share a pagination dependency across all list endpoints?
What does a type checker see for Annotated[int, Query()]?
How do you migrate a large codebase from the old style?
Tips
Lead with the 'functions stay normal Python' benefit
Show a reusable alias
Mention the version where it became recommended
17.fastapi-0017Easyfresher
How do you return something other than JSON in FastAPI, such as HTML, plain text, a file or a redirect?
Return a Response subclass directly, or set response_class on the route. FastAPI provides JSONResponse, HTMLResponse, PlainTextResponse, RedirectResponse, FileResponse and StreamingResponse. Returning a Response object skips the response model and FastAPI's serialisation, so you control status, headers and media type; response_class keeps documentation accurate.
Full answer
By default FastAPI serialises the return value to JSON and wraps it in a JSONResponse. For other formats:
HTMLResponse: HTML pages or snippets. Set response_class=HTMLResponse so OpenAPI documents text/html, then return a string.
PlainTextResponse: plain text, for example a health check for a load balancer that expects text.
RedirectResponse(url, status_code=307): default 307 keeps the method and body; use 303 after a form POST so the browser follows with GET; 301 or 308 for permanent moves.
FileResponse(path, filename="report.pdf"): sends a file from disk efficiently with Content-Disposition and content length. filename triggers a download.
StreamingResponse(generator, media_type=...): sends data as it is produced (CSV exports, large files, server-sent events).
Response(content=bytes, media_type="image/png"): raw bytes with any media type.
Important behaviour: when you return a Response object yourself, FastAPI sends it as is. No response model validation or filtering, no jsonable_encoder. Make sure the content is already safe and correct.
For server-rendered HTML pages, use Jinja2 templates (fastapi.templating.Jinja2Templates) with autoescaping, not hand-built strings with user input, to avoid XSS.
You can also change the default for the whole app: FastAPI(default_response_class=...).
python
import tempfile
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse, RedirectResponse
from fastapi.testclient import TestClient
app = FastAPI()
report = Path(tempfile.mkdtemp()) / "term1.csv"
report.write_text("roll_no,marks\n1,88\n2,73\n")
@app.get("/notice", response_class=HTMLResponse)
def notice():
return "<h1>College closed on Friday</h1>"
@app.get("/ping", response_class=PlainTextResponse)
def ping():
return "pong"
@app.get("/old-results")
def old_results():
return RedirectResponse("/results", status_code=301)
@app.get("/reports/term1")
def download():
return FileResponse(report, media_type="text/csv", filename="term1-results.csv")
c = TestClient(app, follow_redirects=False)
r = c.get("/notice"); print(r.headers["content-type"], r.text)
r = c.get("/ping"); print(r.headers["content-type"], r.text)
r = c.get("/old-results"); print(r.status_code, r.headers["location"])
r = c.get("/reports/term1"); print(r.headers["content-disposition"], r.text.splitlines())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
text/html; charset=utf-8 <h1>College closed on Friday</h1>
text/plain; charset=utf-8 pong
301 /results
attachment; filename="term1-results.csv" ['roll_no,marks', '1,88', '2,73']
Key points
Return a Response subclass or set response_class
HTML, plain text, redirect, file, streaming and raw responses
Returned Response objects skip response models
303 after POST, 307/308 to keep the method
Use templates with autoescaping for HTML
Common mistakes
Returning HTML strings without response_class, so clients receive a JSON-encoded string
Building HTML with user input by string formatting (XSS)
Using 307 after a form POST, so the browser re-posts
Expecting response_model filtering to apply to a returned Response object
Follow-ups
How would you stream a 1 GB CSV export?
Which redirect code would you use after a successful form submission, and why?
How do you serve server-rendered pages with Jinja2 in FastAPI?
Tips
Name the classes and a use for each
Point out that returning a Response skips validation
Know the redirect status codes
18.fastapi-0018Mediummid
How does dependency injection work in FastAPI with Depends()?
A dependency is any callable (function or class) that FastAPI calls before your endpoint, passing its result as a parameter declared with Depends(). Dependencies can declare their own parameters (query, headers, other dependencies), forming a tree that FastAPI resolves per request, caching each dependency once per request by default. They are used for shared logic such as pagination, database sessions, authentication and permissions, and are easy to replace in tests with dependency_overrides.
Full answer
Dependency injection means a function receives what it needs instead of creating it. In FastAPI:
FastAPI inspects the endpoint signature and finds Depends(pagination).
It inspects pagination's signature: page and size are query parameters, so they are read and validated like endpoint parameters and appear in the OpenAPI docs.
It calls pagination(...) and passes the result as p.
Dependencies can depend on other dependencies, forming a graph: get_current_user depends on get_token and get_db; require_admin depends on get_current_user. FastAPI resolves the whole tree.
Caching: if two dependencies in one request both need get_db, FastAPI calls it once and shares the result. Use Depends(get_db, use_cache=False) to get a fresh call.
Where to attach dependencies:
As a parameter, when the endpoint needs the value.
In dependencies=[Depends(verify_key)] on the decorator, router or app, when you only need the side effect (a check that may raise).
Why use it:
Reuse: write auth or pagination once.
Separation: the endpoint describes what it needs, not how to build it.
Testing: app.dependency_overrides[get_db] = fake_db swaps implementations without patching.
Documentation: dependency parameters show up in OpenAPI automatically.
Sync and async dependencies both work; sync ones run in the thread pool. Dependencies with yield add setup and teardown, covered separately.
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The settings dependency is called once per request even though two dependencies use it.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'page': {'offset': 100, 'limit': 50}, 'settings_calls_so_far': 1}
401
{'offset': 0, 'limit': 5}
Key points
A dependency is a callable whose result is injected via Depends()
Dependencies have their own parameters and sub-dependencies
Results are cached once per request by default
dependencies=[...] runs checks without passing values
dependency_overrides makes testing easy
Common mistakes
Creating database sessions or clients inside every endpoint instead of a dependency
Expecting values from dependencies=[...] to be passed into the endpoint
Assuming a dependency is called twice when two sub-dependencies use it (it is cached)
Patching modules in tests instead of using dependency_overrides
Follow-ups
How would you write a dependency that requires a specific role?
What does use_cache=False change?
How do dependencies appear in the OpenAPI schema?
Tips
Explain the per-request resolution and caching
Give two real uses such as pagination and auth
Mention dependency_overrides for testing
19.fastapi-0019Mediummid
How do dependencies with yield work in FastAPI, for example to manage a database session?
A dependency that uses yield runs the code before yield as setup, injects the yielded value, and runs the code after yield as teardown once the response is ready. Wrapping yield in try/finally guarantees cleanup, and try/except lets you roll back on errors. In current FastAPI the exit code runs after the response is sent (scope="request", the default since 0.118), Depends(..., scope="function") (0.121+) closes it right after the endpoint returns, and since 0.110 an exception you catch after yield must be re-raised.
Full answer
Some resources need cleanup: a database session must be closed, a transaction committed or rolled back, a temporary file deleted. A yield dependency handles both ends:
python
def get_db():
db = SessionLocal()
try:
yield db
db.commit()
except Exception:
db.rollback()
raise
finally:
db.close()
The lifecycle per request:
FastAPI runs the code up to yield.
The yielded value is injected into the endpoint (and other dependencies).
The endpoint runs.
FastAPI resumes the generator: the code after yield runs. If the endpoint raised, the exception is thrown into the generator at the yield line, so except blocks can react.
Version details that matter (this behaviour changed several times):
0.106.0 moved the exit code to run before the response was sent, to release resources sooner. That broke StreamingResponse bodies that still needed the session.
0.110.0: if you catch an exception in a yield dependency and do not re-raise it, FastAPI raises a server error. Re-raise (or raise an HTTPException) so the real error is handled.
0.118.0 went back to running the exit code after the response is sent, so streaming responses can keep using the resource. This is the default, called scope="request".
0.121.0 added Depends(get_db, scope="function"), which runs the exit code right after the endpoint returns, before the response is sent. Use it when you want the connection back in the pool as early as possible.
With the default scope, background tasks run before the dependency's exit code (the snippet prints the order). Long background jobs should still open their own session so a slow task does not hold the request's connection.
An HTTPException raised in the exit code cannot change a response that has already been sent. The same applies to a failed commit() in a request-scoped dependency: the client may already have its 200. When the client must know whether the write succeeded, commit inside the endpoint or service function (or give the session dependency scope="function").
Rules:
Use try/finally for cleanup that must always happen.
Keep commit/rollback in one place (the dependency) or in service functions, not both.
Sync generator dependencies run in the thread pool; async ones (async def ... yield) run on the event loop. Use async ones with async libraries.
Each request gets its own instance, and within a request the value is cached, so the endpoint and other dependencies share the same session.
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. FakeSession stands in for a SQLAlchemy Session so the lifecycle is visible.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'marked': 7} ['open', 'audit open', 'audit close', 'background task', 'commit [7]', 'close']
404 ['open', 'audit open', 'audit close', 'rollback', 'close']
Key points
Code before yield is setup; after yield is teardown
try/except/finally around yield handles commit, rollback, close
Exceptions from the endpoint are thrown into the generator
Re-raise caught exceptions (required since 0.110)
Default scope='request' exits after the response; scope='function' exits right after the endpoint (0.121+)
Common mistakes
Forgetting finally, so sessions leak when the endpoint raises
Catching exceptions after yield and not re-raising them
Reusing the request's database session inside a background task
Committing in both the dependency and the endpoint
Committing in a request-scoped exit step and assuming a commit failure will reach the client
Follow-ups
Why did FastAPI move the exit code of yield dependencies back to after the response in 0.118?
How would you share one transaction across several dependencies in a request?
When would you use an async generator dependency?
Tips
Walk through the four steps of the lifecycle
Show commit, rollback and close in the right places
Mention the version changes; it shows you keep up
20.fastapi-0020Mediummid
How do you write parametrised or class-based dependencies in FastAPI, for example a role check like require_role("admin")?
A dependency only has to be callable. A class can be a dependency (FastAPI calls the class and injects the instance), and an instance with __call__ can be a configurable dependency: RoleChecker(["admin"]) stores settings in __init__ and checks the request in __call__. A function that returns an inner function (a factory) works the same way. This avoids writing one near-identical dependency per role or limit.
Full answer
Sometimes the same check needs different settings: "admin only" on one route, "teacher or admin" on another. Writing require_admin, require_teacher, require_teacher_or_admin duplicates code.
Option 1: a callable instance
python
class RoleChecker:
def __init__(self, allowed: list[str]):
self.allowed = allowed
def __call__(self, user: User = Depends(get_current_user)) -> User:
if user.role not in self.allowed:
raise HTTPException(403, "Not allowed")
return user
@app.delete("/marks/{id}", dependencies=[Depends(RoleChecker(["admin"]))])
RoleChecker(["admin"]) runs once when the module loads. FastAPI inspects __call__'s signature and calls it per request.
Option 2: a factory function
python
def require_role(*roles):
def checker(user: User = Depends(get_current_user)):
...
return checker
Same idea with a closure. Simple and readable.
Option 3: a class as the dependency itself
python
class Filters:
def __init__(self, q: str | None = None, page: int = 1): ...
def list_items(f: Annotated[Filters, Depends()]): ...
FastAPI calls Filters(q=..., page=...) using the __init__ parameters. Depends() with no argument means "use the type annotation". Since FastAPI 0.115 a Pydantic model with Query() is often cleaner for grouped query parameters.
Notes:
The instance in option 1 is shared across requests, so do not store per-request state on self.
Overriding in tests: override the inner dependency (get_current_user), not each RoleChecker instance, because instances are different objects.
Combine with Security() and scopes when the roles map to OAuth2 scopes.
python
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
USERS = {"t1": {"name": "Ms. Kapoor", "role": "teacher"}, "a1": {"name": "Mr. Rao", "role": "admin"},
"s1": {"name": "Ishaan", "role": "student"}}
class User(BaseModel):
name: str
role: str
def get_current_user(x_token: Annotated[str, Header()]) -> User:
if x_token not in USERS:
raise HTTPException(status_code=401, detail="Unknown token")
return User(**USERS[x_token])
class RoleChecker:
def __init__(self, allowed: list[str]):
self.allowed = allowed
def __call__(self, user: User = Depends(get_current_user)) -> User:
if user.role not in self.allowed:
raise HTTPException(status_code=403, detail=f"Requires one of {self.allowed}")
return user
class MarkFilters:
def __init__(self, subject: str | None = None, min_score: int = 0):
self.subject, self.min_score = subject, min_score
@app.get("/marks")
def list_marks(f: Annotated[MarkFilters, Depends()],
user: Annotated[User, Depends(RoleChecker(["teacher", "admin"]))]):
return {"viewer": user.name, "subject": f.subject, "min_score": f.min_score}
@app.delete("/marks/{mark_id}", dependencies=[Depends(RoleChecker(["admin"]))])
def delete_mark(mark_id: int):
return {"deleted": mark_id}
c = TestClient(app)
print(c.get("/marks?subject=Physics&min_score=40", headers={"X-Token": "t1"}).json())
print(c.get("/marks", headers={"X-Token": "s1"}).json())
print(c.delete("/marks/5", headers={"X-Token": "t1"}).status_code, c.delete("/marks/5", headers={"X-Token": "a1"}).json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'viewer': 'Ms. Kapoor', 'subject': 'Physics', 'min_score': 40}
{'detail': "Requires one of ['teacher', 'admin']"}
403 {'deleted': 5}
Key points
Any callable can be a dependency
Callable instances hold config in __init__ and check in __call__
Factory functions with closures do the same
Depends() with no argument uses the annotated class
Do not keep per-request state on shared instances
Common mistakes
Writing a separate dependency function for every role combination
Storing request data on a shared dependency instance
Trying to override each RoleChecker instance in tests instead of the user dependency
Forgetting that Depends() without arguments needs a type annotation
Follow-ups
How would you combine roles with OAuth2 scopes?
How do you test endpoints guarded by RoleChecker?
What is the difference between Depends() and Depends(SomeClass)?
Tips
Show the callable-instance pattern and explain when __init__ and __call__ run