Interview Prep/Python for DevOps/Data formats, HTTP & REST APIs

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.

All Python for DevOps questions Roadmap: Python for automation

More on Data formats, HTTP & REST APIs