You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das <abbrtitle='Zeichenfolge, die einen Wert direkt darstellt, etwa 1, "hallowelt", True, None'>Literal</abbr> `...` setzen:
Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, <ahref="https://docs.python.org/3/library/constants.html#Ellipsis"class="external-link"target="_blank">Teil von Python und wird „Ellipsis“ genannt</a> (Deutsch: Ellipse).
327
-
328
-
Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist.
329
-
330
-
///
331
-
332
-
Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist.
333
-
334
318
### Erforderlich, kann `None` sein
335
319
336
320
Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erforderlich ist. Das zwingt Clients, den Wert zu senden, selbst wenn er `None` ist.
The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required.
9
+
The query parameter `q` is of type `str| None`, that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required.
10
10
11
11
/// note
12
12
13
13
FastAPI will know that the value of `q` is not required because of the default value `= None`.
14
14
15
-
The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors.
15
+
Having `str | None` will allow your editor to give you better support and detect errors.
16
16
17
17
///
18
18
@@ -25,29 +25,9 @@ We are going to enforce that even though `q` is optional, whenever it is provide
25
25
To achieve that, first import:
26
26
27
27
*`Query` from `fastapi`
28
-
*`Annotated` from `typing` (or from `typing_extensions` in Python below 3.9)
28
+
*`Annotated` from `typing`
29
29
30
-
//// tab | Python 3.10+
31
-
32
-
In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`.
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*.
@@ -201,7 +150,7 @@ This will validate the data, show a clear error when the data is not valid, and
201
150
202
151
Keep in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`.
203
152
204
-
Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent.
153
+
Instead, use the actual default value of the function parameter. Otherwise, it would be inconsistent.
205
154
206
155
For example, this is not allowed:
207
156
@@ -255,7 +204,7 @@ This specific regular expression pattern checks that the received parameter valu
255
204
256
205
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.
257
206
258
-
But whenever you need them and go and learn them, know that you can already use them directly in **FastAPI**.
207
+
Now you know that whenever you need themyou can use them in **FastAPI**.
259
208
260
209
### Pydantic v1 `regex` instead of `pattern`
261
210
@@ -296,23 +245,15 @@ q: str
296
245
instead of:
297
246
298
247
```Python
299
-
q: Union[str, None]=None
248
+
q: str|None=None
300
249
```
301
250
302
251
But we are now declaring it with `Query`, for example like:
If you hadn't seen that `...` before: it is a special single value, it is <ahref="https://docs.python.org/3/library/constants.html#Ellipsis"class="external-link"target="_blank">part of Python and is called "Ellipsis"</a>.
333
-
334
-
It is used by Pydantic and FastAPI to explicitly declare that a value is required.
335
-
336
-
///
337
-
338
-
This will let **FastAPI** know that this parameter is required.
339
-
340
265
### Required, can be `None`
341
266
342
267
You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`.
343
268
344
-
To do that, you can declare that `None` is a valid type but still use `...` as the default:
269
+
To do that, you can declare that `None` is a valid type but simply do not declare a default value:
Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <ahref="https://docs.pydantic.dev/2.3/usage/models/#required-optional-fields"class="external-link"target="_blank">Required fields</a>.
351
-
352
-
///
353
-
354
-
/// tip
355
-
356
-
Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`.
357
-
358
-
///
359
-
360
273
## Query parameter list / multiple values
361
274
362
275
When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in another way, to receive multiple values.
@@ -396,7 +309,7 @@ The interactive API docs will update accordingly, to allow multiple values:
396
309
397
310
### Query parameter list / multiple values with defaults
398
311
399
-
And you can also define a default `list` of values if none are provided:
312
+
You can also define a default `list` of values if none are provided:
Si no habías visto eso `...` antes: es un valor especial único, es <ahref="https://docs.python.org/3/library/constants.html#Ellipsis"class="external-link"target="_blank">parte de Python y se llama "Ellipsis"</a>.
333
-
334
-
Se usa por Pydantic y FastAPI para declarar explícitamente que un valor es requerido.
335
-
336
-
///
337
-
338
-
Esto le permitirá a **FastAPI** saber que este parámetro es requerido.
339
-
340
324
### Requerido, puede ser `None`
341
325
342
326
Puedes declarar que un parámetro puede aceptar `None`, pero que aún así es requerido. Esto obligaría a los clientes a enviar un valor, incluso si el valor es `None`.
Если вы ранее не сталкивались с `...`: это специальное значение, <ahref="https://docs.python.org/3/library/constants.html#Ellipsis"class="external-link"target="_blank">часть языка Python и называется "Ellipsis"</a>.
303
-
304
-
Используется в Pydantic и FastAPI для определения, что значение требуется обязательно.
305
-
306
-
///
307
-
308
-
Таким образом, **FastAPI** определяет, что параметр является обязательным.
309
-
310
294
### Обязательный параметр с `None`
311
295
312
296
Вы можете определить, что параметр может принимать `None`, но всё ещё является обязательным. Это может потребоваться для того, чтобы пользователи явно указали параметр, даже если его значение будет `None`.
@@ -321,18 +305,6 @@ Pydantic, мощь которого используется в FastAPI для
321
305
322
306
///
323
307
324
-
### Использование Pydantic's `Required` вместо Ellipsis (`...`)
325
-
326
-
Если вас смущает `...`, вы можете использовать `Required` из Pydantic:
Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`.
333
-
334
-
///
335
-
336
308
## Множество значений для query-параметра
337
309
338
310
Для query-параметра `Query` можно указать, что он принимает список значений (множество значений).
0 commit comments