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"}
...

表现形式:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM