How do you validate untrusted JSON or config input?
AdvancedConceptData formats, HTTP & REST APIs
Answer
Do not trust shape or types from webhooks, config files or APIs. Use pydantic models (or jsonschema against a schema) to validate and coerce at the boundary, then pass typed objects inward.
from pydantic import BaseModel, Field
class DeployRequest(BaseModel):
service: str = Field(pattern=r"^[a-z0-9-]{1,40}$")
version: str
replicas: int = Field(ge=1, le=50)
req = DeployRequest.model_validate(payload) # raises ValidationError with field-level errors
FastAPI does this automatically for request bodies.
More on Data formats, HTTP & REST APIs
How do you read and write JSON, and what are the common gotchas?BeginnerWhy must you use `yaml.safe_load` rather than `yaml.load`?BeginnerHow do you load a multi-document Kubernetes YAML file?IntermediateHow do you read and write CSV files properly?BeginnerHow do you make an HTTP request with `requests` the right way?BeginnerWhy use a `requests.Session`?Intermediate