committed by
GitHub
342 changed files with 1710 additions and 1008 deletions
@ -0,0 +1,51 @@ |
|||
# OpenAPI Webhooks |
|||
|
|||
There are cases where you want to tell your API **users** that your app could call *their* app (sending a request) with some data, normally to **notify** of some type of **event**. |
|||
|
|||
This means that instead of the normal process of your users sending requests to your API, it's **your API** (or your app) that could **send requests to their system** (to their API, their app). |
|||
|
|||
This is normally called a **webhook**. |
|||
|
|||
## Webhooks steps |
|||
|
|||
The process normally is that **you define** in your code what is the message that you will send, the **body of the request**. |
|||
|
|||
You also define in some way at which **moments** your app will send those requests or events. |
|||
|
|||
And **your users** define in some way (for example in a web dashboard somewhere) the **URL** where your app should send those requests. |
|||
|
|||
All the **logic** 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 in **your own code**. |
|||
|
|||
## Documenting webhooks with **FastAPI** and OpenAPI |
|||
|
|||
With **FastAPI**, 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 request **bodies** that your app would send. |
|||
|
|||
This can make it a lot easier for your users to **implement their APIs** to receive your **webhook** 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 FastAPI `0.99.0` and above. |
|||
|
|||
## An app with webhooks |
|||
|
|||
When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`. |
|||
|
|||
```Python hl_lines="9-13 36-53" |
|||
{!../../../docs_src/openapi_webhooks/tutorial001.py!} |
|||
``` |
|||
|
|||
The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. |
|||
|
|||
!!! info |
|||
The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files. |
|||
|
|||
Notice that with webhooks you are actually not declaring a *path* (like `/items/`), the text you pass there is just an **identifier** of the webhook (the name of the event), for example in `@app.webhooks.post("new-subscription")`, the webhook name is `new-subscription`. |
|||
|
|||
This is because it is expected that **your users** would define the actual **URL 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 with Uvicorn and go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>. |
|||
|
|||
You will see your docs have the normal *path operations* and now also some **webhooks**: |
|||
|
|||
<img src="/img/tutorial/openapi-webhooks/image01.png"> |
Before Width: | Height: | Size: 88 KiB After Width: | Height: | Size: 84 KiB |
After Width: | Height: | Size: 85 KiB |
@ -1,3 +1,6 @@ |
|||
# Define this here and not in the main mkdocs.yml file because that one is auto |
|||
# updated and written, and the script would remove the env var |
|||
INHERIT: !ENV [INSIDERS_FILE, '../en/mkdocs.no-insiders.yml'] |
|||
markdown_extensions: |
|||
pymdownx.highlight: |
|||
linenums: !ENV [LINENUMS, false] |
|||
|
@ -0,0 +1,38 @@ |
|||
from fastapi import FastAPI |
|||
|
|||
description = """ |
|||
ChimichangApp API helps you do awesome stuff. 🚀 |
|||
|
|||
## Items |
|||
|
|||
You can **read items**. |
|||
|
|||
## Users |
|||
|
|||
You will be able to: |
|||
|
|||
* **Create users** (_not implemented_). |
|||
* **Read users** (_not implemented_). |
|||
""" |
|||
|
|||
app = FastAPI( |
|||
title="ChimichangApp", |
|||
description=description, |
|||
summary="Deadpool's favorite app. Nuff said.", |
|||
version="0.0.1", |
|||
terms_of_service="http://example.com/terms/", |
|||
contact={ |
|||
"name": "Deadpoolio the Amazing", |
|||
"url": "http://x-force.example.com/contact/", |
|||
"email": "[email protected]", |
|||
}, |
|||
license_info={ |
|||
"name": "Apache 2.0", |
|||
"identifier": "MIT", |
|||
}, |
|||
) |
|||
|
|||
|
|||
@app.get("/items/") |
|||
async def read_items(): |
|||
return [{"name": "Katana"}] |
@ -0,0 +1,25 @@ |
|||
from datetime import datetime |
|||
|
|||
from fastapi import FastAPI |
|||
from pydantic import BaseModel |
|||
|
|||
app = FastAPI() |
|||
|
|||
|
|||
class Subscription(BaseModel): |
|||
username: str |
|||
montly_fee: float |
|||
start_date: datetime |
|||
|
|||
|
|||
@app.webhooks.post("new-subscription") |
|||
def new_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/") |
|||
def read_users(): |
|||
return ["Rick", "Morty"] |
@ -0,0 +1,115 @@ |
|||
from typing import Union |
|||
|
|||
from fastapi import FastAPI |
|||
from fastapi.testclient import TestClient |
|||
from pydantic import BaseModel |
|||
|
|||
|
|||
class FooBaseModel(BaseModel): |
|||
class Config: |
|||
extra = "forbid" |
|||
|
|||
|
|||
class Foo(FooBaseModel): |
|||
pass |
|||
|
|||
|
|||
app = FastAPI() |
|||
|
|||
|
|||
@app.post("/") |
|||
async def post( |
|||
foo: Union[Foo, None] = None, |
|||
): |
|||
return foo |
|||
|
|||
|
|||
client = TestClient(app) |
|||
|
|||
|
|||
def test_call_invalid(): |
|||
response = client.post("/", json={"foo": {"bar": "baz"}}) |
|||
assert response.status_code == 422 |
|||
|
|||
|
|||
def test_call_valid(): |
|||
response = client.post("/", json={}) |
|||
assert response.status_code == 200 |
|||
assert response.json() == {} |
|||
|
|||
|
|||
def test_openapi_schema(): |
|||
response = client.get("/openapi.json") |
|||
assert response.status_code == 200, response.text |
|||
assert response.json() == { |
|||
"openapi": "3.1.0", |
|||
"info": {"title": "FastAPI", "version": "0.1.0"}, |
|||
"paths": { |
|||
"/": { |
|||
"post": { |
|||
"summary": "Post", |
|||
"operationId": "post__post", |
|||
"requestBody": { |
|||
"content": { |
|||
"application/json": { |
|||
"schema": {"$ref": "#/components/schemas/Foo"} |
|||
} |
|||
} |
|||
}, |
|||
"responses": { |
|||
"200": { |
|||
"description": "Successful Response", |
|||
"content": {"application/json": {"schema": {}}}, |
|||
}, |
|||
"422": { |
|||
"description": "Validation Error", |
|||
"content": { |
|||
"application/json": { |
|||
"schema": { |
|||
"$ref": "#/components/schemas/HTTPValidationError" |
|||
} |
|||
} |
|||
}, |
|||
}, |
|||
}, |
|||
} |
|||
} |
|||
}, |
|||
"components": { |
|||
"schemas": { |
|||
"Foo": { |
|||
"properties": {}, |
|||
"additionalProperties": False, |
|||
"type": "object", |
|||
"title": "Foo", |
|||
}, |
|||
"HTTPValidationError": { |
|||
"properties": { |
|||
"detail": { |
|||
"items": {"$ref": "#/components/schemas/ValidationError"}, |
|||
"type": "array", |
|||
"title": "Detail", |
|||
} |
|||
}, |
|||
"type": "object", |
|||
"title": "HTTPValidationError", |
|||
}, |
|||
"ValidationError": { |
|||
"properties": { |
|||
"loc": { |
|||
"items": { |
|||
"anyOf": [{"type": "string"}, {"type": "integer"}] |
|||
}, |
|||
"type": "array", |
|||
"title": "Location", |
|||
}, |
|||
"msg": {"type": "string", "title": "Message"}, |
|||
"type": {"type": "string", "title": "Error Type"}, |
|||
}, |
|||
"type": "object", |
|||
"required": ["loc", "msg", "type"], |
|||
"title": "ValidationError", |
|||
}, |
|||
} |
|||
}, |
|||
} |
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue