How to Validate Data Fields and Types in Python

Validate required fields and type correctness in a Python dictionary with small helper functions, returning a list of clear error messages.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 13 views 0 copies

Python code

42 lines
Python 3.9+
import json
from typing import Any, Dict, List


def validate_data(data: Dict[str, Any], required_fields: List[str]) -> List[str]:
    """Check required fields exist and are non-empty. Return list of errors."""
    errors = []
    for field in required_fields:
        value = data.get(field)
        if value is None or value == "":
            errors.append(f"Missing or empty required field: {field}")
    return errors


def validate_types(data: Dict[str, Any], type_map: Dict[str, type]) -> List[str]:
    """Verify fields match expected types. Return list of errors."""
    errors = []
    for field, expected_type in type_map.items():
        if field in data and not isinstance(data[field], expected_type):
            errors.append(
                f"Field '{field}' must be {expected_type.__name__}, got {type(data[field]).__name__}"
            )
    return errors


if __name__ == "__main__":
    sample_payload = {
        "user_id": 123,
        "email": "joe@example.com",
        "score": "high",
        "tags": ["python", "cloud"],
    }

    required = ["user_id", "email", "password"]
    types = {"user_id": int, "email": str, "tags": list}

    all_errors = validate_data(sample_payload, required) + validate_types(sample_payload, types)

    print(json.dumps(sample_payload, indent=2))
    print(f"Validation errors: {len(all_errors)}")
    for error in all_errors:
        print(f"- {error}")

Output

stdout
{
  "user_id": 123,
  "email": "joe@example.com",
  "score": "high",
  "tags": ["python", "cloud"]
}
Validation errors: 2
- Missing or empty required field: password
- Field 'score' must be int, got str

How it works

The validate_data function checks each required field with .get(), returning a friendly error when the value is None or an empty string. validate_types uses isinstance() to confirm fields match the expected built-in types, reporting both the expected and actual type names. Both helpers return plain lists, so callers can concatenate errors and decide how to surface them. The sample payload exercises both helpers, showing how missing fields and type mismatches are reported distinctly.

Common mistakes

  • Using `data[field]` instead of `.get()`, which raises KeyError for missing keys
  • Checking only for `None` and forgetting empty strings or whitespace-only values
  • Assuming `isinstance` accepts tuples for multiple allowed types, which it does not without extra logic

Variations

  1. Add a `value.strip() == ''` check to catch whitespace-only strings as empty
  2. Return a dictionary keyed by field instead of a flat list of errors

Real-world use cases

  • Validating incoming webhook payloads before processing them in a cloud function.
  • Checking environment variables or config dictionaries at service startup for required keys.
  • Pre-validating API request bodies in a serverless lambda before database writes.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.