|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | +from fastapi import FastAPI, Body |
| 4 | +from pydantic import BaseModel, Field |
| 5 | + |
| 6 | +app = FastAPI() |
| 7 | + |
| 8 | + |
| 9 | +class Item(BaseModel): |
| 10 | + name: str |
| 11 | + description: Optional[str] = None |
| 12 | + price: float |
| 13 | + tax: Optional[float] = None |
| 14 | + |
| 15 | + class Config: |
| 16 | + schema_extra = { |
| 17 | + 'example': { |
| 18 | + 'name': 'Foo', |
| 19 | + 'description': 'A very good Item', |
| 20 | + 'price': 25.4, |
| 21 | + 'tax': 3.4, |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + |
| 26 | +class Item2(BaseModel): |
| 27 | + name: str = Field(..., example='Foo') |
| 28 | + description: Optional[str] = Field(None, example='A very good Item') |
| 29 | + price: float = Field(..., example=33.4) |
| 30 | + tax: Optional[float] = Field(None, example=3.3) |
| 31 | + |
| 32 | + |
| 33 | +@app.put('/items/{item_id}') |
| 34 | +async def update_item(item_id: int, item: Item): |
| 35 | + results = {'item_id': item_id, 'item': item} |
| 36 | + return results |
| 37 | + |
| 38 | + |
| 39 | +@app.put('/items2/{item_id}') |
| 40 | +async def update_item2(item_id: int, item: Item2): |
| 41 | + results = {'item_id': item_id, 'item': item} |
| 42 | + return results |
| 43 | + |
| 44 | + |
| 45 | +@app.put('/items3/{item_id}') |
| 46 | +async def update_item3(item_id: int, item: Item = Body(..., example={ |
| 47 | + 'name': 'Foo', |
| 48 | + 'description': 'A very good Item !!!', |
| 49 | + 'price': 34.2, |
| 50 | + 'tax': 3.2 |
| 51 | +})): |
| 52 | + results = {'item_id': item_id, 'item': item} |
| 53 | + return results |
| 54 | + |
| 55 | + |
| 56 | +@app.put('/items4/{item_id}') |
| 57 | +async def update_item3(item_id: int, item: Item = Body(..., examples={ |
| 58 | + "normal": { |
| 59 | + "summary": "A normal example", |
| 60 | + "description": "A **normal** item works correctly.", |
| 61 | + "value": { |
| 62 | + "name": "Foo", |
| 63 | + "description": "A very nice Item", |
| 64 | + "price": 35.4, |
| 65 | + "tax": 3.2, |
| 66 | + }, |
| 67 | + }, |
| 68 | + "converted": { |
| 69 | + "summary": "An example with converted data", |
| 70 | + "description": "FastAPI can convert price `strings` to actual `numbers` automatically", |
| 71 | + "value": { |
| 72 | + "name": "Bar", |
| 73 | + "price": "35.4", |
| 74 | + }, |
| 75 | + }, |
| 76 | + "invalid": { |
| 77 | + "summary": "Invalid data is rejected with an error", |
| 78 | + "value": { |
| 79 | + "name": "Baz", |
| 80 | + "price": "thirty five point four", |
| 81 | + }, |
| 82 | + }, |
| 83 | +})): |
| 84 | + results = {'item_id': item_id, 'item': item} |
| 85 | + return results |
| 86 | + |
| 87 | + |
| 88 | +# PYTHONPATH=module_fastapi uvicorn fastapi_request_example_data:app --reload |
0 commit comments