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