PYTHON

Defining Structured Request Data with Python `dataclasses`

Efficiently define and validate structured request data payloads using Python's `dataclasses` for cleaner, type-hinted web application development.

from dataclasses import dataclass, field
from typing import List, Optional

@dataclass
class UserRequest:
    username: str
    email: str
    age: Optional[int] = None
    roles: List[str] = field(default_factory=list)
    is_active: bool = True

# Example usage in a web context (e.g., FastAPI/Flask)
def process_user_data(data: dict):
    try:
        # Assuming data comes from JSON body
        user_req = UserRequest(**data)
        print(f"Processing user: {user_req.username}, Email: {user_req.email}")
        if user_req.age:
            print(f"Age: {user_req.age}")
        print(f"Roles: {', '.join(user_req.roles)}")
        print(f"Active: {user_req.is_active}")
        return user_req
    except TypeError as e:
        print(f"Invalid request data: {e}")
        return None

# Simulate incoming valid data
valid_data = {
    "username": "john_doe",
    "email": "[email protected]",
    "age": 30,
    "roles": ["admin", "editor"]
}
process_user_data(valid_data)

# Simulate incoming data with defaults and missing optional
partial_data = {
    "username": "jane_doe",
    "email": "[email protected]"
}
process_user_data(partial_data)

# Simulate invalid data
invalid_data = {
    "username": "malformed",
    "email": 123
}
process_user_data(invalid_data)
How it works: `dataclasses` provide a simple way to create classes primarily used to store data, reducing boilerplate. For web development, they are excellent for defining the structure of incoming request bodies (e.g., JSON payloads), ensuring type safety and clarity. The `field(default_factory=list)` is crucial for mutable defaults like lists to avoid unexpected shared states between instances. This snippet demonstrates how to define a data structure for a `UserRequest` and use it to process incoming dictionary data, benefiting from automatic `__init__`, `__repr__`, and `__eq__` methods.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs