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'})
复制代码

 

posted @   ascertain  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2022-12-14 逆序输出整数
2020-12-14 局域网内无法通过主机名访问共享
2020-12-14 Different lower_case_table_names settings for server ('1')
2020-12-14 MySQL grant & revoke 权限管理
2020-12-14 elasticsearch使用快照迁移索引
2020-12-14 Failed to connect to raw.githubusercontent.com port 443
点击右上角即可分享
微信分享提示