Add Webhooks
Starting with version 3.1 OpenAPI supports Webhooks, which are incoming HTTP requests that are in response to events. The
new Webhooks feature is described very similarly to the existing Callbacks functionality. The new webhooks
keyword is a
top-level element, alongside paths
. There are also changes to the required fields: OpenAPI 3.0 required openapi
and info
and paths but in OpenAPI 3.1 only openapi
and info
are always required, but the document must also contain at least one of paths
or webhooks
or components
.
This is allows API descriptions to contain only outgoing API calls, only incoming webhooks, only components that might be referred to by other documents,
or any combination or all of these and still be valid in its own right.
Speakeasy supports generating types for webhooks by supporting the webhook
key word natively during SDK creation. For each defined webhook
in your OpenAPI spec, Speakeasy will generate the types for your webhook’s request, and response objects.
This ensures that whatever the endpoint type, your users have a consistent experience interfacing with your API and you can publish a single package for
your users to consume.
Here is an example for a webhook request posted from a system when a new pet is registered at the Petshop.
OpenAPI
webhooks:
newPet:
post:
operationId: newPetEvent
requestBody:
description: Information about a new pet in the system
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
responses:
"200":
description: Return a 200 status
Here is an example of the generated types for Golang, but the same applies for all other supported languages.
SDK Output
package webhooks
import (
"openapi/pkg/models/shared"
)
type NewPetRequest struct {
Request *shared.Pet `request:"mediaType=application/json"`
}
type NewPetResponse struct {
ContentType string
StatusCode int64
}
Within the webhooks section, each incoming webhook request has an operationId
(such as newPetEvent
in the example above). You don’t need to specify the URL path that the webhook will come in on (often the user can nominate that anyway), just explain what will arrive and your users will get a type to manage it in code.
As of 3.1 PathItem
is now allowed in the components section and you can $ref to a pathItem
from either a path, callback or a webhook.
In the future we are looking to support native serialisation and deserialisation methods for webhook types.