OpenAPI Webhooks¶
There are cases where you want to tell your APIusers that your app could calltheir app (sending a request) with some data, normally tonotify of some type ofevent.
This means that instead of the normal process of your users sending requests to your API, it'syour API (or your app) that couldsend requests to their system (to their API, their app).
This is normally called awebhook.
Webhooks steps¶
The process normally is thatyou define in your code what is the message that you will send, thebody of the request.
You also define in some way at whichmoments your app will send those requests or events.
Andyour users define in some way (for example in a web dashboard somewhere) theURL where your app should send those requests.
All thelogic about how to register the URLs for webhooks and the code to actually send those requests is up to you. You write it however you want to inyour own code.
Documenting webhooks withFastAPI and OpenAPI¶
WithFastAPI, using OpenAPI, you can define the names of these webhooks, the types of HTTP operations that your app can send (e.g.POST,PUT, etc.) and the requestbodies that your app would send.
This can make it a lot easier for your users toimplement their APIs to receive yourwebhook requests, they might even be able to autogenerate some of their own API code.
Info
Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI0.99.0 and above.
An app with webhooks¶
When you create aFastAPI application, there is awebhooks attribute that you can use to definewebhooks, the same way you would definepath operations, for example with@app.webhooks.post().
fromdatetimeimportdatetimefromfastapiimportFastAPIfrompydanticimportBaseModelapp=FastAPI()classSubscription(BaseModel):username:strmonthly_fee:floatstart_date:datetime@app.webhooks.post("new-subscription")defnew_subscription(body:Subscription):""" When a new user subscribes to your service we'll send you a POST request with this data to the URL that you register for the event `new-subscription` in the dashboard. """@app.get("/users/")defread_users():return["Rick","Morty"]The webhooks that you define will end up in theOpenAPI schema and the automaticdocs UI.
Info
Theapp.webhooks object is actually just anAPIRouter, the same type you would use when structuring your app with multiple files.
Notice that with webhooks you are actually not declaring apath (like/items/), the text you pass there is just anidentifier of the webhook (the name of the event), for example in@app.webhooks.post("new-subscription"), the webhook name isnew-subscription.
This is because it is expected thatyour users would define the actualURL path where they want to receive the webhook request in some other way (e.g. a web dashboard).
Check the docs¶
Now you can start your app and go tohttp://127.0.0.1:8000/docs.
You will see your docs have the normalpath operations and now also somewebhooks:








