
Most AI products that a Forward Deployed Engineer ships end up behind an HTTP API, and in Python that API is very often FastAPI. Interviewers for AI engineer and FDE roles know this, so they ask FastAPI questions that go past "hello world": how dependency injection interacts with database sessions, why a streaming endpoint goes silent behind a load balancer, what happens when a blocking SDK call sits inside async def, and how to call an LLM provider without double-charging a customer on retry.
This guide has 52 questions in eleven groups, from fundamentals to production scenarios. Every behaviour described here was checked against the FastAPI, Pydantic, Starlette and Python documentation on 5 December 2026 (FastAPI 0.165.1 and Pydantic 2.14.4 were the current PyPI releases that day). Code samples are illustrative: they show the pattern an interviewer wants to hear, not a complete service. General Python questions are deliberately left out so this page stays about building and running APIs.
FastAPI fundamentals
1. How does FastAPI decide whether a parameter comes from the path, the query string or the body?
The FastAPI tutorial gives three rules. A parameter that also appears in the path template is a path parameter. A parameter of a singular type such as int, str or bool is a query parameter. A parameter typed as a Pydantic model is the request body. A default value (for example q: str | None = None) is what makes a query parameter optional; the type annotation is for editors and validation.
2. What does a return type annotation or response_model actually do?
FastAPI uses it to validate the returned data, add the response JSON Schema to OpenAPI, serialize with Pydantic, and filter the output to only the declared fields. If you declare both, response_model wins. For an AI endpoint, filtering matters: if your handler returns an internal object that holds the raw prompt, retrieved chunks or a trace ID, a narrow response model keeps those out of the response even if someone adds fields to the internal object later.
3. Explain def versus async def path operations.
The FastAPI docs say a path operation declared with plain def "is run in an external threadpool that is then awaited". An async def function runs on the event loop. The same applies to dependencies. The docs' guidance is to use async def unless the function performs blocking I/O, and "if you just don't know, use normal def".
4. A colleague calls a synchronous SDK (for example boto3) inside an async def endpoint. What goes wrong and how do you fix it?
The blocking call runs on the event loop thread, so while it waits on the network no other request on that worker makes progress. Latency for unrelated users climbs, and streaming responses stall. Three fixes: declare the endpoint with plain def so FastAPI runs it in the threadpool; keep async def and push the blocking call to a thread with await asyncio.to_thread(fn, ...) (added in Python 3.9); or use an async-native client. Say which one you would choose and why: to_thread is the smallest change when only one call in an otherwise async handler blocks.
5. What is the lifespan handler and why do AI services use it?
Lifespan is an async context manager passed as FastAPI(lifespan=lifespan). Code before yield runs once at startup, before requests are served; code after yield runs at shutdown. It is where you create long-lived clients (HTTP connection pools, LLM SDK clients, vector store clients) or load a local embedding model once instead of per request. The docs mark @app.on_event("startup") handlers as deprecated and warn that if you provide lifespan, startup and shutdown event handlers are no longer called: "It's all lifespan or all events, not both." Lifespan also runs only for the main application, not for mounted sub-applications.
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(timeout=httpx.Timeout(30.0, connect=5.0))
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
6. How would you organise a FastAPI codebase that has chat, ingestion and admin endpoints?
Split routes into APIRouter modules (routers/chat.py, routers/ingest.py, routers/admin.py) and include them in the app with a prefix and tags. Put shared request and response models in a schemas package, clients and settings in a core package, and dependencies (auth, current tenant, rate-limit checks) in one module so every router reuses the same functions. Router-level dependencies let you require admin auth on every admin route without repeating it on each handler.
Pydantic v2 models and validation
7. What changed in Pydantic v2 that breaks v1-era FastAPI code?
The Pydantic migration guide lists the renames you will hit first: dict() became model_dump(), json() became model_dump_json(), parse_obj() became model_validate(), copy() became model_copy(), @validator became @field_validator, @root_validator became @model_validator, orm_mode became from_attributes, and the inner Config class is deprecated in favour of a model_config attribute. Old method names still work where possible but emit DeprecationWarning, which is a good thing to grep CI logs for.
8. Field validators come in four modes. Name them and give a use for before.
Field validators can be after (the default), before, plain and wrap. Model validators can be before, after and wrap. A before validator sees the raw input before Pydantic's own parsing, so it suits normalisation: stripping whitespace from a query, or accepting a comma-separated string of document IDs and splitting it into a list before the list type is enforced. An after validator sees the already-typed value and suits business rules.
9. Inside a validator, which exception should you raise?
The Pydantic docs list ValueError as the most common, AssertionError (with the warning that assert statements are skipped when Python runs with -O), and PydanticCustomError for more control. Pydantic collects these into a ValidationError itself; you do not raise ValidationError from inside a validator. In an interview, mention the -O trap: a production image started with optimisations silently skips assert-based checks.
10. Why would you set extra="forbid" on request models for an agent or tool-calling API?
By default Pydantic ignores extra fields. With model_config = ConfigDict(extra="forbid"), "providing extra data is not permitted" and the request fails validation. For APIs that an LLM or another agent calls, a misspelled or hallucinated field ("approve": true instead of "approved") should fail loudly instead of being silently dropped while the call appears to succeed.
11. What is lax mode, and when do you want strict mode?
Pydantic's default lax mode coerces compatible input; the docs' example shows the string '123' becoming the integer 123. Strict mode performs no conversion. Lax mode is friendly for browser forms and query strings. Strict mode suits money amounts, IDs and flags coming from model output, where an unexpected type is a sign the model went off-script and you would rather retry than guess.
12. How do you validate JSON that an LLM returns?
Define the expected shape as a Pydantic model and call Model.model_validate_json(raw_text), which validates a JSON string or bytes directly. Catch ValidationError, and on failure either retry once with the error messages appended to the prompt or return a controlled error. Keep the retry count small and log the failing output (minus sensitive data) so you can tell a prompt problem from a model problem.
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class TicketTriage(BaseModel):
model_config = ConfigDict(extra="forbid")
category: str = Field(max_length=40)
priority: int = Field(ge=1, le=4)
summary: str = Field(max_length=500)
def parse_triage(raw: str) -> TicketTriage | None:
try:
return TicketTriage.model_validate_json(raw)
except ValidationError as exc:
# log exc.errors() without the raw customer text, then retry or fail
return None
13. How do you cap prompt size at the API boundary?
Use field constraints: question: Annotated[str, Field(min_length=1, max_length=4000)] and list length limits on things like attached document IDs. This rejects oversized input with a 422 before you spend tokens or embedding calls on it. Character limits are a cheap first gate; token limits still need checking closer to the model call, because characters and tokens don't map one-to-one.
14. What does from_attributes=True do?
It is the v2 name for orm_mode. It lets model_validate read attributes from an object (for example an SQLAlchemy row) instead of requiring a dict, which is how you turn ORM results into response models.
Dependency injection
15. What problems does Depends solve in an AI API?
It gives one place for cross-cutting work: authenticating the caller, resolving the tenant, opening a database session, fetching per-tenant settings (which model, which knowledge base), and checking quotas. Handlers declare what they need instead of building it. The same mechanism makes testing easy, because each dependency can be swapped out (question 18).
16. If three dependencies all depend on get_current_user, how many times does it run per request?
Once. The FastAPI docs say that when a sub-dependency is declared multiple times for the same path operation, FastAPI calls it once per request and caches the value for every dependant. If you really need a fresh call each time, use Depends(fn, use_cache=False).
17. When does the cleanup code in a dependency with yield run?
Code before and including yield runs before the response is created. By default (scope "request") the code after yield runs after the response is sent. With Depends(fn, scope="function") the cleanup runs after the path operation function returns but before the response is sent. This matters for streaming: a database session that a streaming generator still needs must not be closed with function scope. If you catch an exception in a yield dependency, the docs say to re-raise it unless you raise another HTTPException; otherwise the client gets a 500 and the server has no log of the original error.
from typing import Annotated
from fastapi import Depends
async def get_session():
session = SessionLocal()
try:
yield session
except Exception:
await session.rollback()
raise # re-raise so the error is logged
finally:
await session.close()
SessionDep = Annotated[AsyncSession, Depends(get_session)]
18. How do you test an endpoint without calling the real LLM?
Wrap the model client in a dependency (get_llm) and, in tests, set app.dependency_overrides[get_llm] = fake_llm. The override applies wherever the dependency is used, including router and decorator dependencies. Reset with app.dependency_overrides = {} at the end of the test. This is far more reliable than monkeypatching an SDK's internals.
Async, concurrency and background work
19. Your endpoint calls the LLM provider. How do you stop one replica from exceeding the provider's concurrency limit?
Create an asyncio.Semaphore in lifespan and acquire it around the provider call. That bounds in-flight calls per process. Remember the bound is per worker process and per replica, so the effective total is semaphore size times workers times replicas; the provider-side quota is the real ceiling, and you still need retry handling for throttling responses.
20. How do BackgroundTasks work?
Declare a parameter of type BackgroundTasks and call background_tasks.add_task(fn, *args, **kwargs). Tasks run after the response is sent. The function can be sync or async. You can add tasks from dependencies too; FastAPI merges them and runs them all after the response.
21. Would you use BackgroundTasks to re-embed 20,000 documents after an upload?
No. The FastAPI docs note that background tasks run in the same process as the app and point to a dedicated tool such as Celery (with a broker like RabbitMQ or Redis) for heavy computation. In-process tasks share CPU with request handling and disappear if the container is stopped mid-job. Accept the upload, write a job record, put a message on a queue, and let a separate worker service do the embedding. BackgroundTasks is fine for small follow-ups such as writing an audit record or sending a notification.
22. What do asyncio.timeout() and asyncio.wait_for() give you around an LLM call?
Both cancel the awaited work and raise TimeoutError when the deadline passes. asyncio.timeout() is a context manager added in Python 3.11, so it can wrap several awaits under one deadline (retrieve, then generate). Since 3.11, wait_for raises the built-in TimeoutError rather than asyncio.TimeoutError. Set the overall request deadline below your load balancer's idle timeout so your code, not the proxy, decides what the user sees.
Streaming responses and SSE for LLM output
23. How do you stream LLM tokens to a browser with FastAPI today?
FastAPI 0.135.0 added first-class Server-Sent Events. Set response_class=EventSourceResponse (from fastapi.sse) and write an async generator. Yielded objects are JSON-encoded into the data: field; yield ServerSentEvent objects to set event, id, retry or a comment, or use raw_data to skip JSON encoding. The docs note SSE works with any HTTP method, including POST, which suits chat endpoints that take a JSON body.
from collections.abc import AsyncIterable
from fastapi import FastAPI, Request
from fastapi.sse import EventSourceResponse, ServerSentEvent
from pydantic import BaseModel, Field
app = FastAPI()
class ChatIn(BaseModel):
question: str = Field(min_length=1, max_length=4000)
@app.post("/chat/stream", response_class=EventSourceResponse)
async def chat_stream(body: ChatIn, request: Request) -> AsyncIterable[ServerSentEvent]:
async for token in llm_stream(body.question): # your provider wrapper
if await request.is_disconnected():
break # stop paying for tokens nobody reads
yield ServerSentEvent(data={"t": token}, event="token")
yield ServerSentEvent(raw_data="done", event="done")
24. SSE, WebSockets or a plain StreamingResponse: how do you choose?
SSE is one-way server-to-client over ordinary HTTP, has a reconnect model built into browsers (EventSource and the Last-Event-ID header), and passes through most proxies, which makes it the default for token streaming. WebSockets are bidirectional and suit voice or collaborative sessions where the client sends data mid-stream, at the cost of more connection management. A plain StreamingResponse of text or NDJSON is fine for server-to-server consumers that don't need SSE framing.
25. The stream works locally but arrives all at once in production. What do you check?
Buffering in a proxy. FastAPI's SSE support sets Cache-Control: no-cache and X-Accel-Buffering: no (the latter prevents buffering in proxies such as Nginx), and sends a keep-alive ping comment every 15 seconds when no message has been sent. If you built streaming by hand with StreamingResponse, you have to add these yourself. Then check every hop: CDN, ingress, API gateway and load balancer settings, plus any compression middleware that waits for a full buffer.
26. Long answers get cut off after about a minute behind an AWS Application Load Balancer. Why?
The ALB connection idle timeout defaults to 60 seconds and closes connections with no data sent or received in that window. A model that thinks for a long time before emitting the first token can trip it. Options: the SSE keep-alive comment (sent every 15 seconds by FastAPI's implementation) keeps bytes flowing; raise idle_timeout.timeout_seconds (valid range 1 to 4000); and AWS recommends the application's own keep-alive timeout be larger than the load balancer's to avoid 502s.
27. How do you resume a dropped SSE stream?
Give each event an id. On reconnect the browser sends the last received id in the Last-Event-ID header, which you read as a header parameter and use to skip already-delivered events. For LLM output that means buffering generated chunks server-side (for example in Redis keyed by a response ID) for a short time; you cannot ask the model to regenerate the identical continuation.
28. The model provider errors halfway through a stream. What does the client see?
The HTTP status (200) and headers have already been sent, so you cannot change the status code. Send an explicit error event (event: error with a safe message and a correlation ID), then end the stream. Clients must treat "stream ended without a done event" as failure too, because a network drop looks the same as a clean close.
Authentication and authorization
29. What does OAuth2PasswordBearer(tokenUrl="token") do, and what doesn't it do?
It is a dependency that reads the bearer token from the Authorization header and documents the flow in OpenAPI; tokenUrl tells the docs UI where to get a token. It does not validate the token. Your get_current_user dependency must decode and verify it, and raise a 401 with a WWW-Authenticate: Bearer header when verification fails, as the FastAPI tutorial shows.
30. Walk through the JWT checks in the FastAPI security tutorial.
The tutorial uses PyJWT: jwt.encode(...) with HS256 and an exp claim, and jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]), catching InvalidTokenError. Passing an explicit algorithms list is what stops a token from choosing its own algorithm. The sub claim should be a string that is unique across the whole application (the docs suggest a prefix such as username:johndoe). Passwords are hashed with pwdlib's recommended Argon2 hasher; passlib is mentioned only for verifying legacy hashes. RSA or ECDSA signatures need pyjwt[crypto].
31. Tokens come from Microsoft Entra ID or Amazon Cognito, not from your app. What changes?
You no longer hold a shared secret. You verify the signature against the identity provider's published signing keys (JWKS), and check iss (the expected issuer), aud (that the token was issued for your API, not some other app), exp, and any scope or role claims. Cache the keys and refresh on an unknown key ID rather than fetching per request. Skipping the audience check is the classic bug: a valid token for a different application would be accepted.
32. How do scopes work in FastAPI, and what status code should a missing scope return?
Declare scopes on OAuth2PasswordBearer(scopes={...}), require them with Security(get_current_user, scopes=["items"]) (Security is a subclass of Depends with a scopes parameter), and read the combined requirement in the dependency through SecurityScopes (.scopes and .scope_str). The FastAPI tutorial raises 401 for missing scopes. Be ready to discuss the alternative: RFC 6750 defines error="insufficient_scope" with HTTP 403, and the MCP authorization specification uses 403 plus a scope parameter for exactly this case. Either is defensible if documented; 403 tells clients that re-authenticating with the same scopes will not help.
33. Why does the tutorial's login check a dummy hash when the username doesn't exist?
Timing. If unknown usernames returned instantly while known ones paid for an Argon2 verification, response time would reveal which usernames exist. Verifying against a dummy hash makes both paths take similar time.
Rate limiting and cost control
34. Does FastAPI include a rate limiter? How would you add one?
The FastAPI documentation does not describe a built-in rate limiter. Common patterns: enforce coarse limits at the edge (API gateway, WAF or ingress), and enforce per-user or per-tenant limits in a dependency backed by a shared store such as Redis, because in-memory counters are per process and per replica. Return 429 with a Retry-After header so well-behaved clients back off.
35. Request-count limits aren't enough for an LLM API. Why, and what do you add?
Requests vary hugely in cost: one request with a 100-page context costs more than hundreds of short ones. Add token budgets (estimated input tokens before the call, actual usage from the provider's response metadata after it), per-tenant daily or monthly ceilings, and a maximum output token setting on every call. Record usage per request so finance and the customer can see where the spend went.
Error handling
36. HTTPException versus a custom exception handler: when do you use each?
Raise HTTPException(status_code, detail, headers) for expected request-level failures; FastAPI's version accepts any JSON-serialisable detail, while Starlette's accepts only strings. Register handlers with @app.exception_handler(SomeError) to translate domain exceptions (for example ProviderThrottled) into consistent responses in one place. The docs advise registering your HTTP handler for Starlette's HTTPException so it also catches exceptions raised inside Starlette itself.
37. What status does FastAPI return for request validation errors, and what is the risk in customising it?
FastAPI's default response for request validation failure is 422, with a detail list of loc, msg and type entries; you can override it with a handler for RequestValidationError. The docs warn that the error object can contain file names and line numbers, so dumping it into the response can leak information about your system.
38. How should an API map upstream LLM failures to its own responses?
Decide this deliberately and document it. A typical mapping: provider throttling becomes 429 or 503 with Retry-After; a timeout against your own deadline becomes 504; a provider validation error caused by your request (context too long) becomes a 4xx you can explain; anything unexpected becomes 500 with a correlation ID and no internal detail. Never forward raw provider error bodies, which may echo prompt content.
Calling LLM APIs safely
39. Which failures should you retry when calling a model, and how?
Retry throttling, transient 5xx and connection errors, with exponential backoff and jitter and a cap on total attempts and total time. Don't retry validation errors, auth failures or content-policy blocks: they will fail the same way. Know your SDK's built-in behaviour so you don't stack retries. For example, boto3's default "standard" retry mode makes 3 total attempts; if your code wraps that in 3 attempts and the client retries 3 more times, one user click can become 27 calls.
40. A POST /tickets endpoint lets an agent create service-desk tickets. The client times out and retries. How do you avoid duplicate tickets?
Make the operation idempotent. A common pattern is an Idempotency-Key request header: store the key with the request fingerprint and the result; if the same key arrives again, return the stored result instead of creating a second ticket. Expire keys after a sensible window and reject a reused key with a different payload. The same thinking applies to any tool call with side effects that an agent might repeat.
41. Where do LLM API keys live in a FastAPI service?
Not in code, images or .env files committed to git. Load them at startup from the platform's secret store (for example AWS Secrets Manager injected by the container platform, or a cloud workload identity so no static key exists at all). Read settings once in lifespan or a cached settings dependency. Make sure request logging and exception handlers never print headers or the settings object.
42. What input checks belong at the API layer for a RAG chat endpoint?
Size limits on the question and history, extra="forbid" on the body, an allow-list for any client-selectable option (which knowledge base, which model tier), tenant and document-level authorization before retrieval, and a cap on conversation length. Prompt-injection defences live deeper in the pipeline, but the API layer is where you stop a caller from selecting a knowledge base they aren't entitled to.
Testing
43. How do you test endpoints that depend on lifespan setup?
Use with TestClient(app) as client:. Entering the block runs the lifespan startup code and leaving it runs shutdown. A bare TestClient(app) outside a with block does not run lifespan, which is a common source of "works in production, AttributeError in tests".
44. How do you write async tests?
The FastAPI docs use HTTPX directly: AsyncClient(transport=ASGITransport(app=app), base_url="http://test") inside an async def test marked @pytest.mark.anyio. AsyncClient does not trigger lifespan events; the docs point to LifespanManager from asgi-lifespan for that. If you see "Task attached to a different loop", create loop-bound objects inside async functions rather than at module level.
import pytest
from httpx import ASGITransport, AsyncClient
from app.main import app
from app.deps import get_llm
class FakeLLM:
async def complete(self, prompt: str) -> str:
return '{"category": "network", "priority": 2, "summary": "VPN down"}'
@pytest.mark.anyio
async def test_triage_returns_valid_model():
app.dependency_overrides[get_llm] = lambda: FakeLLM()
try:
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
r = await ac.post("/triage", json={"text": "VPN is down for the Pune office"})
assert r.status_code == 200
assert r.json()["priority"] == 2
finally:
app.dependency_overrides = {}
45. What would you test for an LLM endpoint besides the happy path?
Validation failures (oversized input, extra fields), auth failures (no token, wrong audience, missing scope), the fake LLM returning malformed JSON, the fake LLM timing out, provider throttling mapped to the right status, the streaming endpoint emitting an error event mid-stream, and idempotent replays. Keep a small, separate evaluation suite for answer quality; unit tests check the plumbing, not whether the answer is good.
Deployment
46. fastapi run, uvicorn --workers, Gunicorn: what do the current docs recommend?
The FastAPI deployment docs show fastapi run --workers 4 main.py or uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4, where Uvicorn itself manages the worker processes. The old tiangolo/uvicorn-gunicorn-fastapi image is marked deprecated. Gunicorn is not needed for multiple workers in the current guidance.
47. Should a container on Kubernetes or ECS run multiple Uvicorn workers?
Usually not. The docs say that with a cluster orchestrator you probably want a single Uvicorn process per container and handle replication at the cluster level. Scaling then means more tasks or pods, health checks see each process directly, and memory per container is predictable. Multiple workers in one container make sense for a single server or Docker Compose setup.
48. What matters in a FastAPI Dockerfile?
Copy requirements.txt and install dependencies before copying the application code so the dependency layer stays cached. Use the exec form of CMD (CMD ["fastapi", "run", "app/main.py", "--port", "80"]); the docs say this ensures FastAPI can shut down gracefully and lifespan events are triggered. Behind a TLS-terminating load balancer, add --proxy-headers so the app trusts the forwarded scheme and generates correct URLs.
49. What should the health check endpoint do?
Return quickly and check only what the process needs to serve traffic: the app is up, settings loaded, perhaps a cheap check that required clients were created. Don't call the LLM or run a vector search in the load balancer health check; a provider slowdown would then mark every replica unhealthy and take the whole service down. Put deeper dependency checks on a separate diagnostics endpoint or in synthetic monitoring.
Scenario and troubleshooting questions
50. p99 latency for every user jumps whenever one customer uploads a large PDF. Where do you look?
At CPU-bound work on the event loop. PDF parsing or chunking inside an async def handler blocks every other request on that worker until it finishes. Move parsing to a worker service (question 21), or at minimum to a process pool; a thread pool helps with blocking I/O but CPU-heavy pure-Python work still contends for the interpreter. Confirm with per-endpoint latency metrics and a profile before changing code.
51. After moving from one worker to four in the same container, the service is OOM-killed. Why?
Each worker is a separate process with its own copy of everything loaded at startup: a local embedding model, a reranker, large in-memory caches. Four workers means roughly four times that memory. Either load heavy models in a separate inference service, reduce per-process state, or follow the one-process-per-container pattern and scale by task count.
52. The OpenAPI docs page and redirects use http:// URLs even though users reach the API over HTTPS. What's wrong?
TLS ends at the load balancer, and the app sees plain HTTP. Without --proxy-headers (and an appropriate forwarded-allow-ips setting in Uvicorn), the app ignores X-Forwarded-Proto and builds http:// URLs and redirects. Trust forwarded headers only from the proxy's addresses, not from anyone.
How to prepare
Build one small service end to end: a FastAPI RAG or triage endpoint with Pydantic models, a JWT dependency, an SSE streaming route, a fake-LLM test suite and a Dockerfile. Then deploy it somewhere real, because half the questions above are about what breaks between your laptop and a load balancer. Our step-by-step ECS Fargate deployment tutorial walks through that last part on AWS, and containerising LLM apps the right way covers the image itself. For the wider interview loop, pair this page with the 150 FDE interview scenarios and the LLM inference and serving questions, and if agents are on the job description, the AI agent developer question set.
Practise this at Cloud Soft Solutions
Cloud Soft Solutions runs the AI, GenAI and Agentic AI training programme in our Ameerpet, Hyderabad classroom and online. The labs include building FastAPI services for LLM and RAG workloads, streaming responses, testing with fake model clients and deploying containers to the cloud, so you can practise the patterns in this guide on real code with a trainer reviewing your work.
Sources
- FastAPI: Request Body, checked 5 December 2026
- FastAPI: Response Model, checked 5 December 2026
- FastAPI: Concurrency and async / await, checked 5 December 2026
- FastAPI: Lifespan Events, checked 5 December 2026
- FastAPI: Sub-dependencies, checked 5 December 2026
- FastAPI: Dependencies with yield, checked 5 December 2026
- FastAPI: Testing Dependencies with Overrides, checked 5 December 2026
- FastAPI: Background Tasks, checked 5 December 2026
- FastAPI: Server-Sent Events (SSE), checked 5 December 2026
- FastAPI: OAuth2 with Password (and hashing), Bearer with JWT tokens, checked 5 December 2026
- FastAPI: OAuth2 scopes, checked 5 December 2026
- FastAPI: Handling Errors, checked 5 December 2026
- FastAPI: Testing Events (lifespan), checked 5 December 2026
- FastAPI: Async Tests, checked 5 December 2026
- FastAPI: Server Workers, checked 5 December 2026
- FastAPI in Containers: Docker, checked 5 December 2026
- Starlette: Requests, checked 5 December 2026
- Pydantic: Validators, checked 5 December 2026
- Pydantic: Models, checked 5 December 2026
- Pydantic: Migration Guide, checked 5 December 2026
- Python: Coroutines and Tasks (asyncio), checked 5 December 2026
- Boto3: Retries, checked 5 December 2026
- Application Load Balancer attributes (idle timeout), checked 5 December 2026
- MCP specification 2026-07-28: Authorization (insufficient_scope handling), checked 5 December 2026
📞 Call +91 96660 19191 · +91 99496 16388 · WhatsApp
Cloud Soft Solutions, 513, 5th Floor, Aditya Enclave, Nilagiri Block, beside Ameerpet Metro Station, Ameerpet, Hyderabad 500016, Telangana, India
Frequently Asked Questions
How do you stream LLM tokens with FastAPI?
FastAPI 0.135.0 added Server-Sent Events support. Set response_class=EventSourceResponse from fastapi.sse and yield items or ServerSentEvent objects from an async generator. FastAPI sends a keep-alive ping comment every 15 seconds when idle and sets headers that prevent caching and proxy buffering.
Should FastAPI run multiple Uvicorn workers inside a container?
The FastAPI deployment docs say that on Kubernetes or similar orchestrators you probably want a single Uvicorn process per container and handle replication at the cluster level. Multiple workers (fastapi run --workers or uvicorn --workers) suit a single server or Docker Compose setup.
What is the difference between def and async def endpoints in FastAPI?
A path operation declared with def runs in an external threadpool that is then awaited; an async def function runs on the event loop. Blocking I/O inside async def blocks other requests on that worker, so use def, asyncio.to_thread or an async client for blocking SDKs.
When does cleanup code in a FastAPI dependency with yield run?
By default (scope request) the code after yield runs after the response is sent. With Depends(..., scope="function") it runs after the path operation returns but before the response is sent.
What status code does FastAPI return for request validation errors?
FastAPI returns 422 by default with a detail list of loc, msg and type entries. You can override this with an exception handler for RequestValidationError, taking care not to leak internal details.
Is BackgroundTasks suitable for heavy jobs like re-embedding thousands of documents?
No. Background tasks run in the same process after the response is sent. The FastAPI docs recommend a dedicated tool such as Celery with a broker for heavy computation; BackgroundTasks suits small follow-up work.



