ðĄ Generate from AsyncAPI¶
Generate Python models from AsyncAPI 2.x and 3.x documents.
Experimental
AsyncAPI input support is experimental and may change as real-world usage is validated.
ð Quick Start¶
datamodel-codegen \
--input asyncapi.yaml \
--input-file-type asyncapi \
--output-model-type pydantic_v2.BaseModel \
--output model.py
ð Example¶
asyncapi.yaml
asyncapi: 3.0.0
info:
title: User events
version: 1.0.0
channels:
userSignedUp:
messages:
userSignedUp:
payload:
$ref: '#/components/schemas/UserSignedUp'
components:
schemas:
UserSignedUp:
type: object
required:
- id
- email
properties:
id:
type: string
email:
type: string
format: email
âĻ Generated model.py
from __future__ import annotations
from pydantic import BaseModel, EmailStr
class UserSignedUp(BaseModel):
id: str
email: EmailStr
Supported AsyncAPI Versions¶
The AsyncAPI parser supports documents with asyncapi versions in the 2.x and 3.x families.
| Version | Schema behavior |
|---|---|
| 2.x | Message schemaFormat is applied to the message payload. AsyncAPI Schema Objects are handled with OpenAPI 3.0-compatible schema features. |
| 3.x | payload, headers, and components.schemas may be AsyncAPI Schema Objects, Reference Objects, or Multi Format Schema Objects. AsyncAPI Schema Objects are handled with OpenAPI 3.1-compatible schema features. |
Use --schema-version auto to detect the version from the asyncapi field, or pass
--schema-version 2.0 / --schema-version 3.0 to select a version explicitly.
Model Generation Scope¶
--openapi-scopes does not select what AsyncAPI input generates: the parser generates models from every location listed below. The api scope is available for OpenAPI input only, and AsyncAPI input with api stops with an error.
datamodel-code-generator generates data models from schema-bearing fields. It does not generate servers, protocol adapters, or runtime message validators; it generates a client for the WebSocket channels of ws and wss servers and the server-sent event channels of http, https and sse servers (see Generate a client).
The AsyncAPI parser extracts schemas from:
| AsyncAPI location | Generated models |
|---|---|
components.schemas |
Reusable schema models |
components.messages[*].payload and headers |
Reusable message payload/header models |
components.messages[*].bindings |
Binding schemas for schema-bearing binding fields such as Kafka key and HTTP headers |
channels[*].publish.message, subscribe.message, and messages[*] |
Channel message payload/header models |
channels[*].parameters[*].schema and components.parameters[*].schema |
Channel parameter schema models |
channels[*].bindings and components.channels[*].bindings |
Binding schemas for schema-bearing binding fields such as WebSockets query/headers |
operations[*].messages and operations[*].reply.messages |
Operation request/reply message payload/header models |
components.operations[*].messages and reply.messages |
Reusable operation message payload/header models |
operations[*].bindings and components.operations[*].bindings |
Binding schemas for schema-bearing binding fields such as HTTP query and Kafka groupId/clientId |
components.replies[*].messages |
Reusable reply message payload/header models |
message.traits[*].headers and components.messageTraits[*].headers |
Header models when the message itself does not define headers |
message.traits[*].bindings and components.messageTraits[*].bindings |
Binding schemas supplied by message traits |
operation.traits[*].bindings and components.operationTraits[*].bindings |
Binding schemas supplied by operation traits |
| Local and external Reference Objects | Resolved before model generation |
Protocol binding configuration is treated as transport metadata unless the AsyncAPI binding
specification defines the field as a Schema Object or Reference Object. The parser currently
generates models for the schema-bearing binding fields used by the official bindings, including
headers, query, key, groupId, and clientId.
Schema Formats¶
AsyncAPI 3.x Multi Format Schema Objects are unwrapped through schemaFormat before model generation. A $ref that names one holding JSON Schema in components.schemas (from a message payload or headers, or a component schema that is a $ref) is read as a $ref to the schema it holds, so it keeps its own class.
AsyncAPI 2.x message-level schemaFormat is applied to the message payload.
Supported embedded schema formats are:
schemaFormat family |
Behavior |
|---|---|
application/vnd.aai.asyncapi... or omitted |
Parsed as an AsyncAPI Schema Object |
application/schema / application/schema+json / application/schema+yaml |
Parsed with the JSON Schema/OpenAPI schema stack |
application/vnd.oai.openapi... |
Parsed with the OpenAPI schema stack |
application/vnd.apache.avro... |
Converted with the Avro parser, then generated as Python models |
application/vnd.google.protobuf |
Converted with the Protocol Buffers parser, then generated as Python models |
application/xml, text/xml, application/xsd+xml, application/xml+schema, application/xml-schema |
Converted with the XML Schema parser, then generated as Python models |
RAML and custom embedded schemaFormat values inside an AsyncAPI document are rejected with an explicit error instead of producing partial or misleading models.
Embedded Protocol Buffers schemas support inline .proto source strings and local imports resolved relative to the AsyncAPI document. Embedded XML Schema supports inline XSD strings and local xs:include / xs:import / xs:redefine / xs:override locations resolved relative to the AsyncAPI document.
Limitations¶
The AsyncAPI input type is for model generation from message payloads, headers, and reusable schemas. It does not:
- validate complete AsyncAPI documents;
- apply protocol binding runtime semantics;
- generate producer/consumer code;
- enforce runtime message validation;
- merge multiple traits that define the same
headersproperty.
ð See Also¶
- ðĨïļ CLI Reference - Complete CLI options reference
- ð Generate from JSON Schema - JSON Schema input documentation
- ð Generate from OpenAPI - OpenAPI schema behavior
- ðŠķ Generate from Apache Avro Schema - Avro schema input documentation
Generate a client¶
Experimental
Client generation from AsyncAPI documents is experimental (behavior.asyncapi-client); the channels it opens and
the generated package may change.
--generate-client httpx2 with --input-file-type asyncapi generates the models and an HTTPX2 client package whose
attributes open the WebSocket and server-sent event channels of the document, sync and asyncio. The channels are
read by the AsyncAPI version the models are read by: --schema-version 2.0 or 3.0 where it is given, else the
document's asyncapi field.
datamodel-codegen --input market.yaml --input-file-type asyncapi --output models.py \
--generate-client httpx2 --client-output client --client-package client --client-model-package models
from client import Client
from models import Subscribe
with Client() as client, client.market.connect(pair="XBT-USD") as session:
session.send(Subscribe(event="subscribe", channels=["trades"]))
for message in session:
print(message.data)
- Each channel of AsyncAPI 2.x or 3.x that a
wsorwssserver serves becomesclient.<channel>, named after the words of its id (AsyncAPI 3) or its address (AsyncAPI 2). Itsconnect(...)takes the parameters of the address as keyword arguments and returns the session of a WebSocket helper: it sends the channel's handshake, a GET of its address on its servers (withwssandwssent ashttpsandhttp), through the client's call path, and sends and receives typed messages until the block ends. An address is a path under the server URL, with or without its leading/. The channels of a document that declares no servers are opened at--client-default-base-url, which they need as OpenAPI operations without servers do, or at thebase_urlthe client is given. - Channels at one address on the same servers (in any order; a channel that lists none is served on all of them) are
one connection: one attribute, named after the words of the address (
rootfor/), whoseconnect(...)opens the handshake of the first of them and sends and receives the messages of them all, told apart as the messages of one channel are. Their handshakes must take the same parameters, in any order and of the same model types, offer the same subprotocols and need the same security (adescriptionmay differ), or the connection is left out.--client-operationskeys it by the reference of its first channel. - The messages of an AsyncAPI 3 operation's
replygo the other way on the operation's connection: the client receives the replies to what it sends, or sends those to what it receives, among the other messages, and no request is correlated with its reply. A reply lists its messages, else carries every message of its channel, which is the channel it names, else the operation's own. A reply on a channel at another address or on other servers, or sent to an address that a runtime expression gives (reply.address), leaves the connection out. - The models are the only codec, as for an OpenAPI body of the message's media type: a JSON message is encoded and
decoded by its payload's model, a payload that is a
$refbeside annotations only (such as adescription) by the model of the schema it names, as an OpenAPI body is; a payload the models type as raw bytes (a binary string), and any payload of another binary media type such asapplication/octet-stream,image/pngorapplication/x-msgpack, asbytes; a text message (text/plain,text/csv, ...) whose models type a string, an enum of strings among them, asstr, as is anapplication/octet-streammessage whose models type an enum of strings. A text message of another type, and a form or multipart message whose payload is not a binary string, leave the channel out. A direction that carries no message is typedNever. - The messages of a channel are those the models are generated for: a message value stands for each message its
$refandoneOflead to, at any depth. A direction of several messages is typed as the union of their types. A received binary frame is the bytes message and a text frame the text or JSON message; several JSON messages are told apart by a tag, a property that every payload model declares as required with one string value of its own (aconstor a one-valueenum), when no payload admits null, and a message with an unknown or missing tag raisesDecodeErrorand closes the connection with 1002.send(value)takes the message of the value's class, else of its nearest base class, astrthe text message andbytesthe binary one; TypedDict values take the message whose tag they hold. Pydantic models decode received JSON messages without a tag, and encode sent ones that are not all classes, as the union of their types; for the other model types such a channel is left out with a warning, as is a channel whose client receives both text and JSON messages. - The properties of the channel's WebSocket binding
queryandheadersobjects are query and header parameters ofconnect(...): the fields of the model generated for each object (its own properties and those it inherits, as throughallOfor a$ref), typed and required as the model types and requires them, as OpenAPI query and header parameters are, with thedefaultanddescriptiontheir schema gives, through its$ref. An object the models hold as a mapping gives no parameter. A binding that opens the channel with another method than GET, or whosequeryorheadersschema the models type as something else than an object, such as a string, leaves the channel out. - A
Sec-WebSocket-Protocolheader whose type admits fixed values alone (aconst, anenum, or aoneOfofconsts, as the models type them, also through a root model or alias of a union of them), each a token, offers them as the subprotocols of the handshake, in order; the server selects one. Any other header the handshake writes itself (Sec-WebSocket-Protocolwithout such values,Connection,Upgrade,Host,Sec-WebSocket-Key,Sec-WebSocket-Version,Sec-WebSocket-Extensions, ...) is not sent where it is optional, and leaves the channel out where it is required. - The security of the channel's servers and of each operation on it is sent on the handshake with the credentials the
client is given, as the security of an OpenAPI operation is:
httpApiKeyin the query, a header or a cookie,httpbearer and basic,oauth2andopenIdConnecttokens. The handshake needs one alternative of each server's and each operation's security. An alternative that needs a scheme a handshake cannot send, such asuserPassword, is left out, as is one that needs a scheme ofcomponents/securitySchemesthat references another document, or an AsyncAPI 3 scheme written inline in asecuritylist, and a channel with none left is too, as is a channel whose servers require different security (the same alternatives in any order are the same security). A header parameter takes the place of the credential sent in the header it names: an API key's header, orAuthorizationforhttp,oauth2andopenIdConnectcredentials. A call that gives it sends its value, and one that leaves it out sends the credential. - A server's URL variables are substituted by their
default; a channel served on a server whose URL has a variable without one is left out. Variables the URL does not name need none. - A server's URL is its AsyncAPI 2
url, or its AsyncAPI 3hostandpathname. The client reaches it with TLS when either the scheme the URL is written with or the server's protocol iswssorhttps, and without TLS only when one of them iswsorhttpand neither says TLS, so neither downgrades the other. A URL written without a scheme on ansseserver is reached with TLS. A variable the URL starts with gives the URL's scheme when its default is written with one, such ashttp://localhost:8090, as does a variable that is the scheme itself, such as{protocol}://. - A channel is a server-sent event channel when it carries a
text/event-streammessage, by its owncontentTypeor a trait's. A channel that nowsorwssserver serves is one as well when ansseserver serves it, or when the HTTP binding of the channel or of an operation on it fixes theAcceptorContent-Typeheader totext/event-stream(its type admits that one value alone, such as aconst). An operation's HTTP binding may come from one of its traits, which gives it as the document's version merges traits. A server-sent event channel is served on thehttp,httpsandsseservers that serve it; the others are WebSocket channels, so a channel that lists no servers in a document withwsandsseservers is a WebSocket channel. Itsopen(...)returns the event stream of an SSE helper, aswith client.prices.open(symbol="XBT") as stream:orasync with awaitonAsyncClient: it sends a GET of the channel's address, with the parameters of its address, the properties of thequeryandheadersof the HTTP bindings of the channel and of its AsyncAPI 3 operations as query and header parameters (anAcceptorContent-Typeheader is not sent), and its security, and yields each event, whose data the payload's model decodes from JSON, until the stream ends; it does not reconnect. Several messages are told apart by their tag, or decoded as one union by Pydantic models, as a WebSocket's received messages are, and an event that does not decode raisesDecodeError. A stream flows from the server only, so the client receives every message of the channel, whatever its operations'actionand--client-asyncapi-perspectivesay. A channel with a message that is neithertext/event-streamnor JSON, or that its HTTP binding opens with another method than GET, is left out with a warning, as is one whose HTTP bindings declare a query or header parameter differently, and one whosequeryorheadershas no model, as an AsyncAPI 2 operation's own HTTP binding (one a trait undercomponents/operationTraitsgives has one). --client-asyncapi-perspectivesays which side the document describes on a WebSocket channel:server(the default), whose sends the client receives, orclient. It does not apply to a server-sent event channel, whose messages the client always receives.--client-operationskeyed by a channel's reference, such as/channels/market, renames its attribute (resource, one identifier that no other channel takes) and its parameters (parameter_names);--client-protocolsis refused for AsyncAPI input.
A channel that uses a feature the client does not support is left out with a warning that names the feature, and the
other channels are generated; when every channel is left out, the generation fails with their findings. A channel is
also left out, with a warning that names what does not resolve, when an operation, a message or a trait it needs is
in another document, or its payload schema is in no loaded document (such as one --external-ref-mapping maps), or
with one that names the messages the models did not read (those of a channel in another document that no channel of
the document lists); an operation in another document may be on any channel, so it leaves every channel out.
Operation and message traits are merged first, as the document's AsyncAPI version merges them. AsyncAPI Client Features lists each
feature and the client's support.