首页 > 其他分享 >FastAPI: OpenAPI

FastAPI: OpenAPI

时间:2023-12-14 16:24:14浏览次数:29  
标签:description FastAPI OpenAPI item str type id schema

 

openapi_extra

@app.get('/items', operation_id='a', openapi_extra={"x-aperture-labs-portal": "blue", 'requestBody': {
    'content': {
        'application/json': {
            'schema': {
                'required': ['name', 'price'],
                'type': 'object',
                'properties': {
                    'name': {'type': 'string'},
                    'price': {'type': 'number'},
                    'description': {'type': 'string'}
                }
            }
        }
    }
}})
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'})

 

标签:description,FastAPI,OpenAPI,item,str,type,id,schema
From: https://www.cnblogs.com/dissipate/p/17901416.html

相关文章

  • fastapi、tortoise-orm参考文章
    https://www.coonote.com/note/tortoise-orm.htmlhttps://www.yuque.com/u1362970/xyh2wn/ma9g38gn6rekeuq7https://zhuanlan.zhihu.com/p/635436561?utm_id=0http://www.360doc.com/content/23/1013/13/1100047637_1100047637.shtml......
  • 饮冰十年-人工智能-FastAPI-03- FastAPI之模型迁移(类似Django的migrante)
         在开发Web应用程序时,通常会涉及到数据库模型的更改,例如添加新的表、字段或索引。为了使这些更改反映在数据库中,我们使用数据库迁移工具。FastAPI本身并不包含数据库迁移(migration)的功能,但你可以使用第三方库来处理数据库迁移。其中,Alembic是一个常用的数据库迁......
  • FastAPI-请求参数与验证
    最近想搞一下接口,希望能简单上手,前后端分离,大致看了一遍SpringBoot,Gin,NodeJs,Flask,Django,FastAPI等,感觉还是用Python语言来写比较简单呀,关键点在于它语法清晰,能让我直接思考业务逻辑,而不是各种语法折腾.FASTAPI简介Documentation:https://fastap......
  • Using Redis with FastAPI
    UsingRediswithFastAPIhttps://developer.redis.com/develop/python/fastapi/https://github.com/fanqingsong/fastapi-redis-tutorialFastAPIisaPythonwebframeworkbasedontheStarlettemicroframework.Withdeepsupportforasyncio,FastAPIisindeedv......
  • fastapi的两种启动方式
     代码文件中启动if__name__=='__main__':uvicorn.run('test:app')#其中test为当前py文件,app为FastAPI的实例对象,这样启动默认为http://127.0.0.1:8000,可自行配置host,port,workers,reload等参数。终端启动#cd到启动文件同目录#终端执行uvicorntest:app--reloa......
  • Fastapi中dependency的生命周期
    https://bobobo80.com/2021/fastapizhong-dependencyde-sheng-ming-zhou-qi.html发现问题最近使用fastapi时,出现了一个alchemysql数据库连接池的错误。超过了默认的连接池限制。按理说自己的服务只有一个人在用,应该不会出现这种问题。sqlalchemy.exc.TimeoutError:QueuePool......
  • 关于FastAPI与Vue3的通信
    学习一下前后端分离技术,前端采用三大框架之一的Vue.js,后端则采用Python的FastAPI框架。一、前端设计1.建目录mydemo2.在mydemo目录下打开命令行,运行:npminitvue@latest(这里如果cmd卡死了,就ctrl+C结束,再次运行npminitvue@latest)3.工程名设置为 frontend ,其余按默......
  • Fastapi框架:Starlette,Pydantic 与 FastAPI 框架是什么关系?
    【一】介绍Starlette是个什么项目;IDE开发时Python3.5+版本的"typehints"的好处:简短、直观和标准的Python类型声明;介绍Pydantic包,FastAPI项目的开发为什么要使用Pydantic【二】Starlette【1】介绍Starlette是一种轻量级的ASGI框架/工具包,是构建高性能A......
  • Fastapi框架:引入
    【一】为什么新秀FastAPI火成这样介绍FastAPI有哪些突出特点,浏览官网文档中的Feasures一览【二】FastAPI的突出特点性能优越开发效率提升200%~300%直接减少约40%的人为BUG直观易学易用经简代码/代码重复率低自带API交互文档,开发成果随时交付API开发标准化......
  • Flask简介、Flask创建和运行、fastapi、显示用户小案例
    Flask简介#python主流的web框架-Django-fastapi:异步-flask#flask是个微型的web框架,不像djagno那么庞大,django有很多内置app,缓存,信号,消息,权限,admin#flask随着项目越来越大,使用第三方插件,越来越像django模版渲染:jinja2web服务器:WerkzeugWS......