首页>文档>FastAPI>fastapi中文手册:Path Operation Configuration(路径操作配置)

fastapi中文手册:Path Operation Configuration(路径操作配置)

fastapi中文手册:Path Operation Configuration(路径操作配置)

FastAPI 是一个高性能 Web 框架,用于构建 API。

主要特性:

  • 快速:非常高的性能,与 NodeJS 和 Go 相当
  • 快速编码:将功能开发速度提高约 200% 至 300%
  • 更少的错误:减少约 40% 的人为错误
  • 直观:强大的编辑器支持,自动补全无处不在,调试时间更少
  • 简易:旨在易于使用和学习,减少阅读文档的时间。
  • 简短:减少代码重复。
  • 稳健:获取可用于生产环境的代码,具有自动交互式文档
  • 基于标准:基于并完全兼容 API 的开放标准 OpenAPI 和 JSON Schema 

您可以将几个参数传递给路径操作装饰器以对其进行配置。

警告

注意这些参数直接传递到 路径装饰器,而不是传递到 路径操作函数

一、响应状态码

您可以自定义HTTP状态码使用在路径函数的响应中。

您可以直接传递int类型的状态码,比如 404

但是,如果您不记得每个数字代码的用途,则可以使用starlette中的快捷方式常量:

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel
from starlette.status import HTTP_201_CREATED 
app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
    tags: Set[str] = []

@app.post("/items/", response_model=Item, status_code=HTTP_201_CREATED) async def create_item(*, item: Item):
    return item

这些状态码在响应中使用,并且会被添加到OpenAPI schema中。

二、标记(Tags)

你可以给路径操作函数添加标记,通过tags参数,参数类型可以是list或者str(一般是一个str):

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
    tags: Set[str] = []

@app.post("/items/", response_model=Item, tags=["items"]) async def create_item(*, item: Item):
    return item

@app.get("/items/", tags=["items"]) async def read_items():
    return [{"name": "Foo", "price": 42}]

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

这些标记将会被添加到OpenAPI schema中,在自动文旦的交互页面中可查看:

fastapi中文手册:Path Operation Configuration(路径操作配置)

三、总结(summary)和描述(description)

你可以添加 summarydescription:

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
    tags: Set[str] = []

@app.post(
    "/items/",
    response_model=Item,
 summary="Create an item", description="Create an item with all the information, name, description, price, tax and a set of unique tags", )
async def create_item(*, item: Item):
    return item

四、来自文档字符串的描述

如果描述很长或者包含多行文字,你可以申明路径操作描述在函数中,并且 FastAPI 也会从这里读取。

你可以在书写Markdown语法的文档描述串,它也可以被正确显示。

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
    tags: Set[str] = []

@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(*, item: Item):
 """ Create an item with all the information: 
  - **name**: each item must have a name
 - **description**: a long description
 - **price**: required - **tax**: if the item doesn't have tax, you can omit this
 - **tags**: a set of unique tag strings for this item
 """
    return item

在交互文档中,显示如下:

fastapi中文手册:Path Operation Configuration(路径操作配置)

五、响应描

你可以使用参数 response_description来描述响应:

from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
    tags: Set[str] = []

@app.post(
    "/items/",
    response_model=Item,
    summary="Create an item",
    response_description="The created item", )
async def create_item(*, item: Item):
    """
 Create an item with all the information:

 - **name**: each item must have a name
 - **description**: a long description
 - **price**: required
 - **tax**: if the item doesn't have tax, you can omit this
 - **tags**: a set of unique tag strings for this item
 """
    return item

说明
请注意,response_description特别是指响应,description一般是指路径操作。

OpenAPI指定每个路径操作都需要响应描述。

因此,如果您不提供任何一种,** FastAPI **将自动生成“成功响应”之一。

fastapi中文手册:Path Operation Configuration(路径操作配置)

六、弃用路径操作

如果你想要弃用一个路径操作,但是又不想删除它,可以给路径操作函数传递一个参数 deprecated:

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/", tags=["items"])
async def read_items():
    return [{"name": "Foo", "price": 42}]

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

@app.get("/elements/", tags=["items"], deprecated=True) async def read_elements():
    return [{"item_id": "Foo"}]

在交互式文档中,它将明确标记为不推荐使用:

fastapi中文手册:Path Operation Configuration(路径操作配置)

检查不赞成和不赞成使用的路径操作的样子:

fastapi中文手册:Path Operation Configuration(路径操作配置)
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索