0
# Request Parameters
1
2
FastAPI provides type-safe parameter declaration functions for handling different types of request data including path parameters, query parameters, headers, cookies, request bodies, form data, and file uploads. These functions enable automatic validation, serialization, and OpenAPI documentation generation.
3
4
## Capabilities
5
6
### Path Parameters
7
8
Declare path parameters extracted from the URL path with automatic type conversion and validation.
9
10
```python { .api }
11
def Path(
12
default: Any = ...,
13
*,
14
alias: str = None,
15
title: str = None,
16
description: str = None,
17
gt: float = None,
18
ge: float = None,
19
lt: float = None,
20
le: float = None,
21
min_length: int = None,
22
max_length: int = None,
23
regex: str = None,
24
example: Any = None,
25
examples: dict = None,
26
openapi_examples: dict = None,
27
deprecated: bool = None,
28
include_in_schema: bool = True,
29
**extra: Any,
30
) -> Any:
31
"""
32
Declare a path parameter with validation constraints.
33
34
Parameters:
35
- default: Default value (use ... for required parameters)
36
- alias: Alternative name for the parameter in OpenAPI
37
- title: Title for documentation
38
- description: Description for documentation
39
- gt: Greater than validation for numbers
40
- ge: Greater than or equal validation for numbers
41
- lt: Less than validation for numbers
42
- le: Less than or equal validation for numbers
43
- min_length: Minimum length for strings
44
- max_length: Maximum length for strings
45
- regex: Regular expression pattern for string validation
46
- example: Example value for documentation
47
- examples: Multiple examples for documentation
48
- deprecated: Mark parameter as deprecated
49
- include_in_schema: Include in OpenAPI schema
50
51
Returns:
52
Parameter declaration for use in function signatures
53
"""
54
```
55
56
### Query Parameters
57
58
Declare query parameters from URL query strings with optional defaults and validation.
59
60
```python { .api }
61
def Query(
62
default: Any = Undefined,
63
*,
64
alias: str = None,
65
title: str = None,
66
description: str = None,
67
gt: float = None,
68
ge: float = None,
69
lt: float = None,
70
le: float = None,
71
min_length: int = None,
72
max_length: int = None,
73
regex: str = None,
74
example: Any = None,
75
examples: dict = None,
76
openapi_examples: dict = None,
77
deprecated: bool = None,
78
include_in_schema: bool = True,
79
**extra: Any,
80
) -> Any:
81
"""
82
Declare a query parameter with validation constraints.
83
84
Parameters:
85
Same as Path() but with optional default values.
86
Use default=Undefined for required query parameters.
87
88
Returns:
89
Parameter declaration for use in function signatures
90
"""
91
```
92
93
### Header Parameters
94
95
Declare HTTP header parameters with automatic conversion and validation.
96
97
```python { .api }
98
def Header(
99
default: Any = Undefined,
100
*,
101
alias: str = None,
102
convert_underscores: bool = True,
103
title: str = None,
104
description: str = None,
105
gt: float = None,
106
ge: float = None,
107
lt: float = None,
108
le: float = None,
109
min_length: int = None,
110
max_length: int = None,
111
regex: str = None,
112
example: Any = None,
113
examples: dict = None,
114
openapi_examples: dict = None,
115
deprecated: bool = None,
116
include_in_schema: bool = True,
117
**extra: Any,
118
) -> Any:
119
"""
120
Declare an HTTP header parameter with validation constraints.
121
122
Parameters:
123
- convert_underscores: Convert underscores to hyphens in header names
124
- Other parameters same as Path() and Query()
125
126
Returns:
127
Parameter declaration for use in function signatures
128
"""
129
```
130
131
### Cookie Parameters
132
133
Declare HTTP cookie parameters with validation and type conversion.
134
135
```python { .api }
136
def Cookie(
137
default: Any = Undefined,
138
*,
139
alias: str = None,
140
title: str = None,
141
description: str = None,
142
gt: float = None,
143
ge: float = None,
144
lt: float = None,
145
le: float = None,
146
min_length: int = None,
147
max_length: int = None,
148
regex: str = None,
149
example: Any = None,
150
examples: dict = None,
151
openapi_examples: dict = None,
152
deprecated: bool = None,
153
include_in_schema: bool = True,
154
**extra: Any,
155
) -> Any:
156
"""
157
Declare an HTTP cookie parameter with validation constraints.
158
159
Parameters:
160
Same as Query() and Header() without convert_underscores.
161
162
Returns:
163
Parameter declaration for use in function signatures
164
"""
165
```
166
167
### Request Body
168
169
Declare request body parameters with JSON serialization and validation via Pydantic models.
170
171
```python { .api }
172
def Body(
173
default: Any = Undefined,
174
*,
175
embed: bool = None,
176
media_type: str = "application/json",
177
alias: str = None,
178
title: str = None,
179
description: str = None,
180
gt: float = None,
181
ge: float = None,
182
lt: float = None,
183
le: float = None,
184
min_length: int = None,
185
max_length: int = None,
186
regex: str = None,
187
example: Any = None,
188
examples: dict = None,
189
openapi_examples: dict = None,
190
deprecated: bool = None,
191
include_in_schema: bool = True,
192
**extra: Any,
193
) -> Any:
194
"""
195
Declare a request body parameter with validation constraints.
196
197
Parameters:
198
- embed: Embed single values in a JSON object
199
- media_type: Media type for the request body
200
- Other parameters same as other parameter functions
201
202
Returns:
203
Parameter declaration for use in function signatures
204
"""
205
```
206
207
### Form Data
208
209
Declare form data parameters for application/x-www-form-urlencoded content.
210
211
```python { .api }
212
def Form(
213
default: Any = Undefined,
214
*,
215
media_type: str = "application/x-www-form-urlencoded",
216
alias: str = None,
217
title: str = None,
218
description: str = None,
219
gt: float = None,
220
ge: float = None,
221
lt: float = None,
222
le: float = None,
223
min_length: int = None,
224
max_length: int = None,
225
regex: str = None,
226
example: Any = None,
227
examples: dict = None,
228
openapi_examples: dict = None,
229
deprecated: bool = None,
230
include_in_schema: bool = True,
231
**extra: Any,
232
) -> Any:
233
"""
234
Declare a form data parameter with validation constraints.
235
236
Parameters:
237
- media_type: Media type for form data (default: application/x-www-form-urlencoded)
238
- Other parameters same as other parameter functions
239
240
Returns:
241
Parameter declaration for use in function signatures
242
"""
243
```
244
245
### File Upload
246
247
Declare file upload parameters for multipart/form-data content with UploadFile objects.
248
249
```python { .api }
250
def File(
251
default: Any = Undefined,
252
*,
253
media_type: str = "multipart/form-data",
254
alias: str = None,
255
title: str = None,
256
description: str = None,
257
gt: float = None,
258
ge: float = None,
259
lt: float = None,
260
le: float = None,
261
min_length: int = None,
262
max_length: int = None,
263
regex: str = None,
264
example: Any = None,
265
examples: dict = None,
266
openapi_examples: dict = None,
267
deprecated: bool = None,
268
include_in_schema: bool = True,
269
**extra: Any,
270
) -> Any:
271
"""
272
Declare a file upload parameter with validation constraints.
273
274
Parameters:
275
- media_type: Media type for file uploads (default: multipart/form-data)
276
- Other parameters same as other parameter functions
277
278
Returns:
279
Parameter declaration for use in function signatures
280
"""
281
```
282
283
## Usage Examples
284
285
### Path Parameters
286
287
```python
288
from fastapi import FastAPI, Path
289
290
app = FastAPI()
291
292
@app.get("/items/{item_id}")
293
def get_item(
294
item_id: int = Path(..., title="Item ID", description="The ID of the item", ge=1)
295
):
296
return {"item_id": item_id}
297
298
@app.get("/users/{user_id}/posts/{post_id}")
299
def get_user_post(
300
user_id: int = Path(..., ge=1),
301
post_id: int = Path(..., ge=1, le=1000)
302
):
303
return {"user_id": user_id, "post_id": post_id}
304
```
305
306
### Query Parameters
307
308
```python
309
from fastapi import FastAPI, Query
310
from typing import Optional, List
311
312
app = FastAPI()
313
314
@app.get("/items/")
315
def read_items(
316
skip: int = Query(0, ge=0, description="Number of items to skip"),
317
limit: int = Query(10, ge=1, le=100, description="Number of items to return"),
318
q: Optional[str] = Query(None, min_length=3, max_length=50, description="Search query"),
319
tags: List[str] = Query([], description="Filter by tags")
320
):
321
return {"skip": skip, "limit": limit, "q": q, "tags": tags}
322
323
# Multiple query parameters with the same name
324
@app.get("/items/search")
325
def search_items(category: List[str] = Query(..., description="Categories to search")):
326
return {"categories": category}
327
```
328
329
### Header Parameters
330
331
```python
332
from fastapi import FastAPI, Header
333
from typing import Optional
334
335
app = FastAPI()
336
337
@app.get("/items/")
338
def read_items(
339
user_agent: Optional[str] = Header(None),
340
x_token: str = Header(..., description="Authentication token"),
341
accept_language: Optional[str] = Header(None, convert_underscores=True)
342
):
343
return {
344
"User-Agent": user_agent,
345
"X-Token": x_token,
346
"Accept-Language": accept_language
347
}
348
```
349
350
### Cookie Parameters
351
352
```python
353
from fastapi import FastAPI, Cookie
354
from typing import Optional
355
356
app = FastAPI()
357
358
@app.get("/items/")
359
def read_items(
360
session_id: Optional[str] = Cookie(None),
361
ads_id: Optional[str] = Cookie(None)
362
):
363
return {"session_id": session_id, "ads_id": ads_id}
364
```
365
366
### Request Body with Pydantic Models
367
368
```python
369
from fastapi import FastAPI, Body
370
from pydantic import BaseModel
371
from typing import Optional
372
373
app = FastAPI()
374
375
class Item(BaseModel):
376
name: str
377
description: Optional[str] = None
378
price: float
379
tax: Optional[float] = None
380
381
class User(BaseModel):
382
username: str
383
email: str
384
385
@app.post("/items/")
386
def create_item(item: Item):
387
return item
388
389
@app.put("/items/{item_id}")
390
def update_item(
391
item_id: int,
392
item: Item,
393
user: User,
394
importance: int = Body(..., gt=0, description="Item importance level")
395
):
396
return {"item_id": item_id, "item": item, "user": user, "importance": importance}
397
398
# Single value in body
399
@app.post("/items/{item_id}/priority")
400
def set_priority(
401
item_id: int,
402
priority: int = Body(..., embed=True, ge=1, le=5)
403
):
404
return {"item_id": item_id, "priority": priority}
405
```
406
407
### Form Data
408
409
```python
410
from fastapi import FastAPI, Form
411
412
app = FastAPI()
413
414
@app.post("/login/")
415
def login(
416
username: str = Form(..., min_length=3),
417
password: str = Form(..., min_length=8)
418
):
419
return {"username": username}
420
421
@app.post("/contact/")
422
def contact(
423
name: str = Form(...),
424
email: str = Form(..., regex=r'^[^@]+@[^@]+\.[^@]+$'),
425
message: str = Form(..., min_length=10, max_length=1000)
426
):
427
return {"name": name, "email": email, "message": message}
428
```
429
430
### File Upload
431
432
```python
433
from fastapi import FastAPI, File, UploadFile, Form
434
from typing import List
435
436
app = FastAPI()
437
438
@app.post("/upload/")
439
def upload_file(file: UploadFile = File(...)):
440
return {"filename": file.filename, "content_type": file.content_type}
441
442
@app.post("/upload-multiple/")
443
def upload_multiple_files(files: List[UploadFile] = File(...)):
444
return {"filenames": [file.filename for file in files]}
445
446
@app.post("/upload-with-form/")
447
def upload_with_form_data(
448
file: UploadFile = File(...),
449
name: str = Form(...),
450
description: str = Form(...)
451
):
452
return {
453
"filename": file.filename,
454
"name": name,
455
"description": description
456
}
457
458
# File as bytes
459
@app.post("/upload-bytes/")
460
def upload_file_bytes(file: bytes = File(...)):
461
return {"file_size": len(file)}
462
```
463
464
### Combined Parameters
465
466
```python
467
from fastapi import FastAPI, Path, Query, Header, Cookie, Body, Form, File, UploadFile
468
from pydantic import BaseModel
469
from typing import Optional
470
471
app = FastAPI()
472
473
class Metadata(BaseModel):
474
title: str
475
description: Optional[str] = None
476
477
@app.post("/items/{item_id}/process")
478
def process_item(
479
# Path parameter
480
item_id: int = Path(..., ge=1),
481
482
# Query parameters
483
force: bool = Query(False),
484
notify_users: bool = Query(True),
485
486
# Headers
487
user_agent: Optional[str] = Header(None),
488
x_api_key: str = Header(...),
489
490
# Cookies
491
session_id: Optional[str] = Cookie(None),
492
493
# Request body
494
metadata: Metadata,
495
priority: int = Body(..., ge=1, le=5),
496
497
# Form data and file
498
notes: str = Form(...),
499
attachment: Optional[UploadFile] = File(None)
500
):
501
return {
502
"item_id": item_id,
503
"force": force,
504
"notify_users": notify_users,
505
"user_agent": user_agent,
506
"session_id": session_id,
507
"metadata": metadata,
508
"priority": priority,
509
"notes": notes,
510
"attachment": attachment.filename if attachment else None
511
}
512
```