Callbacks in OpenAPI — Defining Webhook and Async Patterns
In this tutorial, you will learn about Callbacks in OpenAPI. We cover key concepts, practical examples, and best practices to help you master this topic.
Callbacks in OpenAPI define outbound requests that the API makes to a URL provided by the client, enabling documentation of Webhooks, asynchronous notifications, and event-driven patterns.
What You'll Learn
You will learn how to define callbacks, reference runtime expressions for dynamic URLs, and document Webhook payloads and expected responses.
flowchart LR A[Client] --> B[POST /subscribe] B --> C[API Stores URL] D[Event Occurs] --> E[API Calls Callback] E --> F[Client Processes] A:::current classDef current fill:#f90,color:#fff,stroke:#333,stroke-width:2px
Callback Definition
paths:
/subscribe:
post:
summary: Subscribe to event notifications
operationId: subscribe
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
callbackUrl:
type: string
format: uri
description: URL the API will call when events occur
events:
type: array
items:
type: string
enum: [user.created, document.updated]
responses:
"201":
description: Subscription created
callbacks:
onUserCreated:
$request.body#/callbackUrl:
post:
summary: User created notification
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
id:
type: integer
name:
type: string
responses:
"202":
description: Client accepted the notification
Reusable Callbacks in Components
components:
callbacks:
UserCreatedCallback:
$request.body#/callbackUrl:
post:
summary: User created webhook payload
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
event:
type: string
enum: [user.created]
data:
$ref: "#/components/schemas/User"
responses:
"202":
description: Acknowledged
Common Mistakes
- Static callback URLs — Hardcoding URLs instead of using runtime expressions.
- No response expectations — Not documenting what the API expects from the callback response.
- Complex expressions — Using overly complex runtime expressions.
Practice Questions
- What is the purpose of callbacks?
- How do runtime expressions work in callbacks?
- How do you make callbacks reusable?
- What does the API expect from the callback response?
Challenge
Design callbacks for a document processing API where clients subscribe to events for document.uploaded, document.processed, and document.failed. Include the subscription endpoint and all callback definitions.
What's Next
In the next lesson, you will learn about link objects in OpenAPI.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro