FastAPI 教程翻译 - 介绍

FastAPI 教程翻译 - 介绍

FastAPI 教程翻译 - 介绍_第1张图片

FastAPI framework, high performance, easy to learn, fast to code, ready for production

FastAPI 框架,高性能,易于学习,快速编写代码,可投入生产


Documentation: https://fastapi.tiangolo.com

文档:https://fastapi.tiangolo.com

Source Code: https://github.com/tiangolo/fastapi

源代码:https://github.com/tiangolo/fastapi


FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.

FastAPI 是一种现代、快速(高性能)的 Web 框架,用于构建 API,使用 Python 3.6+,基于标准 Python 类型提示。

The key features are:

主要特性是:

  • Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.

    快速:非常高的性能,与 NodeJSGo 相当(感谢 Starlette 和 Pydantic)。可用的最快的 Python 框架之一。

  • Fast to code: Increase the speed to develop features by about 200% to 300%.*

    快速编写代码:将功能开发速度提高约 200% 至 300%。*

  • Fewer bugs: Reduce about 40% of human (developer) induced errors.

    更少的错误:减少约 40% 的人为错误(开发人员)。*

  • Intuitive: Great editor support. Completion everywhere. Less time debugging.

    直观:强大的编辑器支持。自动补全无处不在。调试时间更少。

  • Easy: Designed to be easy to use and learn. Less time reading docs.

    简单:易于使用和学习。减少阅读文档的时间。

  • Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.

    简短:减少代码重复。每个参数声明中具有多个特性。更少的错误。

  • Robust: Get production-ready code. With automatic interactive documentation.

    健壮:获取可用于生产环境的代码。具有自动交互式文档。

  • Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.

    基于标准的:基于 API 的开放标准(并与之完全兼容):OpenAPI(以前称为 Swagger)和 JSON 模式。

* estimation based on tests on an internal development team, building production applications.

*根据内部开发团队的测试进行估算,以构建生产应用程序。

Opinions

意见

[…] I’m using FastAPI a ton these days. […] I’m actually planning to use it for all of my team’s ML services at Microsoft*. Some of them are getting integrated into the core* Windows product and some Office products.

Kabir Khan - Microsoft (ref)


I’m over the moon excited about FastAPI*. It’s so fun!*”

Brian Okken - Python Bytes podcast host (ref)


Honestly, what you’ve built looks super solid and polished. In many ways, it’s what I wanted Hug to be - it’s really inspiring to see someone build that.

Timothy Crosley - Hug creator (ref)


If you’re looking to learn one modern framework for building REST APIs, check out FastAPI […] It’s fast, easy to use and easy to learn […]

We’ve switched over to FastAPI for our APIs […] I think you’ll like it […]

Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)


We adopted the FastAPI library to spawn a REST server that can be queried to obtain predictions*. [for Ludwig]*”

Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)


Requirements

要求

Python 3.6+

FastAPI stands on the shoulders of giants:

FastAPI 站在巨人的肩膀上:

  • Starlette for the web parts.

    Starlette 用于构建 Web 部件。

  • Pydantic for the data parts.

    Pydantic 用于数据部分。

Installation

安装

pip install fastapi

You will also need an ASGI server, for production such as Uvicorn or Hypercorn.

您还需要一个 ASGI 服务来进行生产部署,例如 Uvicorn 或者 Hypercorn。

pip install uvicorn

Example

示例

Create it

创建

  • Create a file main.py with:

    使用以下命令创建文件 main.py

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

Or use async def

或者使用 asyn def……

If your code uses async / await, use async def:

如果您的代码使用了 async 或者 await,请使用 async def

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def read_root():
 return {"Hello": "World"}


@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
 return {"item_id": item_id, "q": q}

Note

注意

If you don’t know, check the “In a hurry?” section about async and await in the docs.

如果您不知道,查看“繁忙?“章节关于 async and await in the docs 的部分。

Run it

运行

Run the server with:

使用以下命令运行服务器:

uvicorn main:app --reload

About the command uvicorn main:app --reload

关于命令 uvicorn main:app --reload

The command uvicorn main:app --reload refers to:

命令 uvicorn main:app --reload 的相关说明:

  • main: the file main.py (the Python “module”).

    main:文件 main.py(Python 模块)

  • app: the object created inside of main.py with the line app = FastAPI().

    app:在 main.py 内部创建的对象,其中包含 app = FastAPI() 行。

  • --reload: make the server restart after code changes. Only do this for development.

    --reload:使服务器在代码更改后重新启动。 仅开发时使用。

Check it

检查

Open your browser at http://127.0.0.1:8000/items/5?q=somequery.

用浏览器打开 http://127.0.0.1:8000/items/5?q=somequery。

You will see the JSON response as:

您将看到 JSON 响应:

{"item_id": 5, "q": "somequery"}

You already created an API that:

您已经创建了一个 API:

  • Receives HTTP requests in the paths / and /items/{item_id}.

    路径 //items/{item_id} 中接收 HTTP 请求。

  • Both paths take GET operations (also known as HTTP methods).

    两个路径都采用 GET 操作(也称为 HTTP 方法)。

  • The path /items/{item_id} has a path parameter item_id that should be an int.

    路径 /items/{item_id} 具有路径参数 item_id 并且应该是 int

  • The path /items/{item_id} has an optional str query parameter q.

    路径 /items/{item_id} 具有可选的 str 查询参数 q

Interactive API docs

交互式 API 文档

Now go to http://127.0.0.1:8000/docs.

现在转到 http://127.0.0.1:8000/docs。

You will see the automatic interactive API documentation (provided by Swagger UI):

您将看到自动交互式 API 文档(由 Swagger UI 提供):

FastAPI 教程翻译 - 介绍_第2张图片

Alternative API docs

备用 API 文档

And now, go to http://127.0.0.1:8000/redoc.

现在,转到 http://127.0.0.1:8000/redoc。

You will see the alternative automatic documentation (provided by ReDoc):

您将看到备用的自动交互式文档(由 ReDoc 提供):

FastAPI 教程翻译 - 介绍_第3张图片

Example upgrade

更新示例

Now modify the file main.py to receive a body from a PUT request.

现在修改文件 main.py 以接收来自 PUT 的请求体。

Declare the body using standard Python types, thanks to Pydantic.

感谢 Pydantic,实现用标准的 Python 类来声明请求体。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}


@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    return {"item_name": item.name, "item_id": item_id}

The server should reload automatically (because you added --reload to the uvicorn command above).

服务应该自动重新加载(因为您在上面的 uvicorn 命令中添加了 --reload)。

Interactive API docs upgrade

交互式 API 文档更新

Now go to http://127.0.0.1:8000/docs.

现在转到 http://127.0.0.1:8000/docs。

  • The interactive API documentation will be automatically updated, including the new body:

    交互式 API 文档将自动更新,包括新的请求体:

FastAPI 教程翻译 - 介绍_第4张图片

  • Click on the button “Try it out”, it allows you to fill the parameters and directly interact with the API:

    点击『Try it out』按钮,它可以让您填写参数并直接与 API 交互:

FastAPI 教程翻译 - 介绍_第5张图片

  • Then click on the “Execute” button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:

    然后点击『Execute』按钮,用户界面将与您的 API 通信,发送参数,获取结果并将其显示在屏幕上:

FastAPI 教程翻译 - 介绍_第6张图片

Alternative API docs upgrade

备用 API 文档更新

And now, go to http://127.0.0.1:8000/redoc.

现在,转到 http://127.0.0.1:8000/redoc。

  • The alternative documentation will also reflect the new query parameter and body:

    备用文档也将反映新的查询参数和请求体:

FastAPI 教程翻译 - 介绍_第7张图片

Recap

回顾

In summary, you declare once the types of parameters, body, etc. as function parameters.

总而言之,您可以一次性将参数的类型、请求体等声明为函数参数。

You do that with standard modern Python types.

您可以使用标准的现代 Python 类型来做到这一点。

You don’t have to learn a new syntax, the methods or classes of a specific library, etc.

您不必学习新的语法,特定库的方法或类等。

Just standard Python 3.6+.

只是标准的 Python 3.6+

For example, for an int:

例如,对于一个 int

item_id: int

or for a more complex Item model:

或更复杂的 Item 模型:

item: Item

…and with that single declaration you get:

…… 并且使用该单个声明,您将获得:

  • Editor support, including:

    编辑器支持,包括:

    • Completion.

      自动补全。

    • Type checks.

      类型检查。

  • Validation of data:

    数据验证:

    • Automatic and clear errors when the data is invalid.

      数据无效时自动清除错误。

    • Validation even for deeply nested JSON objects.

      甚至针对深度嵌套的 JSON 对象进行验证。

  • Conversion of input data: coming from the network to Python data and types. Reading from:

    输入数据的转换:从网络到 Python 数据和类型。如:

    • JSON.

    • Path parameters.

      路径参数。

    • Query parameters.

      查询参数。

    • Cookies.

    • Headers.

    • Forms.

      表单。

    • Files.

      文件。

  • Conversion of output data: converting from Python data and types to network data (as JSON):

    输出数据的转换:从 Python 数据和类型转换为网络数据(如 JSON):

    • Convert Python types (str, int, float, bool, list, etc).

      转换 Python 类型(strintfloatboollist 等等)。

    • datetime objects.

      datetime 对象。

    • UUID objects.

      UUID对象。

    • Database models.

      数据基础模型。

    • …and many more.

      …… 和更多的。

  • Automatic interactive API documentation, including 2 alternative user interfaces:

    自动交互式API文档,包括2个备用用户界面:

    • Swagger UI.
    • ReDoc.

Coming back to the previous code example, FastAPI will:

回到前面的代码示例,**FastAPI **将:

  • Validate that there is an item_id in the path for GET and PUT requests.

    验证路径中是否有用于 GETPUT 请求的 item_id

  • Validate that the item_id is of type int for GET and PUT requests.

    验证 item_id 的类型是否为 GETPUT 请求的 int 类型。

  • If it is not, the client will see a useful, clear error.

    如果不是,则客户端将看到一个有用的明确错误。

  • Check if there is an optional query parameter named q (as in http://127.0.0.1:8000/items/foo?q=somequery) for GET requests.

    检查是否有一个名为 q 的可选查询参数(如 http://127.0.0.1:8000/items/foo?q=somequery),用于 GET 请求。

  • As the q parameter is declared with = None, it is optional.

    由于 q 参数以 =None 声明,因此它是可选的。

    • Without the None it would be required (as is the body in the case with PUT).

      如果没有 None,则将是必需的(与 PUT 一样,请求体也是如此)。

  • For PUT requests to /items/{item_id}, Read the body as JSON:

    对于对 /items/{item_id}PUT 请求,将正文读取为 JSON:

  • Check that it has a required attribute name that should be a str.

    检查其是否具有必须的属性 name,该属性应为 str

    • Check that it has a required attribute price that has to be a float.

      检查它是否具有必须的属性 price,该属性应为 float

    • Check that it has an optional attribute is_offer, that should be a bool, if present.

      检查它是否具有可选属性 is_offer,如果存在则应为 bool

    • All this would also work for deeply nested JSON objects.

      所有这些也适用于深度嵌套的 JSON 对象。

  • Convert from and to JSON automatically.

    自动从 JSON 转换。

  • Document everything with OpenAPI, that can be used by:

    使用 OpenAPI 记录所有内容,可用于:

    • Interactive documentation systems.

      交互式文档系统。

    • Automatic client code generation systems, for many languages.

      适用于多种语言的自动客户端代码生成系统。

  • Provide 2 interactive documentation web interfaces directly.

    直接提供 2 个交互式文档 Web 界面。


We just scratched the surface, but you already get the idea of how it all works.

我们仅仅只进行了简单描绘,但您已经了解了所有工作原理。

Try changing the line with:

尝试使用以下方法更改这行代码:

    return {"item_name": item.name, "item_id": item_id}

…from:

…… 从:

        ... "item_name": item.name ...

…to:

…… 到:

        ... "item_price": item.price ...

…and see how your editor will auto-complete the attributes and know their types:

…… 并查看编辑器如何自动完成属性并了解其类型:

FastAPI 教程翻译 - 介绍_第8张图片

For a more complete example including more features, see the Tutorial - User Guide.

有关包含更多功能的更完整示例,请参见 Tutorial - User Guide。

Spoiler alert: the tutorial - user guide includes:

剧透警报:本教程 - 用户指南包括:

  • Declaration of parameters from other different places as: headers, cookies, form fields and files.

    从其他不同地方声明参数,例如:headerscookies表单字段文件

  • How to set validation constraints as maximum_length or regex.

    如何将验证约束设置为 maximum_lengthregex

  • A very powerful and easy to use Dependency Injection system.

    一个非常强大且易于使用的依赖注入系统。

  • Security and authentication, including support for OAuth2 with JWT tokens and HTTP Basic auth.

    安全性和身份验证,包括通过 JWT 令牌认证HTTP 基础认证

  • More advanced (but equally easy) techniques for declaring deeply nested JSON models (thanks to Pydantic).

    用于声明深度嵌套的 JSON 模型的更高级(但同样容易)的技术(感谢 Pydantic)。

  • Many extra features (thanks to Starlette) as:

    许多额外的功能(感谢 Starlette):

    • WebSockets

    • GraphQL

    • extremely easy tests based on requests and pytest

      基于 requestspytest 的极其简单的测试

    • CORS

    • Cookie Sessions

    • …and more.

      …… 和更多。

Performance

性能

Independent TechEmpower benchmarks show FastAPI applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)

独立的 TechEmpower 基准测试显示 FastAPI 应用程序在 Uvicorn(可用的最快 Python 框架之一)上运行,仅低于 Starlette 和 Uvicorn 本身(由 FastAPI 内部使用)。

To understand more about it, see the section Benchmarks.

要了解更多信息,请参阅基准部分。

Optional Dependencies

可选依赖项

Used by Pydantic:

由 Pydantic 提供:

  • ujson - for faster JSON “parsing”.

    ujson - 用于更快的 JSON『解析』。

  • email_validator - for email validation.

    email_validator - 用于电子邮箱验证。

Used by Starlette:

由 Starlette 提供:

  • requests - Required if you want to use the TestClient.

    requests - 如果您想使用TestClient,则为必需。

  • aiofiles - Required if you want to use FileResponse or StaticFiles.

    aiofiles - 如果您想使用FileResponseStaticFiles,则必选。

  • jinja2 - Required if you want to use the default template configuration.

    jinja2 - 如果要使用默认模板配置,则为必需。

  • python-multipart - Required if you want to support form “parsing”, with request.form().

    python-multipart - 如果您想使用request.form()支持表单“解析”,则为必需。

  • itsdangerous - Required for SessionMiddleware support.

    itsdangerous - 需要SessionMiddleware支持。

  • pyyaml - Required for Starlette’s SchemaGenerator support (you probably don’t need it with FastAPI).

    pyyaml - Starlette的SchemaGenerator支持所必需的(FastAPI可能不需要它)。

  • graphene - Required for GraphQLApp support.

    graphene - 为GraphQLApp支持所必需。

  • ujson - Required if you want to use UJSONResponse.

    ujson - 如果要使用UJSONResponse,则为必需。

Used by FastAPI / Starlette:

由 FastAPI / Starlette 提供:

  • uvicorn - for the server that loads and serves your application.

    uvicorn - 用于加载和服务您的应用程序的服务器。

  • orjson - Required if you want to use ORJSONResponse.

    orjson - 如果要使用ORJSONResponse,则为必需。

You can install all of these with pip install fastapi[all].

您可以使用 pip install fastapi[all] 安装所有这些内容。

License

许可

This project is licensed under the terms of the MIT license.

e/ultrajson) - Required if you want to use UJSONResponse.

ujson - 如果要使用UJSONResponse,则为必需。

Used by FastAPI / Starlette:

由 FastAPI / Starlette 提供:

  • uvicorn - for the server that loads and serves your application.

    uvicorn - 用于加载和服务您的应用程序的服务器。

  • orjson - Required if you want to use ORJSONResponse.

    orjson - 如果要使用ORJSONResponse,则为必需。

You can install all of these with pip install fastapi[all].

您可以使用 pip install fastapi[all] 安装所有这些内容。

License

许可

This project is licensed under the terms of the MIT license.

该项目根据 MIT 许可条款获得许可。

你可能感兴趣的:(FastAPI,教程翻译,python)