FastAPI: OpenAPI
openapi_extra
@app.get('/items', operation_id='a', openapi_extra={"x-aperture-labs-portal": "blue", 'requestBody': { 'content': {
'required': True, 'application/json': { 'schema': { 'required': ['name', 'price'], 'type': 'object', 'properties': { 'name': {'type': 'string'}, 'price': {'type': 'number'}, 'description': {'type': 'string'} } } },
'application/yaml': {
'schema': Item.model_json_schema()
}
} }}) async def aaa(): return [{'item_id': 9}]
class Item(BaseModel): name: str tags: list[str] @app.post('/items', operation_id='a', openapi_extra={'x-aperture-labs-portal': 'blue', 'requestBody': { 'content': { 'application/yaml': { 'schema': Item.model_json_schema() } }, 'required': True }}) async def create_item(request: Request): raw = await request.body() try: data = yaml.safe_load(raw) print(data) except yaml.YAMLError: raise HTTPException(status_code=422, detail='Invalid YAML') try: item = Item.model_validate(data) except ValidationError as e: print(e) raise HTTPException(status_code=422, detail=e.errors()) return item
class Item(BaseModel): id: str value: str class Message(BaseModel): message: str @app.get('/items/{item_id}', response_model=Item, status_code=201, responses={ 201: { 'description': 'additional media types for the main response', 'content': { 'image/png': {}, 'application/json': { 'example': { 'id': 'bar', 'value': 'the bar tenders' } } }, 'headers': { 'X-Rate-Limit': { 'description': 'The number of allowed requests in the current period', 'schema': { 'type': 'integer' } }, 'X-Rate-Limit-Reset': { 'description': 'The number of seconds', 'schema': { 'type': 'string' } } } }, 404: { 'description': 'the item was not found', 'model': Message }, 10404: { 'model': Message }, 20404: { 'description': '20404', 'content': { 'application/json': { 'schema': Message.model_json_schema() } } } }) async def read_item(item_id: str, img: bool | None = None): if img: return FileResponse(path='image.png', media_type='image/png') if item_id == 'foo': return {"id": "foo", "value": "there goes my hero"} return JSONResponse(status_code=404, content={'message': 'item not found'})