路径配置的一些参数,通过路径操作装饰器去配置它,包括:
• 1. status_code
• 2. tags
• 3. summary & description
• 4. response_description
• 5. deprecated
1、status_code
使用status_code参数来声明HTTP状态码,可以通过状态码数字、状态码变量方式来使用。
常用的有:
• 200及以上 成功的响应
• 300及以上 重定向
• 400及以上 客户端错误
• 500及以上 服务端错误
from fastapi import FastAPI
app =FastAPI()
@app.post("/status_code/", status_code=200)
def status_code():
return {"status_code": 200}
如果不记得具体的数字,可以使用FastAPI提供的变量形式。
这与上面的数字效果是一样的,两种方式都可以。
from fastapi import FastAPI, status
app = FastAPI()
@app.post("/status_attribute/", status_code=status.HTTP_200_OK)
def status_code():
return {"status_code": status.HTTP_200_OK}
表现形式:
2、tags
标签的作用可以将不同的API进行分类:
from fastapi import FastAPI
app = FastAPI()
@app.post("/create/item", tags=["items"])
def create_item():
return {"info":"create item"}@app.get("/get/item", tags=["items"])
def read_items():
return {"info":"get items"}@app.get("/users", tags=["users"])
def read_users():
return {"info":"get users"}
表现形式:
3、summary & description
summary,是对这个api的简短说明,说明当前这个api是干什么用的。
description,是对这个api的说明,比如是实现的什么功能。
from fastapi import FastAPI
app = FastAPI()
@app.post("/create/item",
tags=["items"],
summary="create an item",
description="this is a item,about ...")
表现形式:
但是如果说明内容很多,此时可以在函数中进行注释说明,FastAPI会自动在文档中显示。
@app.post("/docs/item",
tags=["items"],
summary="create an item")
def create_item():
""" create an item with all infomation:
- **name**: each item must have a name
- **description**: a long description
- **price**: required
...
"""
return{"info":"create item"}
表现形式:
4、response_description
对响应的数据进行说明:
from fastapi import FastAPI
app = FastAPI()
@app.post("/create/item",
tags=["items"],
summary="create an item",
description="this is a item,about ...",
response_description="the created item ...")
def create_item():
return {"info":"create item"}
表现形式:
5、deprecated
对废弃的API进行标识。
比如,API升级为V2.0版本,那么之前的V1.0版本废弃了,废弃了并不代表不能使用,所以可以通过 deprecated 标识配置值为True 进行区分。
from fastapi import FastAPI
app = FastAPI()
@app.post("/create/item",
tags=["items"],
summary="create an item",
description="this is a item,about ...",
response_description="the created item ...",
deprecated=True)
def create_item():
return {"info":"create item"}表现形式: