FastAPI has become the go-to Python web framework for building high-performance APIs. Its dependency injection system, lifecycle management with lifespan, and Pydantic-powered response models make it powerful and expressive for professional backend development.
0 / 5 completed
1 / 5
A function is declared as a FastAPI dependency with Depends() and uses yield. What does the code after yield typically do?
A dependency that yields acts like a context manager: code before yield runs setup (e.g., open a DB session) and code after yield runs teardown (e.g., close the session) once the response is sent.
2 / 5
What is the purpose of BackgroundTasks in FastAPI?
BackgroundTasks lets you add callables that execute after the response is returned, keeping response latency low. They run in the same event loop/thread as the app, so they are best suited for I/O tasks like sending emails.
3 / 5
You define a route with response_model=UserOut. The handler returns a SQLAlchemy ORM object with extra fields not in UserOut. What does FastAPI do?
response_model tells FastAPI to validate and serialize the return value through the specified Pydantic model, which automatically strips any fields not declared in the model, preventing accidental data leakage.
4 / 5
What does the lifespan parameter on a FastAPI application replace in modern FastAPI?
The lifespan context manager (introduced as the preferred pattern in FastAPI 0.93+) replaces the older @app.on_event('startup') and @app.on_event('shutdown') decorators, consolidating startup and shutdown logic in one place.
5 / 5
A route decorated with @app.post('/items', status_code=201) calls a dependency that raises HTTPException(status_code=404). What HTTP status code is returned?
Raising HTTPException always overrides the route's declared status_code. FastAPI's exception handler intercepts it and returns the status specified in the exception, in this case 404.