This commit is contained in:
JONEMI19 2023-07-08 10:26:53 +00:00
parent 4ee9c097a2
commit c020f9c8a9
3 changed files with 62 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 KiB

View File

@ -223,3 +223,45 @@ In this case, there are 3 query parameters:
!!! tip
You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}.
## Free Form Query Parameters
Sometimes you want to receive some query parameters, but you don't know in advance what they will be. **FastAPI** supports this case too.
=== "Python 3.10+"
```Python hl_lines="8"
{!> ../../../docs_src/query_params/tutorial007_py310.py!}
```
And when you open your browser at <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>, you will that OpenAPI supports this too:
<img src="/img/tutorial/path-params/image01.png">
However, since the query parameters are decaled in the request as
```
http://127.0.0.1:8000/query/mixed-type-params?query=1&foo=bar&foo=baz
```
**FastAPI** greedily adds all the query parameters to every `Query` argument for which it is valid. The above request will be parsed as:
```Python
{
"query": 1,
"string_mapping": {
"query": "1",
"foo": "baz"
},
"mapping_query_int": {
"query": 1
},
"sequence_mapping_queries": {
"query": [
"1"
],
"foo": []
}
}
```
As you can see the `query` parameter is added to every `Query` argument for which it is valid. This is because **FastAPI** does not know which `Query` argument you want to add the `query` parameter to, and `1` validates as an `int`, `str`, and `List[str]`. `foo` is only added to the `string_mapping` and `sequence_mapping_queries` arguments because it is not a valid `int`.

View File

@ -0,0 +1,20 @@
from typing import Mapping, List
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/query/mixed-type-params")
def get_mixed_mapping_mixed_type_query_params(
query: int = Query(),
mapping_query_str: Mapping[str, str] = Query({}),
mapping_query_int: Mapping[str, int] = Query({}),
sequence_mapping_queries: Mapping[str, List[int]] = Query({}),
):
return {
"query":query,
"string_mapping": mapping_query_str,
"mapping_query_int": mapping_query_int,
"sequence_mapping_queries": sequence_mapping_queries
}