More in Backend Dev — page 19
How do you test a FastAPI endpoint without real tokens?
Tests whether you know FastAPI's dependency override mechanism to isolate business logic from auth. A great answer describes using app.dependency_overrides to swap the auth Depends for a mock returning a fake user, then cleaning up after the test.
Explain FastAPI dependency overrides with an in-memory SQLite test example
This tests FastAPI's hook for swapping dependencies cleanly in tests. A strong answer names app.dependency_overrides, defines a test-only in-memory SQLite session, and handles teardown. A red flag is patching globals or mocking ORM instead of dependency.
What is FastAPI's TestClient and how does it differ from requests?
Tests if you know TestClient runs pytest against the app directly without a live server. Good answers note its HTTPX-based Requests-like API, passing the FastAPI app into the client, and simple asserts. Red flag: saying you need a running server and real URLs.
How do you test a FastAPI GET endpoint with pytest and TestClient?
WHAT IT TESTS: FastAPI testing with TestClient. ANSWER OUTLINE: Import TestClient and app, write a test_ function, call client.get("/items/1"), assert status_code == 200 and json() matches expected data. RED FLAG: Using requests or forgetting test_ prefix.

Design DB transaction middleware and identify the background-task pitfall
Tests request-scoped DB lifecycle awareness. Strong answer: middleware closes the session on response, yet BackgroundTasks run afterward, so sharing that session causes crashes or leaks. Red flag: saying background tasks can reuse the request transaction.
Why is FastAPI BackgroundTasks poor for multi-minute PDF generation?
Tests whether you know BackgroundTasks is same-process and for seconds, not minutes. Answer: propose a task queue with broker, workers, and result backend; return HTTP 202 with a job ID. Red flag: suggesting FastAPI workers instead of persistence and retries.
Which FastAPI CORSMiddleware parameters beyond allow_origins fix a PUT preflight?
WHAT IT TESTS: CORS preflight mechanics for non-simple requests. ANSWER OUTLINE: Configure allow_methods for PUT and allow_headers for Authorization so the browser approves the cross-origin call.
Write a FastAPI middleware that adds X-Process-Time header
Tests FastAPI lifecycle and header mutation. Strong answers use the http middleware decorator, await call_next, compute elapsed time, and inject X-Process-Time before returning. Red flag: forgetting to await call_next or mutating headers after the return.
Purpose of await next(request) in FastAPI middleware and timing effects
Tests ASGI middleware lifecycle. await next(request) forwards the request downstream to the endpoint and returns the response. Pre-call code touches the request; post-call code touches the response.
How do you send an email without blocking a FastAPI request?
Tests knowledge of FastAPI's BackgroundTasks for post-response work. Strong answer: import it, inject into the endpoint, define a task function, and call add_task before returning. RED FLAG: Recommending raw asyncio.create_task or insisting Celery is required.
Frontend on localhost:3000 gets errors calling FastAPI on localhost:8000. Name and fix?
This tests whether different ports mean different origins, causing CORS errors. A strong answer names CORS, notes ports are distinct origins, and outlines using CORSMiddleware with allow_origins.
What JWT claims must you validate beyond the signature?
This tests whether you understand token misuse beyond crypto: time validity, audience and issuer binding, algorithm whitelisting, and required claims enforcement. Red flag: only checking signature and ignoring exp or aud.

How do OAuth2 scopes enable granular permissions in FastAPI versus role-based checks?
Tests OAuth2 scope granularity vs RBAC and FastAPI SecurityScopes. Strong answers mention JWT claim strings, SecurityScopes per endpoint, and that RBAC is coarse while scopes are fine-grained. Red flag: treating scopes as roles or skipping claim checks.

Implement RBAC in FastAPI with a JWT role dependency
WHAT IT TESTS: FastAPI dependency composition for JWT role validation. ANSWER OUTLINE: build a dependency that decodes the JWT, checks the role, raises 403 if not admin, and inject via Depends. RED FLAG: parsing headers inside route not using dependencies.

Implement OAuth2 Password Flow in FastAPI
Tests FastAPI security integration and stateless auth patterns. A strong answer covers the POST /token endpoint returning a JWT, the OAuth2PasswordBearer dependency, and get_current_user decoding the JWT sub.
How should you store user passwords in a database?
Tests knowledge of slow salted hashing versus encryption. Strong answers pick Argon2id or bcrypt, require unique per-user salts, describe verification via re-hashing with constant-time comparison, and cite bcrypt or argon2-cffi.
What are the three components of a JWT?
Tests if you know JWT structure beyond library usage. A strong answer lists header, payload, and signature; notes Base64Url encoding; and gives a registered claim like exp. A red flag is confusing signing with encryption.

How do you protect a FastAPI endpoint using Depends and OAuth2PasswordBearer?
WHAT IT TESTS: your grasp of FastAPI dependency injection for security. ANSWER OUTLINE: OAuth2PasswordBearer sets the token URL, Depends injects it into the endpoint, and FastAPI validates the Bearer header.
How do you atomically create an order and update inventory?
Tests transaction boundaries and SQLAlchemy 2.0 session lifecycle in FastAPI. A strong answer wraps both writes in session.begin(), flushes to catch constraint errors early, and uses exceptions to trigger rollback.
Implement a PATCH endpoint for partial SQLAlchemy updates
Tests PATCH vs PUT and selective ORM updates. Strong answer: all-optional update schema, load existing record, iterate exclude_unset=True fields with setattr, commit. Red flag: updating without excluding unset, which overwrites missing fields with None.