API Navigator Logo

Python API Response Validation

Author: Newtum

This example covers how to validate the structure and data types of a JSON API response using the `Pydantic` library. This is crucial for ensuring the data you receive is what you expect.

Why Validate Responses?

APIs can change or return unexpected data. Validating the response ensures your application doesn't crash from missing keys or incorrect data types, making your code more robust.

Validating with Pydantic

Pydantic allows you to define data models. If the JSON data from the API doesn't conform to the model, it raises a helpful validation error.

from pydantic import BaseModel, ValidationError

# Define the expected structure of the User data
class User(BaseModel):
    id: int
    name: str
    email: str

# A valid JSON response from an API
valid_data = {
    "id": 1,
    "name": "Leanne Graham",
    "email": "Sincere@april.biz"
}

# An invalid JSON response (id is a string, not an int)
invalid_data = {
    "id": "one",
    "name": "Leanne Graham",
    "email": "Sincere@april.biz"
}

try:
    user = User(**valid_data)
    print("Valid data parsed successfully:")
    print(user.model_dump_json(indent=2))
except ValidationError as e:
    print(f"Validation failed for valid_data: {e}")

try:
    user = User(**invalid_data)
    print("Invalid data parsed successfully.")
except ValidationError as e:
    print("\nValidation failed for invalid_data as expected:")
    print(e)