Given this FastAPI endpoint code snippet, what will be the JSON response when a GET request is made to /users/1 assuming the user with ID 1 exists in the database?
from fastapi import FastAPI, Depends, HTTPException from sqlalchemy.orm import Session app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get('/users/{user_id}') async def read_user(user_id: int, db: Session = Depends(get_db)): user = db.query(User).filter(User.id == user_id).first() if not user: raise HTTPException(status_code=404, detail='User not found') return {'id': user.id, 'name': user.name}
Check what the endpoint returns when the user is found and how the dictionary keys are named.
The endpoint queries the database for a user with the given ID. If found, it returns a dictionary with keys id and name. So the JSON response will have those keys and values.
Choose the correct code snippet that defines a get_db dependency yielding a SQLAlchemy session and properly closing it after use.
Remember that yield inside try and finally ensures the session closes after use.
Option C correctly uses try and finally to close the session after yielding it. Option C closes the session immediately after yielding, which is incorrect. Option C uses a context manager but SessionLocal is not a context manager by default. Option C returns the session without closing it.
Consider this code snippet. What is the cause of the error when the endpoint tries to query the database?
from fastapi import FastAPI, Depends from sqlalchemy.orm import Session app = FastAPI() @app.get('/items') async def read_items(db: Session = Depends()): items = db.query(Item).all() return items
Check the Depends() usage and what it expects as an argument.
Depends() requires a callable to provide the dependency. Here, it is empty, so FastAPI cannot inject the database session. The correct usage is Depends(get_db).
Given this get_db dependency and endpoint, what happens to the database session after the endpoint returns the response?
def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get('/data') async def get_data(db: Session = Depends(get_db)): return db.query(Data).all()
Think about how yield and finally work in the dependency.
The yield pauses the function and lets FastAPI use the session. After the endpoint finishes, the finally block runs and closes the session properly.
Choose the most accurate explanation of why SQLAlchemy sessions are provided as dependencies in FastAPI endpoints.
Consider how database connections should be managed per request in web apps.
Providing sessions as dependencies ensures each request uses its own session that is closed after the request, avoiding connection leaks and ensuring thread safety. Sharing sessions or caching results globally is unsafe and not the intended use.