网页
综合
更新时间 2026-11-14 05:19:58
Query Parameters - FastAPI
自动蜘蛛
fastapi.tiangolo.com
正文约 2840 字
Use the official FastAPI skill for your installed version. Install it from your project directory:
See Develop with AI.
When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters.
The query is the set of key-value pairs that go after the ? in a URL, separated by & characters.
For example, in the URL:
...the query parameters are:
As they are part of the URL, they are "naturally" strings.
But when you declare them with Python types (in the example above, as int), they are converted to that type and validated against it.
All the same processes that apply to path parameters also apply to query parameters:
As query parameters are not a fixed part of a path, they can be optional and can have default values.
In the example above they have default values of skip=0 and limit=10.
So, going to the URL:
would be the same as going to:
But if you go to, for example:
The parameter values in your function will be:
The same way, you can declare optional query parameters, by setting their default to None:
In this case, the function parameter q will be optional, and will be None by default.
Also notice that FastAPI is smart enough to notice that the path parameter item_id is a path parameter and q is not, so, it's a query parameter.
You can also declare bool types, and they will be converted:
In this case, if you go to:
or any other case variation (uppercase, first letter in uppercase, etc), your function will see the parameter short with a bool value of True.
Values such as 0, false, off, and no (including case variations) are converted to False.
If short is omitted, FastAPI uses its default value, which is False in this example.
An empty value (?short=) or an unrecognized value (for example, ?short=maybe) produces a 422 validation error.
You can declare multiple path parameters and query parameters at the same time, FastAPI knows which is which.
And you don't have to declare them in any specific order.
They will be detected by name:
When you declare a default value for non-path parameters (for now, we have only seen query parameters), then it is not required.
If you don't want to add a specific value but just make it optional, set the default as None.
But when you want to make a query parameter required, you can just not declare any default value:
Here the query parameter needy is a required query parameter of type str.
If you open in your browser a URL like:
...without adding the required parameter needy, you will see an error like:
As needy is a required parameter, you would need to set it in the URL:
And of course, you can define some parameters as required, some as having a default value, and some entirely optional:
In this case, there are 3 query parameters:
You could also use Enums the same way as with Path Parameters.
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。