FastAPI interview question · Most asked
What is ASGI and how does it differ from WSGI?
Summary
WSGI is the synchronous Python interface between servers and apps (one request per call). ASGI is its async successor, supporting async request handling, WebSockets, HTTP/2 and long-lived connections.
Longer Answer
A WSGI app is a callable app(environ, start_response) that blocks a worker thread per request. An ASGI app is async def app(scope, receive, send), so one event loop can multiplex thousands of concurrent connections. FastAPI/Starlette are ASGI apps served by Uvicorn, Hypercorn or Granian.
Key Points
- WSGI: sync, request/response only
- ASGI: async, WebSockets, lifespan events
- Servers: Uvicorn, Hypercorn, Granian
- ASGI apps can still run sync code in a threadpool
Deep dive: Request Lifecycle course: WSGI, ASGI and the Event Loop
More most-asked FastAPI questions
- How do `yield` dependencies work and why are they used for database sessions?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- How does dependency injection with `Depends` work in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?