← Back to FastAPI, page 4

fastapi-0065 · Easy fresher

What is ASGI, how do Starlette and FastAPI relate to it, and what does an ASGI application look like?

ASGI (Asynchronous Server Gateway Interface) is the standard between Python async web servers (Uvicorn, Hypercorn, Daphne) and applications. An ASGI app is an async callable app(scope, receive, send): the server passes a dict describing the connection and two awaitable channels for messages. Starlette is a toolkit that implements routing, requests, responses, middleware and WebSockets on ASGI, and FastAPI subclasses Starlette to add typed parameters, validation, dependency injection and OpenAPI.

Full answer

WSGI (Flask, classic Django) handles one request per call synchronously and has no WebSocket support. ASGI is its async successor: it supports concurrent requests, WebSockets, long-lived connections, and server-sent events.

The contract:

python
async def app(scope, receive, send):
    # scope: {"type": "http", "method": "GET", "path": "/", "headers": [...], ...}
    await send({"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")]})
    await send({"type": "http.response.body", "body": b"hello"})
  • scope["type"] is "http", "websocket" or "lifespan" (start-up and shutdown events).
  • receive() yields incoming messages (http.request with body chunks, websocket.receive, http.disconnect).
  • send(message) writes response messages.

Layers:

  1. Server: Uvicorn parses HTTP, manages sockets, and calls the app. (Gunicorn can run Uvicorn workers.)
  2. Middleware: wrappers that take an ASGI app and return an ASGI app (CORS, GZip, sessions). Starlette's BaseHTTPMiddleware is a convenience; pure ASGI middleware is faster and more flexible.
  3. Starlette: Request, Response, Router, Mount, WebSocket, StaticFiles, BackgroundTask, lifespan handling.
  4. FastAPI: builds Starlette routes from typed functions, validates with Pydantic, resolves Depends, and generates OpenAPI.

Implications: a FastAPI() instance is itself an ASGI app, so it can be mounted inside another app, wrapped by middleware or called directly in tests; sync def endpoints run in a thread pool, async def endpoints run on the event loop; and anything blocking inside async def stalls all requests on that worker.

python
import asyncio

from fastapi import FastAPI


async def raw_asgi_app(scope, receive, send):
    assert scope["type"] == "http"
    await send({"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")]})
    await send({"type": "http.response.body", "body": b"hello from a raw ASGI app"})


app = FastAPI()


@app.get("/students")
def students():
    return ["Asha"]


async def call(asgi_app, path):
    scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http",
             "path": path, "raw_path": path.encode(), "query_string": b"", "headers": [], "server": ("testserver", 80),
             "client": ("127.0.0.1", 1234), "root_path": ""}
    sent = []

    async def receive():
        return {"type": "http.request", "body": b"", "more_body": False}

    async def send(message):
        sent.append(message)

    await asyncio.wait_for(asgi_app(scope, receive, send), timeout=5)
    start = sent[0]
    body = b"".join(m.get("body", b"") for m in sent[1:])
    return start["status"], body


print(asyncio.run(call(raw_asgi_app, "/")))
print(asyncio.run(call(app, "/students")))         # FastAPI is itself an ASGI callable
print(asyncio.run(call(app, "/nope")))

from starlette.routing import Mount
app.router.routes.append(Mount("/legacy", app=raw_asgi_app))   # mount a raw ASGI app inside FastAPI
print(asyncio.run(call(app, "/legacy/")))

Standalone script. Run it with `python file.py`; it calls the ASGI apps directly with a hand-built scope, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): (200, b'hello from a raw ASGI app') (200, b'["Asha"]') (404, b'{"detail":"Not Found"}') (200, b'hello from a raw ASGI app')

Key points

  • ASGI is the async server-application interface: app(scope, receive, send)
  • Scope types: http, websocket, lifespan
  • Starlette provides the toolkit; FastAPI adds typing, validation, DI and OpenAPI
  • A FastAPI app is an ASGI callable and can be wrapped or mounted
  • Blocking inside async def stalls the event loop

Common mistakes

  • Confusing WSGI and ASGI servers
  • Running blocking code inside async def and freezing the event loop
  • Thinking FastAPI replaces the server: Uvicorn or similar is still required
  • Using BaseHTTPMiddleware for performance-critical paths without considering pure ASGI

Follow-ups

  • What is the lifespan scope for?
  • How does Uvicorn differ from Gunicorn?
  • What are the downsides of BaseHTTPMiddleware?

Tips

  • Write the three-argument signature
  • Describe the layers
  • Say what blocking does