pypi-fastapi

Description
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-fastapi@0.116.0

request-parameters.md docs/

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