Asynchronous Server Gateway Interface (ASGI)

Sources:

title: ## Contents 
style: nestedList # TOC style (nestedList|inlineFirstLevel)
minLevel: 1 # Include headings from the specified level
maxLevel: 4 # Include headings up to the specified level
includeLinks: true # Make headings clickable
debugInConsole: false # Print debug info in Obsidian console

Overview

About

ASGI (Asynchronous Server Gateway Interface) is a successor to Web Server Gateway Interface (WSGI), intended to provide a standard interface between async-capable Python web servers, frameworks, and applications.

Where WSGI provided a standard for synchronous Python apps, ASGI provides one for both asynchronous and synchronous apps, with a WSGI backwards-compatibility implementation and multiple servers and application frameworks.

How does it work?

ASGI is structured as a single, asynchronous callable. It takes a scope, which is a dict containing details about the specific connection, send, an asynchronous callable, that lets the application send event messages to the client, and receive, an asynchronous callable which lets the application receive event messages from the client.

This not only allows multiple incoming events and outgoing events for each application, but also allows for a background coroutine so the application can do other things (such as listening for events on an external trigger, like a Redis queue).

In its simplest form, an application can be written as an asynchronous function, like this:

async def application(scope, receive, send):
    event = await receive()
    ...
    await send({"type": "websocket.send", ...})

Every event that you send or receive is a Python dict, with a predefined format. It’s these event formats that form the basis of the standard, and allow applications to be swappable between servers.

These events each have a defined type key, which can be used to infer the event’s structure. Here’s an example event that you might receive from receive with the body from a HTTP request:

{
    "type": "http.request",
    "body": b"Hello World",
    "more_body": False,
}

And here’s an example of an event you might pass to send to send an outgoing WebSocket message:

{
    "type": "websocket.send",
    "text": "Hello world!",
}

Specifications

NOTE

See Specifications — ASGI 3.0 documentation.

These are the specifications for ASGI. The root specification outlines how applications are structured and called, and the protocol specifications outline the events that can be sent and received for each protocol.

Implementations and Frameworks


Appendix

Note created on 2024-05-08 and last modified on 2024-05-08.

LIST FROM [[Asynchronous Server Gateway Interface (ASGI)]] AND -"CHANGELOG" AND -"04-RESOURCES/Definitions/Acronyms/Asynchronous Server Gateway Interface (ASGI)"

(c) No Clocks, LLC | 2024