FastAPI配置系列(一) 路径操作配置

一、概述

通过一些参数去通过路径操作装饰器去配置它,在响应模型中的响应状态码就是属于路径操作配置,它包括:

  • status_code
  • tags
  • summary & description
  • response_description
  • deprecated

上述中都是路径配置的一些参数,下面详细说明。

二、配置参数说明

1、status_code

参考:https://www.cnblogs.com/shenjianping/p/14852051.html

2、tags

标签的作用可以将不同的API进行分类:

from fastapi import FastAPI

app = FastAPI()


@app.post("/create/item", tags=["items"])
async def create_item():
    return {"info": "create item"}


@app.get("/get/item", tags=["items"])
async def read_items():
    return {"info": "get items"}


@app.get("/users", tags=["users"])
async def read_users():
    return {"info": "get users"}

表现形式:

 3、summary & description

from fastapi import FastAPI

app = FastAPI()

@app.post("/create/item",
          tags=["items"],
          summary="create an item",
          description="this is a item,about ..."
          )

表现形式:

从上面可以看到descrition是对这个api的说明,比如是实现的什么功能,但是如果说明内容很多,应该怎么做呢?此时可以在函数中进行注释说明,FastAPI会自动在文档中显示。

@app.post("/docs/item",
          tags=["items"],
          summary="create an item",
          )
async 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 ..."
          )
async def create_item():
    return {"info": "create item"}

表现形式:

 5、deprecated

对废弃的API进行标识,比如API升级为2.0版本,那么之前的1.0版本废弃了,废弃了并不代表不能使用:

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
          )
async def create_item():
    return {"info": "create item"}
...

表现形式:

作者:iveBoy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/shenjianping/p/14854189.html