Skip to content
Tech Interview Prep
Technical interview guideNew

FastAPI Web Services

How FastAPI routes, validates, injects dependencies and serves requests on Starlette and Uvicorn, and what interviewers probe about async handlers, auth, sessions and production workers.

Read
14 min
Practice MCQs
25
Interview Q&A
25
Edition
v1
Editorial status
Reviewed

Scope: FastAPI 0.100 or later (Pydantic v2 support), Python 3.10 or later, current Starlette and Uvicorn releases. Behaviour of response_model, Depends caching and yield dependency teardown is stated for these versions; re-check the official docs if a newer FastAPI major changes them..

Curated: · Written: · Reviewed:

25 questions · Flow follows Relevance until this set has a learning order.

MCQ-1A FastAPI service's p99 latency rises from 40 ms to 900 ms when one `async def` route calls `requests.get` on a partner API that takes about 800 ms per call. The team must keep `requests` because a shared client wrapper depends on it. Which change stops the stall with the smallest edit?
MCQ-2A route is declared as `@app.get("/items/{item_id}")` with `def read_item(item_id: int)`, and a client sends a GET to `/items/abc`. The handler body is never entered. Which response does FastAPI send to the client?
MCQ-3A route declares `response_model=UserPublic`, a Pydantic v2 model with `id` and `email` fields and `model_config = ConfigDict(extra='allow')`. The handler returns a plain dict containing `id`, `email` and `password_hash`. What does the client receive for `password_hash`?
MCQ-4A router is built with `APIRouter(dependencies=[Depends(get_current_user)])`. Its `GET /reports/{report_id}` handler takes `user: User = Depends(get_current_user)`. `get_current_user` increments a counter on every call, and no other option is set. One client sends one GET request. What does the counter read after that request, and which single edit makes it read 2 on the same request?
MCQ-5A route depends on `get_session`, a yield dependency that opens a SQLAlchemy session, yields it, and runs `session.commit()` on the line after `yield` with no try block. The handler adds an `Order` row, then raises `OrderRejected`, which a registered exception handler turns into a 409. What happens to the row?
MCQ-6A FastAPI route is declared with plain `def` and calls `time.sleep(0.3)` while a partner API responds. A second request arrives at the same worker during that wait. Where does the first handler run, and what happens to the second request?
MCQ-7A FastAPI service runs `uvicorn app:app --workers 16` in a container limited to 2 vCPUs and 2 GiB of memory. Each worker imports the app and holds about 120 MB resident. The routes are CPU-light JSON APIs that mostly await a database. Under peak load the container is OOM-killed while CPU stays below 40%. What is the most accurate fix?
MCQ-8A POST /users handler returns 201 and adds a BackgroundTasks job that sends a welcome email through an in-process SMTP client. The pod is evicted during a rolling deploy one second after the response is sent. What guarantee does the design provide?
MCQ-9A FastAPI orders service verifies JWTs by checking only the signature and the `exp` claim. The auth service issues tokens for the orders API and the billing API with the same `iss` value and one shared HS256 key. A token minted for billing's own API is accepted by the orders routes. Which single change closes the gap while keeping the shared key?
MCQ-10An engineer must revoke one user's access immediately on every instance of a FastAPI service. The service issues stateless JWT access tokens with a 60-minute lifetime and keeps no server-side session store. Which design meets the requirement?
MCQ-11A pytest module sets `app.dependency_overrides[get_db]` to a generator that yields a SQLite session seeded with one order. `POST /orders` takes `db: Session = Depends(get_db)` and reads the seeded row through it, but the handler then calls `reserve()` from a module-level import, and that helper opens its own `SessionLocal()` and commits. The test's response matches the seed, yet production gets a new row. What is the most likely cause?
MCQ-12A route declares `response_model=UserOut`, where `UserOut` has a required `nickname: str`, and the OpenAPI document lists `nickname` as required. The handler returns the dict `{"id": 7, "email": "a@example.com"}` with no `nickname` key, and the route sets no `response_model_exclude_unset`. What does the client receive?
MCQ-13A FastAPI service caps each API key at 100 requests per minute using a module-level dictionary of counters, with no Redis. It runs as `gunicorn -k uvicorn.workers.UvicornWorker -w 4`. One key sends 400 requests spread evenly over one minute, and the kernel spreads its connections roughly evenly across the four workers. How many of those requests succeed, and why?
MCQ-14A FastAPI handler calls `create_engine(DATABASE_URL)` on every request, so each request builds a new connection pool that is discarded when the response returns. Under load, p95 latency climbs. Which change addresses the root cause?
MCQ-15A `POST /charges` handler wraps its body in `try/except Exception` and returns `JSONResponse({"error": "db timeout"}, status_code=200)` when the database times out after the card is charged. During a brownout 40 of 5,000 requests in five minutes time out this way. The alert fires when 5xx exceeds 1% of requests over five minutes, and the mobile client retries any non-2xx status. What does the alert do?
MCQ-16A route depends on a yield dependency that opens a SQLAlchemy Session, yields it, and calls `session.commit()` on the line after `yield` with no try block. The handler calls `db.add(Invoice(...))` and `db.flush()`, then raises `RuntimeError('gateway timeout')`, which no handler catches. What happens to the invoice row?
MCQ-17An endpoint is declared `async def` and calls a synchronous image resize that holds the CPU for 2 seconds per request. Other routes on the same worker slow to several seconds under load, while the host still has idle cores. Which change best protects those other requests on that worker?
MCQ-18A FastAPI service is deployed to production with `uvicorn app:app --reload` as its start command, running one Uvicorn process per pod behind a load balancer that routes to four pods. What is the main problem?
MCQ-19A FastAPI test overrides get_now to return 2024-05-01T12:00:00Z for every request. A coupon row starts with expires_at 2024-05-01T12:00:01Z. The route returns 410 when expires_at <= now. On success it sets coupon.expires_at = now and commits through the session that get_tenant opens for that request. The test posts to /coupons/redeem twice, and the first POST returns 200. What does the second POST return?
MCQ-20A service's routes get configuration through `Depends(get_settings)`. `get_settings` is decorated with `functools.lru_cache` and returns `Settings()`, which reads `DATABASE_URL` and `FEATURE_FLAG` from `os.environ` on its first call. Each pytest test needs its own values for those two variables. Which setup gives each test its values?
MCQ-21A GET /articles handler is declared as `def list_articles(tags: str | None = None)` and filters by tag. A client sends `/articles?tags=python` and the handler receives the string `'python'`, so looping over it yields single characters. The team wants one route that accepts one tag or several repeated `tags` values as a list. Which declaration does that?
MCQ-22A Pydantic model declares `name: str` with no default, and a POST route takes it as a body parameter. The client sends an empty JSON object `{}`. What does FastAPI return to the client?
MCQ-23A GET /quotes/{id} route is declared with plain def and takes Depends(get_partner_price), an async def dependency that calls requests.get on a partner API taking about 800 ms. Under load, p95 of an unrelated GET /health rises only while quote requests are in flight, and worker CPU stays under 20%. The shared client wrapper must keep using requests. Which change removes the stall?
MCQ-24A POST /invoices route depends on get_current_user and get_tenant, and both dependencies need a database session. The handler adds an Invoice and a LedgerEntry and flushes them, and a failure after that flush must roll back both rows. Which design gives the dependencies and the handler one shared session?
MCQ-25Two FastAPI services validate the same bearer token with PyJWT, and both hosts run NTP-synced clocks. The token's `exp` is 10:00:00 UTC. At 10:00:20 UTC the orders service accepts the token, while the billing service returns 401 with 'Signature has expired'. Both verify with the same HS256 key. Which difference explains the split?