eventsswaggermicroservicesevent-driven

How to define events in OpenAPI / Swagger spec?


How can an event-driven microservices architecture be defined using the OpenAPI / Swagger specification? For events, it is important to document the event payload passed among different services, even when they are not accessed via HTTP paths.

Everything I've seen is API-based via HTTP paths, so I'm wondering now to implement this with OpenAPI / Swagger spec?


Solution

  • OpenAPI 3.1

    OpenAPI Spec 3.1 supports events via the top level webhooks property. OpenAPI Spec 3.1 defines webhook support here:

    OpenAPI 3.0

    For tools that handle OAS 3.0, defining event bodies using schemas only is still useful as such definitions can be used by codegen tools like OpenAPI Generator to auto-generate schema objects for languages like Java, Swift, Go, etc.

    OpenAPI 2.0 / Swagger 2.0

    For Swagger Spec 2.0 (aka OpenAPI Spec 2.0), you can include definitions in the Swagger spec as mentioned by alamar. Swagger Codegen will automatically create model classes for these definitions, even if they are not associated with any paths. I build and maintain a Swagger Spec/Codegen-built SDK in Go for the RingCentral API that has events like this. You can see the auto-generated classes/structs Swagger Codegen builds in the following folder, filtering for the 20 files that end in _event.go. These are currently created using swagger-codegen 2.3.1.

    If you have multiple event types, having an event property that can distinguish message types you are receiving can help parse it into the correct event class/struct. In Go, you can unmarshal the data twice, once into a generic struct to peek at the event type property, and then a second time for the actual event type.

    I also maintain a collection of example events and parsing code in the Chathooks webhook reformatter project you can use for reference. You can see the example events and (hand-rolled) language definitions here:

    AsyncAPI

    An alternative to OpenAPI is to use AsyncAPI is a specification for event driven architectures. It is protocol agnostic so can be used with Kafka, Websocket, MQTT, AMQP and anything else based on messaging.