Coverage for docs_src/openapi_callbacks/tutorial001.py: 100%

21 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-05 00:03 +0000

1from typing import Union 1abcdef

2 

3from fastapi import APIRouter, FastAPI 1abcdef

4from pydantic import BaseModel, HttpUrl 1abcdef

5 

6app = FastAPI() 1abcdef

7 

8 

9class Invoice(BaseModel): 1abcdef

10 id: str 1abcdef

11 title: Union[str, None] = None 1abcdef

12 customer: str 1abcdef

13 total: float 1abcdef

14 

15 

16class InvoiceEvent(BaseModel): 1abcdef

17 description: str 1abcdef

18 paid: bool 1abcdef

19 

20 

21class InvoiceEventReceived(BaseModel): 1abcdef

22 ok: bool 1abcdef

23 

24 

25invoices_callback_router = APIRouter() 1abcdef

26 

27 

28@invoices_callback_router.post( 1abcdef

29 "{$callback_url}/invoices/{$request.body.id}", response_model=InvoiceEventReceived 

30) 

31def invoice_notification(body: InvoiceEvent): 1abcdef

32 pass 1ghijkl

33 

34 

35@app.post("/invoices/", callbacks=invoices_callback_router.routes) 1abcdef

36def create_invoice(invoice: Invoice, callback_url: Union[HttpUrl, None] = None): 1abcdef

37 """ 

38 Create an invoice. 

39 

40 This will (let's imagine) let the API user (some external developer) create an 

41 invoice. 

42 

43 And this path operation will: 

44 

45 * Send the invoice to the client. 

46 * Collect the money from the client. 

47 * Send a notification back to the API user (the external developer), as a callback. 

48 * At this point is that the API will somehow send a POST request to the 

49 external API with the notification of the invoice event 

50 (e.g. "payment successful"). 

51 """ 

52 # Send the invoice, collect the money, send the notification (the callback) 

53 return {"msg": "Invoice received"} 1mnopqr