What Are Callbacks?
A callback occurs when:- A user sends a request to your API
- Your API processes the request
- Your API sends a request to an external API (provided by the user)
- The external API processes and responds
Callbacks are essentially “your API calling their API” - documenting what the external API should look like to receive your requests.
Callback Use Case Example
Imagine you’re building an invoice processing API:- External developers create invoices through your API
- Your API sends invoices to customers
- Your API collects payment
- Your API notifies the external developer by making a POST request to their API (callback)
Creating an API with Callbacks
Let’s build a complete example showing how to document callbacks.Define Data Models
First, define the models for invoices and callback events:The
HttpUrl type from Pydantic validates that the callback URL is properly formatted.Create a Callback Router
Create anAPIRouter specifically for documenting the callback:
Understanding the Callback Path
The callback path uses OpenAPI expressions:{$callback_url}: References thecallback_urlquery parameter from the original request{$request.body.id}: References theidfield from the request body
Add the Callback to Your Endpoint
Use thecallbacks parameter to attach the callback documentation:
How Callbacks Work in Practice
Here’s a real-world example flow:1. User Sends Request to Your API
2. Your API Processes and Calls Back
After processing, your API makes a callback request:3. External API Responds
The external API (implemented by your user) responds:Implementing the Actual Callback
The callback router only documents the callback. You still need to implement the actual HTTP request:Multiple Callbacks
You can document multiple callbacks for different events:OpenAPI Path Expressions
Callbacks support various OpenAPI 3 expressions:Query Parameter Reference
Header Reference
Body Field Reference
Multiple Parameters
Viewing Callback Documentation
Once implemented, your callbacks appear in the API documentation:- Start your application:
uvicorn main:app --reload - Open the docs:
http://127.0.0.1:8000/docs - Find your endpoint and expand the “Callbacks” section
Best Practices
- Use clear naming: Name your callbacks descriptively (e.g.,
payment-completed,invoice-sent) - Include authentication: Document required headers or authentication for callbacks
- Handle failures gracefully: Implement retries and error handling for callback requests
- Use background tasks: Don’t block user requests while sending callbacks
- Timeout appropriately: Set reasonable timeouts for callback requests
- Version your callbacks: Include version info if your callback format may change
Complete Example
Related Topics
- OpenAPI Webhooks - Document webhook endpoints (similar but different concept)
- Extending OpenAPI - Customize your OpenAPI schema
- Background Tasks - Execute callbacks without blocking