FastAPI 教程翻译 - 用户指南 2 - 第一步
FastAPI Tutorial - User Guide - First Steps
The simplest FastAPI file could look like this:
最简单的 FastAPI 文件可能如下所示:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Copy that to a file main.py
.
将其复制到文件 main.py
中。
Run the live server:
运行实时服务器:
uvicorn main:app --reload
Note
注意
The command
uvicorn main:app
refers to:命令
uvicorn main:app
指的是:
main
: the filemain.py
(the Python “module”).
main
:文件main.py
(Python 的『模块』)。
app
: the object created inside ofmain.py
with the lineapp = FastAPI()
.
app
:在main.py
内部创建的对象,其中一行app = FastAPI()
。
--reload
: make the server restart after code changes. Only use for development.
--reload
:使服务器在代码更改后重新启动,仅用于开发。
You will see an output like:
您将看到如下的输出:
INFO: Started reloader process [17961]
INFO: Started server process [17962]
INFO: Waiting for application startup.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
That last line shows the URL where your app is being served, in your local machine.
最后一行显示在本地计算机中为您的应用提供服务的 URL。
Check it
检查
Open your browser at http://127.0.0.1:8000.
在浏览器中打开http://127.0.0.1:8000。
You will see the JSON response as:
您将看到如下的 JSON 响应:
{"message": "Hello World"}
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 提供):
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 提供):
OpenAPI
FastAPI generates a “schema” with all your API using the OpenAPI standard for defining APIs.
FastAPI 使用用于定义API的 OpenAPI 标准为您的所有 API 生成『模式』。
“Schema”
『模式』
A “schema” is a definition or description of something. Not the code that implements it, but just the abstract description.
『模式』是事物的定义或描述。不是实现它的代码,而是抽象描述。
API “schema”
API『模式』
In this case, OpenAPI is a specification that dictates how to define a schema of your API.
在这种情况下,OpenAPI 是规定如何定义 API 模式的规范。
This OpenAPI schema would include your API paths, the possible parameters they take, etc.
此 OpenAPI 模式将包括您的 API 路径,以及路径中包含的可能参数等。
Data “schema”
数据『模式』
The term “schema” might also refer to the shape of some data, like a JSON content.
术语『模式』也可能表示某些数据的形状,例如 JSON 内容。
In that case, it would mean the JSON attributes, and data types they have, etc.
在这种情况下,这将意味着 JSON 属性及其具有的数据类型,等等。
OpenAPI and JSON Schema
OpenAPI 和 JSON 模式
OpenAPI defines an API schema for your API. And that schema includes definitions (or “schemas”) of the data sent and received by your API using JSON Schema, the standard for JSON data schemas.
OpenAPI:为您的 API 定义了一个 API 模式。并且这个模式包含了 API 传输数据的定义和 API 接收数据的定义。
JSON模式:JSON 数据模式的标准。
Check the openapi.json
检查 openapi.json
If you are curious about how the raw OpenAPI schema looks like, it is just an automatically generated JSON with the descriptions of all your API.
原始 OpenAPI 模式只是一个自动生成的 JSON,其中包含所有 API 的描述。
You can see it directly at: http://127.0.0.1:8000/openapi.json.
如果您对它是什么样子感到好奇,您可以直接转到:http://127.0.0.1:8000/openapi.json。
It will show a JSON starting with something like:
它将会显示如下的 JSON:
{
"openapi": "3.0.2",
"info": {
"title": "FastAPI",
"version": "0.1.0"
},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
...
What is OpenAPI for
什么是 OpenAPI
This OpenAPI schema is what powers the 2 interactive documentation systems included.
此 OpenAPI 架构是为所包含的2个交互式文档提供支持的。
And there are dozens of alternatives, all based on OpenAPI. You could easily add any of those alternatives to your application built with FastAPI.
并且有数十种替代方案,全部基于 OpenAPI。您可以轻松地将这些替代方案中的任何一种添加到使用 FastAPI 构建的应用程序中。
You could also use it to generate code automatically, for clients that communicate with your API. For example, frontend, mobile or IoT applications.
您还可以使用它为与 API 通信的客户端自动生成代码。例如:前端,移动或物联网应用程序。
Recap, step by step
回顾,逐步的
Step 1: import FastAPI
步骤1:导入 FastAPI
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
FastAPI
is a Python class that provides all the functionality for your API.
FastAPI
是一个 Python 类,可为您的 API 提供所有功能。
Technical Details
技术细节
FastAPI
is a class that inherits directly fromStarlette
.
FastAPI
是直接继承自Starlette
的类。You can use all the Starlette functionality with
FastAPI
too.您也可以将所有 Starlette 功能与
FastAPI
一起使用。
Step 2: create a FastAPI
“instance”
步骤2:创建一个 FastAPI
『实例』
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Here the app
variable will be an “instance” of the class FastAPI
.
这里的 app
变量将是 FastAPI
类的『实例』。
This will be the main point of interaction to create all your API.
这将是创建所有 API 的主要交互点。
This app
is the same one referred by uvicorn
in the command:
这个 app
与 uvicorn
在命令中引用的 app
是同一个:
uvicorn main:app --reload
If you create your app like:
如果您像这样创建应用程序:
from fastapi import FastAPI
my_awesome_api = FastAPI()
@my_awesome_api.get("/")
async def root():
return {"message": "Hello World"}
And put it in a file main.py
, then you would call uvicorn
like:
并将其放在文件 main.py
中,然后您可以如下启动 uvicorn
:
uvicorn main:my_awesome_api --reload
Step 3: create a path operation
步骤3:创建路径操作
Path
路径
“Path” here refers to the last part of the URL starting from the first /
.
这里的『路径』是指 URL 的最后一部分,从第一个 /
开始。
So, in a URL like:
因此,在如下网址中:
https://example.com/items/foo
…the path would be:
…… 路径将是:
/items/foo
Info
信息
A “path” is also commonly called an “endpoint” or a “route”.
『路径』通常也称为『端点』或『路由』。
Building an API, the “path” is the main way to separate “concerns” and “resources”.
构建 API 时,『路径』是分离『关注点』和『资源』的主要方法。
Operation
操作
“Operation” here refers to one of the HTTP “methods”.
这里的『操作』是指 HTTP『方法』之一。
One of:
如:
POST
GET
PUT
DELETE
…and the more exotic ones:
…… 还有更少见的一些方法:
OPTIONS
HEAD
PATCH
TRACE
In the HTTP protocol, you can communicate to each path using one (or more) of these “methods”.
在 HTTP 协议中,您可以使用这些『方法』中的一个(或多个)与每个路径通信。
When building APIs, you normally use these specific HTTP methods to perform a specific action.
构建 API 时,通常使用这些特定的 HTTP 方法来执行特定的操作。
Normally you use:
通常,您可以使用:
POST
:to create data
POST
:创建数据。GET
:to read data
GET
:读取数据。PUT
:to update data
PUT
:更新数据。DELETE
:to delete data
DELETE
:删除数据。
So, in OpenAPI, each of the HTTP methods is called an “operation”.
因为,在 OpenAPI 中,每个 HTTP 方法都称为『操作』。
We are going to call them “operations” too.
所以,在以后的内容中,我们也把它称为操作。
Define a path operation function
定义路径操作函数
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
The @app.get("/")
tells FastAPI that the function right below is in charge of handling requests that go to:
@app.get("/")
告诉 FastAPI ,下面的函数负责处理收到的请求:
-
the path
/
路径
/
-
using a
get
operation使用
get
操作
@decorator
Info
@decorator
信息That
@something
syntax in Python is called a “decorator”.Python中的
@something
语法称为『装饰器』。You put it on top of a function. Like a pretty decorative hat (I guess that’s where the term came from).
您将其放在函数之上。就像一顶漂亮的装饰帽(我想这是这个术语的来源)。
A “decorator” takes the function below and does something with it.
『装饰器』采用下面的功能并对其进行处理。
In our case, this decorator tells FastAPI that the function below corresponds to the path
/
with an operationget
.在我们的例子中,这个装饰器告诉 FastAPI,下面的视图函数将会响应路径
/
中的操作get
。It is the “path operation decorator”.
这就是『路由操作装饰器』。
You can also use the other operations:
您还可以使用其他操作:
@app.post()
@app.put()
@app.delete()
And the more exotic ones:
还有些更少见的:
@app.options()
@app.head()
@app.patch()
@app.trace()
Tip
提示
You are free to use each operation (HTTP method) as you wish.
您可以随意使用每个操作(HTTP 方法)。
FastAPI doesn’t enforce any specific meaning.
FastAPI 没有强制任何特定含义。
The information here is presented as a guideline, not a requirement.
此处提供的信息仅供参考,并非必需。
For example, when using GraphQL you normally perform all the actions using only
post
.例如,当使用 GraphQL 时,通常仅使用
post
执行所有动作。
Step 4: define the path operation function
步骤4:定义路径操作函数
This is our “path operation function”:
这是我们的『路径操作函数』:
-
path: is
/
.路径:
/
。 -
operation: is
get
.操作:
get
。 -
function: is the function below the “decorator” (below
@app.get("/")
).函数:是『装饰器』下方的函数(在
@app.get("/")
下面)。
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
This is a Python function.
这是一个 Python 函数。
It will be called by FastAPI whenever it receives a request to the URL “/
” using GET
.
每当它通过 GET
收到对 URL『/
』的请求时,它将由 FastAPI 调用。
In this case, it is an async
function.
在这种情况下,它是一个 async
函数。
You could also define it as a normal function instead of async def
:
您也可以将其定义为常规函数,而不是 async def
:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello World"}
Note
注意
If you don’t know the difference, check the Async: “In a hurry?”.
如果您不知道它们之间的区别,请查看 Concurrency and async / await: “In a hurry?”.
Step 5: return the content
步骤5:返回内容
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
You can return a dict
, list
, singular values as str
, int
, etc.
您可以返回 dict
,list
,单数形式的 str
,int
等。
You can also return Pydantic models (you’ll see more about that later).
您还可以返回 Pydantic 模型(稍后会看到更多信息)。
There are many other objects and models that will be automatically converted to JSON (including ORMs, etc). Try using your favorite ones, it’s highly probable that they are already supported.
还有许多其他对象和模型将自动转换为 JSON(包括 ORM 等)。尝试使用您最喜欢的方法,很有可能已经支持它们了。
Recap
回顾
-
Import
FastAPI
.导入
FastAPI
。 -
Create an
app
instance.创建
app
实例。 -
Write a path operation decorator (like
@app.get("/")
).编写路径操作修饰符(例如
@app.get("/")
)。 -
Write a path operation function (like
def root(): ...
above).编写路径操作函数(如上面的
def root(): ...
)。 -
Run the development server (like
uvicorn main:app --reload
).运行开发服务器(如
uvicorn main:app --reload
)。