FastAPI framework, high performance, easy to learn, fast to code, ready for production - slim version without standard dependencies
—
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.
Function for declaring path parameters extracted from URL path segments with validation constraints.
def Path(
default: Any = ...,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
validation_alias: Union[str, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
regex: Optional[str] = None, # Deprecated: use pattern instead
discriminator: Union[str, None] = None,
strict: Union[bool, None] = _Unset,
multiple_of: Union[float, None] = None,
allow_inf_nan: Union[bool, None] = None,
max_digits: Union[int, None] = None,
decimal_places: Union[int, None] = None,
example: Any = Undefined,
examples: Optional[List[Any]] = None,
openapi_examples: Optional[Dict[str, Example]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,
**extra: Any
) -> Any:
"""
Declare a path parameter with validation constraints.
Parameters:
- default: Default value (use ... for required parameters)
- default_factory: Callable to generate default value (not applicable for Path)
- alias: Alternative parameter name in OpenAPI schema
- alias_priority: Priority for alias resolution
- validation_alias: Alias used for validation
- serialization_alias: Alias used for serialization
- title: Parameter title for OpenAPI documentation
- description: Parameter description for OpenAPI documentation
- gt: Value must be greater than this number
- ge: Value must be greater than or equal to this number
- lt: Value must be less than this number
- le: Value must be less than or equal to this number
- min_length: Minimum string length (for string parameters)
- max_length: Maximum string length (for string parameters)
- pattern: Regular expression pattern for string validation
- regex: Regular expression pattern (deprecated, use pattern instead)
- discriminator: Field name for discriminating tagged union types
- strict: Enable strict validation mode
- multiple_of: Value must be a multiple of this number
- allow_inf_nan: Allow infinite and NaN values for floats
- max_digits: Maximum number of digits for Decimal values
- decimal_places: Maximum decimal places for Decimal values
- example: Example value for OpenAPI documentation
- examples: List of example values for OpenAPI documentation
- openapi_examples: Dict of OpenAPI example objects
- deprecated: Mark parameter as deprecated in OpenAPI
- include_in_schema: Include parameter in OpenAPI schema
- json_schema_extra: Additional JSON schema properties
"""Function for declaring query parameters from URL query string with validation constraints.
def Query(
default: Any = Undefined,
*,
alias: Optional[str] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
example: Any = Undefined,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,
**extra: Any
) -> Any:
"""
Declare a query parameter with validation constraints.
Parameters: Same as Path(), used for URL query string parameters.
Special behaviors:
- Supports list values for repeated parameters (?tags=red&tags=blue)
- Optional by default (default=None) unless explicitly required
- Automatically converts string values to specified types
"""Function for declaring HTTP header parameters with automatic case conversion and validation.
def Header(
default: Any = Undefined,
*,
alias: Optional[str] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
regex: Optional[str] = None,
example: Any = Undefined,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,
convert_underscores: bool = True,
**extra: Any
) -> Any:
"""
Declare a header parameter with validation constraints.
Parameters: Same as Path(), plus:
- convert_underscores: Convert underscores to hyphens in header names
(user_agent becomes User-Agent)
Special behaviors:
- Header names are case-insensitive
- Supports list values for headers with multiple values
- Automatic conversion of underscore parameter names to hyphenated header names
"""Function for declaring HTTP cookie parameters with validation.
def Cookie(
default: Any = Undefined,
*,
alias: Optional[str] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
regex: Optional[str] = None,
example: Any = Undefined,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,
**extra: Any
) -> Any:
"""
Declare a cookie parameter with validation constraints.
Parameters: Same as Path().
Special behaviors:
- Reads values from HTTP cookies
- Optional by default
- Automatic type conversion from string cookie values
"""Function for declaring request body parameters with content type specification and validation.
def Body(
default: Any = Undefined,
*,
embed: bool = False,
media_type: str = "application/json",
alias: Optional[str] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
regex: Optional[str] = None,
example: Any = Undefined,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,
**extra: Any
) -> Any:
"""
Declare a request body parameter with validation constraints.
Parameters: Same as Path(), plus:
- embed: Embed single values in JSON object instead of using value directly
- media_type: Expected media type for the request body
Special behaviors:
- Reads from request body instead of URL/headers
- Supports JSON, form data, and other content types
- Can be combined with other Body() parameters for complex payloads
- When embed=True, wraps single values: {"value": <actual_value>}
"""Function for declaring form data parameters for multipart/form-data and application/x-www-form-urlencoded requests.
def Form(
default: Any = Undefined,
*,
media_type: str = "application/x-www-form-urlencoded",
alias: Optional[str] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
regex: Optional[str] = None,
example: Any = Undefined,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,
**extra: Any
) -> Any:
"""
Declare a form data parameter with validation constraints.
Parameters: Same as Path(), plus:
- media_type: Expected media type for form data
Special behaviors:
- Reads from form data in request body
- Supports both URL-encoded and multipart form data
- Can be mixed with File() parameters for file uploads
- Cannot be used together with Body() parameters
"""Function for declaring file upload parameters from multipart/form-data requests.
def File(
default: Any = Undefined,
*,
media_type: str = "multipart/form-data",
alias: Optional[str] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
regex: Optional[str] = None,
example: Any = Undefined,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], Callable[[Dict[str, Any]], None], None] = None,
**extra: Any
) -> Any:
"""
Declare a file upload parameter with validation constraints.
Parameters: Same as Path(), plus:
- media_type: Expected media type for file uploads
Special behaviors:
- Reads file data from multipart/form-data requests
- Returns bytes by default, or UploadFile when type-hinted as such
- Can be mixed with Form() parameters
- Supports multiple file uploads with List[UploadFile] type hint
"""from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def get_item(
item_id: int = Path(..., title="Item ID", description="The ID of the item", ge=1, le=1000)
):
return {"item_id": item_id}
@app.get("/users/{username}")
async def get_user(
username: str = Path(
...,
title="Username",
min_length=3,
max_length=20,
regex=r"^[a-zA-Z0-9_]+$"
)
):
return {"username": username}from fastapi import FastAPI, Query
from typing import Optional, List
app = FastAPI()
@app.get("/items/")
async def get_items(
skip: int = Query(0, ge=0, description="Number of items to skip"),
limit: int = Query(10, ge=1, le=100, description="Number of items to return"),
tags: List[str] = Query(None, description="List of tags to filter by"),
q: Optional[str] = Query(None, min_length=3, max_length=50, description="Search query")
):
return {"skip": skip, "limit": limit, "tags": tags, "q": q}
# Example usage:
# GET /items/?skip=0&limit=10&tags=red&tags=blue&q=searchfrom fastapi import FastAPI, Header, Cookie
from typing import Optional
app = FastAPI()
@app.get("/items/")
async def get_items(
user_agent: Optional[str] = Header(None), # Reads User-Agent header
x_request_id: Optional[str] = Header(None, alias="X-Request-ID"),
session_id: Optional[str] = Cookie(None, description="Session identifier")
):
return {
"user_agent": user_agent,
"request_id": x_request_id,
"session_id": session_id
}from fastapi import FastAPI, Body
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class Item(BaseModel):
name: str
price: float
class User(BaseModel):
username: str
email: str
@app.post("/items/")
async def create_item(
item: Item,
user: User,
timestamp: int = Body(..., embed=True), # Embedded in JSON
importance: int = Body(1, gt=0, le=5)
):
# Request body structure:
# {
# "item": {"name": "...", "price": ...},
# "user": {"username": "...", "email": "..."},
# "timestamp": {"value": 1234567890}, # embedded
# "importance": 3
# }
return {"item": item, "user": user, "timestamp": timestamp, "importance": importance}from fastapi import FastAPI, Form, File, UploadFile
from typing import List, Optional
app = FastAPI()
@app.post("/upload/")
async def upload_file(
file: UploadFile = File(..., description="File to upload"),
title: str = Form(..., min_length=1, max_length=100),
description: Optional[str] = Form(None)
):
return {
"filename": file.filename,
"content_type": file.content_type,
"title": title,
"description": description
}
@app.post("/upload-multiple/")
async def upload_multiple_files(
files: List[UploadFile] = File(..., description="Multiple files to upload"),
category: str = Form(..., description="File category")
):
return {
"filenames": [file.filename for file in files],
"category": category,
"file_count": len(files)
}
@app.post("/upload-bytes/")
async def upload_raw_bytes(
file: bytes = File(..., description="Raw file bytes"),
metadata: str = Form(..., description="File metadata")
):
return {
"file_size": len(file),
"metadata": metadata
}from fastapi import FastAPI, Path, Query, Header, Body, Depends
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class UpdateData(BaseModel):
name: Optional[str] = None
value: Optional[int] = None
def get_auth_user(authorization: str = Header(...)):
# Extract user from authorization header
return {"user_id": 123, "username": "john"}
@app.put("/items/{item_id}")
async def update_item(
# Path parameter
item_id: int = Path(..., ge=1, description="Item ID to update"),
# Query parameters
force: bool = Query(False, description="Force update even if item is locked"),
notify: Optional[str] = Query(None, regex=r"^(email|sms|push)$"),
# Header parameter
x_request_id: str = Header(..., alias="X-Request-ID"),
# Body parameter
update_data: UpdateData,
# Dependency
current_user: dict = Depends(get_auth_user)
):
return {
"item_id": item_id,
"update_data": update_data,
"force": force,
"notify": notify,
"request_id": x_request_id,
"updated_by": current_user["username"]
}from fastapi import FastAPI, Query, Path, Body
from pydantic import BaseModel, Field, validator
from datetime import datetime
from typing import List, Optional
import re
app = FastAPI()
class SearchFilters(BaseModel):
min_price: Optional[float] = Field(None, ge=0, description="Minimum price filter")
max_price: Optional[float] = Field(None, ge=0, description="Maximum price filter")
categories: List[str] = Field(default_factory=list, description="Category filters")
created_after: Optional[datetime] = Field(None, description="Filter by creation date")
@validator('max_price')
def validate_price_range(cls, v, values):
if v is not None and 'min_price' in values and values['min_price'] is not None:
if v < values['min_price']:
raise ValueError('max_price must be greater than min_price')
return v
@app.get("/search/{query}")
async def search_items(
# Path with complex regex validation
query: str = Path(
...,
title="Search Query",
description="Search query string",
min_length=1,
max_length=100,
regex=r"^[a-zA-Z0-9\s\-_\.]+$"
),
# Query with multiple validation constraints
page: int = Query(1, ge=1, le=1000, description="Page number"),
size: int = Query(10, ge=1, le=100, description="Page size"),
# Query with enum-like validation
sort_by: Optional[str] = Query(
"relevance",
regex=r"^(relevance|price|date|popularity)$",
description="Sort criteria"
),
sort_order: Optional[str] = Query(
"asc",
regex=r"^(asc|desc)$",
description="Sort order"
),
# Body with complex model
filters: Optional[SearchFilters] = Body(None, description="Advanced search filters")
):
return {
"query": query,
"page": page,
"size": size,
"sort_by": sort_by,
"sort_order": sort_order,
"filters": filters
}Install with Tessl CLI
npx tessl i tessl/pypi-fastapi-slim