or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

api-routing.mdbackground-tasks.mdcore-application.mddependency-injection.mdexception-handling.mdfile-handling.mdindex.mdparameter-declaration.mdrequest-response.mdwebsocket-support.md

parameter-declaration.mddocs/

0

# Parameter Declaration

1

2

FastAPI's parameter declaration system provides functions for declaring and validating different types of request parameters with rich validation constraints, automatic type conversion, and OpenAPI schema generation. All parameter functions support extensive validation options through Pydantic.

3

4

## Capabilities

5

6

### Path Parameters

7

8

Function for declaring path parameters extracted from URL path segments with validation constraints.

9

10

```python { .api }

11

def Path(

12

default: Any = ...,

13

*,

14

default_factory: Union[Callable[[], Any], None] = _Unset,

15

alias: Optional[str] = None,

16

alias_priority: Union[int, None] = _Unset,

17

validation_alias: Union[str, None] = None,

18

serialization_alias: Union[str, None] = None,

19

title: Optional[str] = None,

20

description: Optional[str] = None,

21

gt: Optional[float] = None,

22

ge: Optional[float] = None,

23

lt: Optional[float] = None,

24

le: Optional[float] = None,

25

min_length: Optional[int] = None,

26

max_length: Optional[int] = None,

27

pattern: Optional[str] = None,

28

regex: Optional[str] = None, # Deprecated: use pattern instead

29

discriminator: Union[str, None] = None,

30

strict: Union[bool, None] = _Unset,

31

multiple_of: Union[float, None] = None,

32

allow_inf_nan: Union[bool, None] = None,

33

max_digits: Union[int, None] = None,

34

decimal_places: Union[int, None] = None,

35

example: Any = Undefined,

36

examples: Optional[List[Any]] = None,

37

openapi_examples: Optional[Dict[str, Example]] = None,

38

deprecated: Optional[bool] = None,

39

include_in_schema: bool = True,

40

json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,

41

**extra: Any

42

) -> Any:

43

"""

44

Declare a path parameter with validation constraints.

45

46

Parameters:

47

- default: Default value (use ... for required parameters)

48

- default_factory: Callable to generate default value (not applicable for Path)

49

- alias: Alternative parameter name in OpenAPI schema

50

- alias_priority: Priority for alias resolution

51

- validation_alias: Alias used for validation

52

- serialization_alias: Alias used for serialization

53

- title: Parameter title for OpenAPI documentation

54

- description: Parameter description for OpenAPI documentation

55

- gt: Value must be greater than this number

56

- ge: Value must be greater than or equal to this number

57

- lt: Value must be less than this number

58

- le: Value must be less than or equal to this number

59

- min_length: Minimum string length (for string parameters)

60

- max_length: Maximum string length (for string parameters)

61

- pattern: Regular expression pattern for string validation

62

- regex: Regular expression pattern (deprecated, use pattern instead)

63

- discriminator: Field name for discriminating tagged union types

64

- strict: Enable strict validation mode

65

- multiple_of: Value must be a multiple of this number

66

- allow_inf_nan: Allow infinite and NaN values for floats

67

- max_digits: Maximum number of digits for Decimal values

68

- decimal_places: Maximum decimal places for Decimal values

69

- example: Example value for OpenAPI documentation

70

- examples: List of example values for OpenAPI documentation

71

- openapi_examples: Dict of OpenAPI example objects

72

- deprecated: Mark parameter as deprecated in OpenAPI

73

- include_in_schema: Include parameter in OpenAPI schema

74

- json_schema_extra: Additional JSON schema properties

75

"""

76

```

77

78

### Query Parameters

79

80

Function for declaring query parameters from URL query string with validation constraints.

81

82

```python { .api }

83

def Query(

84

default: Any = Undefined,

85

*,

86

alias: Optional[str] = None,

87

title: Optional[str] = None,

88

description: Optional[str] = None,

89

gt: Optional[float] = None,

90

ge: Optional[float] = None,

91

lt: Optional[float] = None,

92

le: Optional[float] = None,

93

min_length: Optional[int] = None,

94

max_length: Optional[int] = None,

95

pattern: Optional[str] = None,

96

example: Any = Undefined,

97

examples: Optional[List[Any]] = None,

98

deprecated: Optional[bool] = None,

99

include_in_schema: bool = True,

100

json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,

101

**extra: Any

102

) -> Any:

103

"""

104

Declare a query parameter with validation constraints.

105

106

Parameters: Same as Path(), used for URL query string parameters.

107

Special behaviors:

108

- Supports list values for repeated parameters (?tags=red&tags=blue)

109

- Optional by default (default=None) unless explicitly required

110

- Automatically converts string values to specified types

111

"""

112

```

113

114

### Header Parameters

115

116

Function for declaring HTTP header parameters with automatic case conversion and validation.

117

118

```python { .api }

119

def Header(

120

default: Any = Undefined,

121

*,

122

alias: Optional[str] = None,

123

title: Optional[str] = None,

124

description: Optional[str] = None,

125

gt: Optional[float] = None,

126

ge: Optional[float] = None,

127

lt: Optional[float] = None,

128

le: Optional[float] = None,

129

min_length: Optional[int] = None,

130

max_length: Optional[int] = None,

131

regex: Optional[str] = None,

132

example: Any = Undefined,

133

examples: Optional[List[Any]] = None,

134

deprecated: Optional[bool] = None,

135

include_in_schema: bool = True,

136

json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,

137

convert_underscores: bool = True,

138

**extra: Any

139

) -> Any:

140

"""

141

Declare a header parameter with validation constraints.

142

143

Parameters: Same as Path(), plus:

144

- convert_underscores: Convert underscores to hyphens in header names

145

(user_agent becomes User-Agent)

146

147

Special behaviors:

148

- Header names are case-insensitive

149

- Supports list values for headers with multiple values

150

- Automatic conversion of underscore parameter names to hyphenated header names

151

"""

152

```

153

154

### Cookie Parameters

155

156

Function for declaring HTTP cookie parameters with validation.

157

158

```python { .api }

159

def Cookie(

160

default: Any = Undefined,

161

*,

162

alias: Optional[str] = None,

163

title: Optional[str] = None,

164

description: Optional[str] = None,

165

gt: Optional[float] = None,

166

ge: Optional[float] = None,

167

lt: Optional[float] = None,

168

le: Optional[float] = None,

169

min_length: Optional[int] = None,

170

max_length: Optional[int] = None,

171

regex: Optional[str] = None,

172

example: Any = Undefined,

173

examples: Optional[List[Any]] = None,

174

deprecated: Optional[bool] = None,

175

include_in_schema: bool = True,

176

json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,

177

**extra: Any

178

) -> Any:

179

"""

180

Declare a cookie parameter with validation constraints.

181

182

Parameters: Same as Path().

183

Special behaviors:

184

- Reads values from HTTP cookies

185

- Optional by default

186

- Automatic type conversion from string cookie values

187

"""

188

```

189

190

### Request Body Parameters

191

192

Function for declaring request body parameters with content type specification and validation.

193

194

```python { .api }

195

def Body(

196

default: Any = Undefined,

197

*,

198

embed: bool = False,

199

media_type: str = "application/json",

200

alias: Optional[str] = None,

201

title: Optional[str] = None,

202

description: Optional[str] = None,

203

gt: Optional[float] = None,

204

ge: Optional[float] = None,

205

lt: Optional[float] = None,

206

le: Optional[float] = None,

207

min_length: Optional[int] = None,

208

max_length: Optional[int] = None,

209

regex: Optional[str] = None,

210

example: Any = Undefined,

211

examples: Optional[List[Any]] = None,

212

deprecated: Optional[bool] = None,

213

include_in_schema: bool = True,

214

json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,

215

**extra: Any

216

) -> Any:

217

"""

218

Declare a request body parameter with validation constraints.

219

220

Parameters: Same as Path(), plus:

221

- embed: Embed single values in JSON object instead of using value directly

222

- media_type: Expected media type for the request body

223

224

Special behaviors:

225

- Reads from request body instead of URL/headers

226

- Supports JSON, form data, and other content types

227

- Can be combined with other Body() parameters for complex payloads

228

- When embed=True, wraps single values: {"value": <actual_value>}

229

"""

230

```

231

232

### Form Data Parameters

233

234

Function for declaring form data parameters for multipart/form-data and application/x-www-form-urlencoded requests.

235

236

```python { .api }

237

def Form(

238

default: Any = Undefined,

239

*,

240

media_type: str = "application/x-www-form-urlencoded",

241

alias: Optional[str] = None,

242

title: Optional[str] = None,

243

description: Optional[str] = None,

244

gt: Optional[float] = None,

245

ge: Optional[float] = None,

246

lt: Optional[float] = None,

247

le: Optional[float] = None,

248

min_length: Optional[int] = None,

249

max_length: Optional[int] = None,

250

regex: Optional[str] = None,

251

example: Any = Undefined,

252

examples: Optional[List[Any]] = None,

253

deprecated: Optional[bool] = None,

254

include_in_schema: bool = True,

255

json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,

256

**extra: Any

257

) -> Any:

258

"""

259

Declare a form data parameter with validation constraints.

260

261

Parameters: Same as Path(), plus:

262

- media_type: Expected media type for form data

263

264

Special behaviors:

265

- Reads from form data in request body

266

- Supports both URL-encoded and multipart form data

267

- Can be mixed with File() parameters for file uploads

268

- Cannot be used together with Body() parameters

269

"""

270

```

271

272

### File Upload Parameters

273

274

Function for declaring file upload parameters from multipart/form-data requests.

275

276

```python { .api }

277

def File(

278

default: Any = Undefined,

279

*,

280

media_type: str = "multipart/form-data",

281

alias: Optional[str] = None,

282

title: Optional[str] = None,

283

description: Optional[str] = None,

284

gt: Optional[float] = None,

285

ge: Optional[float] = None,

286

lt: Optional[float] = None,

287

le: Optional[float] = None,

288

min_length: Optional[int] = None,

289

max_length: Optional[int] = None,

290

regex: Optional[str] = None,

291

example: Any = Undefined,

292

examples: Optional[List[Any]] = None,

293

deprecated: Optional[bool] = None,

294

include_in_schema: bool = True,

295

json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,

296

**extra: Any

297

) -> Any:

298

"""

299

Declare a file upload parameter with validation constraints.

300

301

Parameters: Same as Path(), plus:

302

- media_type: Expected media type for file uploads

303

304

Special behaviors:

305

- Reads file data from multipart/form-data requests

306

- Returns bytes by default, or UploadFile when type-hinted as such

307

- Can be mixed with Form() parameters

308

- Supports multiple file uploads with List[UploadFile] type hint

309

"""

310

```

311

312

## Usage Examples

313

314

### Path Parameter Validation

315

316

```python

317

from fastapi import FastAPI, Path

318

319

app = FastAPI()

320

321

@app.get("/items/{item_id}")

322

async def get_item(

323

item_id: int = Path(..., title="Item ID", description="The ID of the item", ge=1, le=1000)

324

):

325

return {"item_id": item_id}

326

327

@app.get("/users/{username}")

328

async def get_user(

329

username: str = Path(

330

...,

331

title="Username",

332

min_length=3,

333

max_length=20,

334

regex=r"^[a-zA-Z0-9_]+$"

335

)

336

):

337

return {"username": username}

338

```

339

340

### Query Parameter Validation

341

342

```python

343

from fastapi import FastAPI, Query

344

from typing import Optional, List

345

346

app = FastAPI()

347

348

@app.get("/items/")

349

async def get_items(

350

skip: int = Query(0, ge=0, description="Number of items to skip"),

351

limit: int = Query(10, ge=1, le=100, description="Number of items to return"),

352

tags: List[str] = Query(None, description="List of tags to filter by"),

353

q: Optional[str] = Query(None, min_length=3, max_length=50, description="Search query")

354

):

355

return {"skip": skip, "limit": limit, "tags": tags, "q": q}

356

357

# Example usage:

358

# GET /items/?skip=0&limit=10&tags=red&tags=blue&q=search

359

```

360

361

### Header and Cookie Parameters

362

363

```python

364

from fastapi import FastAPI, Header, Cookie

365

from typing import Optional

366

367

app = FastAPI()

368

369

@app.get("/items/")

370

async def get_items(

371

user_agent: Optional[str] = Header(None), # Reads User-Agent header

372

x_request_id: Optional[str] = Header(None, alias="X-Request-ID"),

373

session_id: Optional[str] = Cookie(None, description="Session identifier")

374

):

375

return {

376

"user_agent": user_agent,

377

"request_id": x_request_id,

378

"session_id": session_id

379

}

380

```

381

382

### Request Body Parameters

383

384

```python

385

from fastapi import FastAPI, Body

386

from pydantic import BaseModel

387

from typing import Optional

388

389

app = FastAPI()

390

391

class Item(BaseModel):

392

name: str

393

price: float

394

395

class User(BaseModel):

396

username: str

397

email: str

398

399

@app.post("/items/")

400

async def create_item(

401

item: Item,

402

user: User,

403

timestamp: int = Body(..., embed=True), # Embedded in JSON

404

importance: int = Body(1, gt=0, le=5)

405

):

406

# Request body structure:

407

# {

408

# "item": {"name": "...", "price": ...},

409

# "user": {"username": "...", "email": "..."},

410

# "timestamp": {"value": 1234567890}, # embedded

411

# "importance": 3

412

# }

413

return {"item": item, "user": user, "timestamp": timestamp, "importance": importance}

414

```

415

416

### Form Data and File Uploads

417

418

```python

419

from fastapi import FastAPI, Form, File, UploadFile

420

from typing import List, Optional

421

422

app = FastAPI()

423

424

@app.post("/upload/")

425

async def upload_file(

426

file: UploadFile = File(..., description="File to upload"),

427

title: str = Form(..., min_length=1, max_length=100),

428

description: Optional[str] = Form(None)

429

):

430

return {

431

"filename": file.filename,

432

"content_type": file.content_type,

433

"title": title,

434

"description": description

435

}

436

437

@app.post("/upload-multiple/")

438

async def upload_multiple_files(

439

files: List[UploadFile] = File(..., description="Multiple files to upload"),

440

category: str = Form(..., description="File category")

441

):

442

return {

443

"filenames": [file.filename for file in files],

444

"category": category,

445

"file_count": len(files)

446

}

447

448

@app.post("/upload-bytes/")

449

async def upload_raw_bytes(

450

file: bytes = File(..., description="Raw file bytes"),

451

metadata: str = Form(..., description="File metadata")

452

):

453

return {

454

"file_size": len(file),

455

"metadata": metadata

456

}

457

```

458

459

### Complex Parameter Combinations

460

461

```python

462

from fastapi import FastAPI, Path, Query, Header, Body, Depends

463

from pydantic import BaseModel

464

from typing import Optional

465

466

app = FastAPI()

467

468

class UpdateData(BaseModel):

469

name: Optional[str] = None

470

value: Optional[int] = None

471

472

def get_auth_user(authorization: str = Header(...)):

473

# Extract user from authorization header

474

return {"user_id": 123, "username": "john"}

475

476

@app.put("/items/{item_id}")

477

async def update_item(

478

# Path parameter

479

item_id: int = Path(..., ge=1, description="Item ID to update"),

480

481

# Query parameters

482

force: bool = Query(False, description="Force update even if item is locked"),

483

notify: Optional[str] = Query(None, regex=r"^(email|sms|push)$"),

484

485

# Header parameter

486

x_request_id: str = Header(..., alias="X-Request-ID"),

487

488

# Body parameter

489

update_data: UpdateData,

490

491

# Dependency

492

current_user: dict = Depends(get_auth_user)

493

):

494

return {

495

"item_id": item_id,

496

"update_data": update_data,

497

"force": force,

498

"notify": notify,

499

"request_id": x_request_id,

500

"updated_by": current_user["username"]

501

}

502

```

503

504

### Advanced Validation Examples

505

506

```python

507

from fastapi import FastAPI, Query, Path, Body

508

from pydantic import BaseModel, Field, validator

509

from datetime import datetime

510

from typing import List, Optional

511

import re

512

513

app = FastAPI()

514

515

class SearchFilters(BaseModel):

516

min_price: Optional[float] = Field(None, ge=0, description="Minimum price filter")

517

max_price: Optional[float] = Field(None, ge=0, description="Maximum price filter")

518

categories: List[str] = Field(default_factory=list, description="Category filters")

519

created_after: Optional[datetime] = Field(None, description="Filter by creation date")

520

521

@validator('max_price')

522

def validate_price_range(cls, v, values):

523

if v is not None and 'min_price' in values and values['min_price'] is not None:

524

if v < values['min_price']:

525

raise ValueError('max_price must be greater than min_price')

526

return v

527

528

@app.get("/search/{query}")

529

async def search_items(

530

# Path with complex regex validation

531

query: str = Path(

532

...,

533

title="Search Query",

534

description="Search query string",

535

min_length=1,

536

max_length=100,

537

regex=r"^[a-zA-Z0-9\s\-_\.]+$"

538

),

539

540

# Query with multiple validation constraints

541

page: int = Query(1, ge=1, le=1000, description="Page number"),

542

size: int = Query(10, ge=1, le=100, description="Page size"),

543

544

# Query with enum-like validation

545

sort_by: Optional[str] = Query(

546

"relevance",

547

regex=r"^(relevance|price|date|popularity)$",

548

description="Sort criteria"

549

),

550

sort_order: Optional[str] = Query(

551

"asc",

552

regex=r"^(asc|desc)$",

553

description="Sort order"

554

),

555

556

# Body with complex model

557

filters: Optional[SearchFilters] = Body(None, description="Advanced search filters")

558

):

559

return {

560

"query": query,

561

"page": page,

562

"size": size,

563

"sort_by": sort_by,

564

"sort_order": sort_order,

565

"filters": filters

566

}

567

```