What is ASGI?
ASGI (Asynchronous Server Gateway Interface) is a specification for Python asynchronous web servers and applications. It extends WSGI to support async, WebSockets, and long-lived connections.
// Table of Contents
Definition
ASGI (Asynchronous Server Gateway Interface) is the spiritual successor to WSGI, designed to handle asynchronous Python web applications. It provides a standard interface between async web servers and Python frameworks.
ASGI supports HTTP, WebSockets, and other protocols through a single interface. It enables frameworks like FastAPI and Starlette to handle thousands of concurrent connections efficiently.
How ASGI Works
An ASGI application is a callable that takes three arguments:
- scope: A dictionary containing connection information (type, path, headers).
- receive: An async callable to receive incoming messages.
- send: An async callable to send outgoing messages.
Unlike WSGI's synchronous request-response model, ASGI's message-based design supports long-lived connections, streaming, and bidirectional communication.
ASGI Servers
Popular ASGI servers include:
- Uvicorn: Lightning-fast ASGI server built on uvloop and httptools. The most popular choice for FastAPI.
- Hypercorn: ASGI server supporting HTTP/1, HTTP/2, and HTTP/3.
- Daphne: Reference ASGI server, developed as part of the Django Channels project.
- Granian: A Rust-based ASGI server with excellent performance.
Code Example
# Raw ASGI application
async def app(scope, receive, send):
if 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 ASGI!',
})
# In practice, use a framework like FastAPI
# Run with: uvicorn main:app --host 0.0.0.0 --port 8000
Frequently Asked Questions
What is the difference between ASGI and WSGI?
WSGI is synchronous - it handles one request at a time per worker. ASGI is asynchronous - it can handle many concurrent connections with a single worker. ASGI also supports WebSockets and long-lived connections, which WSGI cannot. ASGI is the modern standard for new Python web applications.
Need expert backend development?
I build scalable Python APIs and backend systems. Let's discuss your project.
Get in Touch