FastAPI 教程翻译 - 用户指南 5 - 请求主体

FastAPI 教程翻译 - 用户指南 5 - 请求主体

FastAPI Tutorial - User Guide - Request Body

When you need to send data from a client (let’s say, a browser) to your API, you send it as a request body.

当您需要将数据从客户端(例如浏览器)发送到 API 时,可以将其作为请求主体发送。

A request body is data sent by the client to your API. A response body is the data your API sends to the client.

请求主体是客户端发送到您的 API 的数据。响应主体是您的 API 发送给客户端的数据。

Your API almost always has to send a response body. But clients don’t necessarily need to send request bodies all the time.

您的 API 几乎总是必须发送响应主体。但是客户端不一定需要一直发送请求主体

To declare a request body, you use Pydantic models with all their power and benefits.

要声明请求主体,请使用 Pydantic 模型并应用其所有功能和优点。

Info

信息

You cannot send a request body using a GET operation (HTTP method).

您不能使用 GET 操作(HTTP 方法)发送请求主体。

To send data, you have to use one of: POST (the more common), PUT, DELETE or PATCH.

要发送数据,您必须使用以下之一:POST(较常见)、PUTDELETEPATCH

Import Pydantic’s BaseModel

导入 Pydantic 的 BaseModel

First, you need to import BaseModel from pydantic:

首先,您需要从 pydantic 导入 BaseModel

from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


app = FastAPI()


@app.post("/items/")
async def create_item(item: Item):
    return item

Create your data model

创建您的数据模型

Then you declare your data model as a class that inherits from BaseModel.

然后,将数据模型声明为继承自 BaseModel 的类。

Use standard Python types for all the attributes:

对所有属性使用标准 Python 类型:

from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


app = FastAPI()


@app.post("/items/")
async def create_item(item: Item):
    return item

The same as when declaring query parameters, when a model attribute has a default value, it is not required. Otherwise, it is required. Use None to make it just optional.

与声明查询参数时相同,当模型属性具有默认值时,则不需要此属性。否则,它是必需的。使用 None 使其成为可选。

For example, this model above declares a JSON “object” (or Python dict) like:

例如,上面的该模型声明一个 JSON『对象』(或 Python dict),如下:

{
    "name": "Foo",
    "description": "An optional description",
    "price": 45.2,
    "tax": 3.5
}

…as description and tax are optional (with a default value of None), this JSON “object” would also be valid:

…… 由于 descriptiontax 是可选的(因为默认值为 None),因此这个 JSON『对象』也将有效:

{
    "name": "Foo",
    "price": 45.2
}

Declare it as a parameter

声明为参数

To add it to your path operation, declare it the same way you declared path and query parameters:

要将其添加到路径操作中,请使用声明路径和查询参数的相同方式进行声明:

from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


app = FastAPI()


@app.post("/items/")
async def create_item(item: Item):
    return item

…and declare its type as the model you created, Item.

…… 并将其类型声明为您创建的模型 Item

Results

结果

With just that Python type declaration, FastAPI will:

有了该 Python 类型声明,FastAPI 将:

  • Read the body of the request as JSON.

    以 JSON 读取请求主体。

  • Convert the corresponding types (if needed).

    转换相应的类型(如果需要)。

  • Validate the data.

    验证数据。

  • If the data is invalid, it will return a nice and clear error, indicating exactly where and what was the incorrect data.

    如果数据无效,它将返回一个清晰的错误,指出错误数据的确切位置和内容。

  • Give you the received data in the parameter item.

    在参数 item 中给您提供接收的数据。

  • As you declared it in the function to be of type Item, you will also have all the editor support (completion, etc) for all of the attributes and their types.

    当您在函数中声明类型 Item 时,您将获得所有属性及其类型的所有编辑器支持(自动补全等)。

  • Generate JSON Schema definitions for your model, you can also use them anywhere else you like if it makes sense for your project.

    为您的模型生成 JSON Schema 定义,如果对您的项目有意义,您也可以在其他任何地方使用它们。

  • Those schemas will be part of the generated OpenAPI schema, and used by the automatic documentation UIs.

    这些模式将是生成的 OpenAPI 模式的一部分,并由自动文档用户界面使用。

Automatic docs

自动文档

The JSON Schemas of your models will be part of your OpenAPI generated schema, and will be shown in the interactive API docs:

模型的 JSON 模式将成为 OpenAPI 生成模式的一部分,并将显示在交互式 API 文档中:

And will be also used in the API docs inside each path operation that needs them:

并且还将在需要它们的每个路径操作中的 API 文档中使用:

在这里插入图片描述

Editor support

编辑器支持

In your editor, inside your function you will get type hints and completion everywhere (this wouldn’t happen if you received a dict instead of a Pydantic model):

在编辑器的函数中,您会在任何地方得到类型提示和自动补全(如果您收到的是 dict 而不是 Pydantic 模型,则不会发生这种情况):

在这里插入图片描述

You also get error checks for incorrect type operations:

您还将获得错误检查,以检查错误的类型操作:

在这里插入图片描述

This is not by chance, the whole framework was built around that design.

这并非偶然,整个框架都是围绕该设计构建的。

And it was thoroughly tested at the design phase, before any implementation, to ensure it would work with all the editors.

在进行任何实施之前,它都已在设计阶段进行了全面测试,以确保它可以与所有编辑器一起使用。

There were even some changes to Pydantic itself to support this.

Pydantic 本身甚至进行了一些更改以支持此操作。

The previous screenshots were taken with Visual Studio Code.

以前的屏幕截图是使用 Visual Studio Code 拍摄的。

But you would get the same editor support with PyCharm and most of the other Python editors:

但是您可以通过 PyCharm 和其他大多数 Python 编辑器获得相同的编辑器支持:

在这里插入图片描述

Use the model

使用模型

Inside of the function, you can access all the attributes of the model object directly:

在函数内部,您可以直接访问模型对象的所有属性:

from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


app = FastAPI()


@app.post("/items/")
async def create_item(item: Item):
    item_dict = item.dict()
    if item.tax:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
    return item_dict

Request body + path parameters

请求主体 + 路径参数

You can declare path parameters and body requests at the same time.

您可以同时声明路径参数和请求主体。

FastAPI will recognize that the function parameters that match path parameters should be taken from the path, and that function parameters that are declared to be Pydantic models should be taken from the request body.

FastAPI 将识别出与路径参数匹配的函数参数应从路径中获取,而声明为 Pydantic 模型的函数参数应从请求主体中获取

from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


app = FastAPI()


@app.put("/items/{item_id}")
async def create_item(item_id: int, item: Item):
    return {"item_id": item_id, **item.dict()}

Request body + path + query parameters

请求主体 + 路径 + 查询参数

You can also declare body, path and query parameters, all at the same time.

您还可以同时声明请求主体路径参数查询参数

FastAPI will recognize each of them and take the data from the correct place.

FastAPI 将识别它们中的每一个,并从正确的位置获取数据。

from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


app = FastAPI()


@app.put("/items/{item_id}")
async def create_item(item_id: int, item: Item, q: str = None):
    result = {"item_id": item_id, **item.dict()}
    if q:
        result.update({"q": q})
    return result

The function parameters will be recognized as follows:

函数参数将被识别如下:

  • If the parameter is also declared in the path, it will be used as a path parameter.

    如果在路径中也声明了该参数,它将用作路径参数。

  • If the parameter is of a singular type (like int, float, str, bool, etc) it will be interpreted as a query parameter.

    如果参数是单一类型(例如 intfloatstrbool 等),它将被解释为查询参数。

  • If the parameter is declared to be of the type of a Pydantic model, it will be interpreted as a request body.

    如果参数声明为 Pydantic 模型的类型,它将被解释为请求主体

Without Pydantic

不使用 Pydantic

If you don’t want to use Pydantic models, you can also use Body parameters. See the docs for Body - Multiple Parameters: Singular values in body.

如果您不想使用 Pydantic 模型,也可以使用 Body 参数。请参阅文档 Body - Multiple Parameters: Singular values in body

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值