FastAPI 教程翻译 - 用户指南 6 - 查询参数和字符串验证
FastAPI Tutorial - User Guide - Query Parameters and String Validations
FastAPI allows you to declare additional information and validation for your parameters.
FastAPI 允许您声明其他信息并验证参数。
Let’s take this application as example:
让我们以这个应用程序为例:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = None):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
The query parameter q
is of type str
, and by default is None
, so it is optional.
查询参数 q
的类型为 str
,默认值为 None
,因此它是可选的。
Additional validation
附加验证
We are going to enforce that even though q
is optional, whenever it is provided, it doesn’t exceed a length of 50 characters.
我们将强制执行验证,只要提供了 q
,它不能超过 50 个字符的长度,即使 q
是可选的。
Import Query
导入 Query
To achieve that, first import Query
from fastapi
:
为此,首先从 fastapi
导入 Query
:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(None, max_length=50)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
Use Query
as the default value
使用 Query
作为默认值
And now use it as the default value of your parameter, setting the parameter max_length
to 50:
现在,将其用作参数的默认值,将参数 max_length
设置为 50:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(None, max_length=50)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
As we have to replace the default value None
with Query(None)
, the first parameter to Query
serves the same purpose of defining that default value.
由于我们必须用 Query(None)
替换默认值 None
,因此 Query
的第一个参数是定义默认值。
So:
所以:
q: str = Query(None)
…makes the parameter optional, the same as:
…… 也可以使参数成为可选参数:
q: str = None
But it declares it explicitly as being a query parameter.
但是它明确地将其声明为查询参数。
And then, we can pass more parameters to Query
. In this case, the max_length
parameter that applies to strings:
然后,我们可以将更多参数传递给 Query
。在这种情况下,适用于字符串的 max_length
参数:
q: str = Query(None, max_length=50)
This will validate the data, show a clear error when the data is not valid, and document the parameter in the OpenAPI schema path operation.
这将验证数据,当数据无效时显示清楚的错误,并在 OpenAPI 模式路径操作中记录参数。
Add more validations
添加更多验证
You can also add a parameter min_length
:
您还可以添加参数 min_length
:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(None, min_length=3, max_length=50)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
Add regular expressions
添加正则表达式
You can define a regular expression that the parameter should match:
您可以定义参数应匹配的正则表达式:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(
q: str = Query(None, min_length=3, max_length=50, regex="^fixedquery$")
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
This specific regular expression checks that the received parameter value:
这个特定的正则表达式检查接收到的参数值:
^
: starts with the following characters, doesn’t have characters before. 以之后的字符开头,之前不匹配字符。fixedquery
: has the exact valuefixedquery
. 匹配fixedquery
字符串。$
: ends there, doesn’t have any more characters afterfixedquery
. 到此结束,在fixedquery
之后不匹配任何字符。
If you feel lost with all these “regular expression” ideas, don’t worry. They are a hard topic for many people. You can still do a lot of stuff without needing regular expressions yet.
如果您对所有这些正则表达式的想法感到迷茫,请不要担心。对于许多人来说,这是也是一个艰难的话题。您仍然可以做很多事情而无需正则表达式。
But whenever you need them and go and learn them, know that you can already use them directly in FastAPI.
但是,只要您需要它们并去学习它们,便知道您已经可以在 FastAPI 中直接使用它们。
Default values
默认值
The same way that you can pass None
as the first argument to be used as the default value, you can pass other values.
您可以将 None
作为第一个参数用作默认值,也可以传递其他值。
Let’s say that you want to declare the q
query parameter to have a min_length
of 3
, and to have a default value of "fixedquery"
:
假设您要声明 q
查询参数,使其 min_length
为 3
,并且默认值为 fixedquery
:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query("fixedquery", min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
Note
注意
Having a default value also makes the parameter optional.
具有默认值也会使该参数成为可选参数。
Make it required
必需
When we don’t need to declare more validations or metadata, we can make the q
query parameter required just by not declaring a default value, like:
当我们不需要声明更多的验证或元数据时,只需不声明默认值就可以使 q
参数成为必需,例如:
q: str
instead of:
代替:
q: str = None
But we are now declaring it with Query
, for example like:
但是我们现在用 Query
声明它,例如:
q: str = Query(None, min_length=3)
So, when you need to declare a value as required while using Query
, you can use ...
as the first argument:
因此,当您在使用 Query
时需要声明必需的值时,可以将 ...
作为第一个参数:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(..., min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
Info
信息
If you hadn’t seen that
...
before: it is a a special single value, it is part of Python and is called “Ellipsis”.如果您之前没有看过
...
:它是一个特殊的单一值,它是 Python的一部分,被称为『省略号』。
This will let FastAPI know that this parameter is required.
这将使 FastAPI
知道此参数是必需的。
Query parameter list / multiple values
查询参数列表 / 多个值
When you define a query parameter explicitly with Query
you can also declare it to receive a list of values, or said in other way, to receive multiple values.
当您使用 Query
显式定义查询参数时,您也可以声明它以接收值列表,或以其他方式表示要接收多个值。
For example, to declare a query parameter q
that can appear multiple times in the URL, you can write:
例如,要声明一个可以在 URL 中多次出现的查询参数 q
,您可以编写:
from typing import List
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: List[str] = Query(None)):
query_items = {"q": q}
return query_items
Then, with a URL like:
然后,输入如下网址:
http://localhost:8000/items/?q=foo&q=bar
you would receive the multiple q
query parameters’ values (foo
and bar
) in a Python list
inside your path operation function, in the function parameter q
.
您会在路径参数的路径操作函数内的 Python list
中收到多个 q
的查询参数值(foo
和 bar
)。
So, the response to that URL would be:
因此,对该 URL 的响应为:
{
"q": [
"foo",
"bar"
]
}
Tip
提示
To declare a query parameter with a type of
list
, like in the example above, you need to explicitly useQuery
, otherwise it would be interpreted as a request body.要声明类型为
list
的查询参数,如上例所示,您需要显式使用Query
,否则它将被解释为请求主体。
The interactive API docs will update accordingly, to allow multiple values:
交互式 API 文档将相应更新,以允许多个值:
Query parameter list / multiple values with defaults
查询参数列表 / 多个默认值
And you can also define a default list
of values if none are provided:
如果没有提供值,您还可以定义默认的 list
:
from typing import List
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: List[str] = Query(["foo", "bar"])):
query_items = {"q": q}
return query_items
If you go to:
如果您访问:
http://localhost:8000/items/
the default of q
will be: ["foo", "bar"]
and your response will be:
q
的默认值为:["foo", "bar"]
,您的响应为:
{
"q": [
"foo",
"bar"
]
}
Using list
使用 list
You can also use list
directly instead of List[str]
:
您也可以直接使用 list
代替 List[str]
:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: list = Query(None)):
query_items = {"q": q}
return query_items
Note
注意
Have in mind that in this case, FastAPI won’t check the contents of the list.
请记住,在这种情况下,FastAPI 将不会检查列表的内容。
For example,
List[int]
would check (and document) that the contents of the list are integers. Butlist
alone wouldn’t.例如,
List[int]
将检查(和记录)列表内容是否为整数。但是,单单list
则不会。
Declare more metadata
声明更多元数据
You can add more information about the parameter.
您可以添加有关该参数的更多信息。
That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools.
该信息将包含在生成的 OpenAPI 中,并由文档用户界面和外部工具使用。
Note
注意
Have in mind that different tools might have different levels of OpenAPI support.
请记住,不同的工具可能具有不同级别的 OpenAPI 支持。
Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development.
其中有些可能不会显示已声明的所有额外信息,尽管在大多数情况下,已经计划开发缺少的功能。
You can add a title
:
您可以添加 title
:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(None, title="Query string", min_length=3)):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
And a description
:
还有 description
:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(
q: str = Query(
None,
title="Query string",
description="Query string for the items to search in the database that have a good match",
min_length=3,
)
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
Alias parameters
别名参数
Imagine that you want the parameter to be item-query
.
假设您希望参数为 item-query
。
Like in:
像是:
http://127.0.0.1:8000/items/?item-query=foobaritems
But item-query
is not a valid Python variable name.
但是 item-query
不是有效的 Python 变量名称。
The closest would be item_query
.
最接近的是 item_query
。
But you still need it to be exactly item-query
…
但是您仍然需要它完全是 item-query
……
Then you can declare an alias
, and that alias is what will be used to find the parameter value:
然后可以声明一个 alias
,该别名将用于查找参数值:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(None, alias="item-query")):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
Deprecating parameters
弃用参数
Now let’s say you don’t like this parameter anymore.
现在,假设您不再喜欢此参数。
You have to leave it there a while because there are clients using it, but you want the docs to clearly show it as deprecated.
您必须将其保留一段时间,因为有许多客户在使用它,但是您希望文档将其清楚地显示为已弃用。
Then pass the parameter deprecated=True
to Query
:
然后将参数 deprecated=True
传递给 Query
:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(
q: str = Query(
None,
alias="item-query",
title="Query string",
description="Query string for the items to search in the database that have a good match",
min_length=3,
max_length=50,
regex="^fixedquery$",
deprecated=True,
)
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
The docs will show it like this:
该文档将显示如下:
Recap
回顾
You can declare additional validations and metadata for your parameters.
您可以为参数声明其他验证和元数据。
Generic validations and metadata:
通用验证和元数据:
alias
title
description
deprecated
Validations specific for strings:
特定于字符串的验证:
min_length
max_length
regex
In these examples you saw how to declare validations for str
values.
在这些示例中,您了解了如何声明对 str
值得验证。
See the next chapters to see how to declare validations for other types, like numbers.
请参阅下一章,了解如何声明对其他类型(例如数字)的验证。