# Python data validation libraries

Python data validation libraries check that incoming data has the expected structure and types before an application uses it. A validator either builds typed objects from annotated classes or checks a plain dictionary against a separate schema. These libraries let APIs and AI agents reject malformed input before it reaches application logic.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Pydantic](#pydantic) | 1.2B | 29.6K | Nov 2026 | MIT |
| [jsonschema](#jsonschema) | 653.8M | 5.0K | Jan 2026 | MIT |
| [fastjsonschema](#fastjsonschema) | 127.8M | 504 | Nov 2026 | BSD-3-Clause |
| [marshmallow](#marshmallow) | 92.3M | 7.2K | Nov 2026 | MIT |
| [dataclasses-json](#dataclasses-json) | 50.6M | 1.5K | Jun 2024 | MIT |
| [msgspec](#msgspec) | 40.1M | 4.2K | Sep 2026 | BSD-3-Clause |
| [cattrs](#cattrs) | 38.6M | 1.1K | Sep 2026 | MIT |
| [schema](#schema) | 21.9M | 2.9K | Oct 2025 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Pydantic](#pydantic) has the most monthly downloads in this comparison, at 1.2B.

## Capabilities

| Library | Annotation-defined records | Converts numeric strings |
| --- | --- | --- |
| [Pydantic](#pydantic) | Yes | Yes |
| [jsonschema](#jsonschema) | No | No |
| [fastjsonschema](#fastjsonschema) | No | No |
| [marshmallow](#marshmallow) | No | Yes |
| [dataclasses-json](#dataclasses-json) | Yes | Yes |
| [msgspec](#msgspec) | Yes | Yes |
| [cattrs](#cattrs) | Yes | Yes |
| [schema](#schema) | No | Yes |

## Libraries

### Pydantic

[GitHub](https://github.com/pydantic/pydantic) · [PyPI](https://pypi.org/project/pydantic) · [Docs](https://docs.pydantic.dev/latest/concepts/models/)

Builds validated Python models from annotated field types.

- Downloads / mo: 1.2B
- Stars: 29.6K
- Last release: 2.14.3
- License: MIT
- Capabilities: [From the Pydantic docs](https://docs.pydantic.dev/latest/concepts/models/)

**Strengths**

- **Builds nested typed models.** Use model classes inside annotations to validate hierarchical records.
- **Serializes models directly as JSON.** Use model_dump_json to encode supported model values as JSON.

**Watch out for**

- **Validation can change input types.** Enable strict mode when values must already have the required types.

```sh
python -m pip install pydantic==2.14.3
```

**fastapi/fastapi** (104.9K stars)

[fastapi/fastapi](https://github.com/fastapi/fastapi) 

```python
def validate(
    self,
    value: Any,
    values: dict[str, Any] = {},  # noqa: B006
    *,
    loc: tuple[int | str, ...] = (),
) -> tuple[Any, list[dict[str, Any]]]:
    try:
        return (
            self._type_adapter.validate_python(value, from_attributes=True),
            [],
        )
    except ValidationError as exc:
        return None, _regenerate_error_with_loc(
            errors=exc.errors(include_url=False), loc_prefix=loc
        )

```

[fastapi/_compat/v2.py](https://github.com/fastapi/fastapi/blob/5add7a458d629b07311d48261f696b5ac2bb9a5f/fastapi/_compat/v2.py) · [More projects using Pydantic →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20pydantic&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from pydantic import BaseModel

class User(BaseModel):
    age: int

user = User.model_validate({"age": "42"})
print(user.age)

```

From [models.md](https://docs.pydantic.dev/latest/concepts/models/)

### jsonschema

[GitHub](https://github.com/python-jsonschema/jsonschema) · [PyPI](https://pypi.org/project/jsonschema) · [Docs](https://python-jsonschema.readthedocs.io/en/stable/validate/)

Checks data instances against JSON Schema rules.

- Downloads / mo: 653.8M
- Stars: 5.0K
- Last release: 4.26.0
- License: MIT
- Capabilities: [From the jsonschema docs](https://python-jsonschema.readthedocs.io/en/stable/validate/)

**Strengths**

- **Iterates structured validation errors.** Use iter_errors to inspect each validation issue lazily.
- **Extends existing validator classes.** Add custom keyword handlers by extending a validator class.

**Watch out for**

- **Formats require explicit checking.** Configure a FormatChecker when format values must be validated.
- **Defaults do not populate data.** The default keyword does not fill missing properties during validation.

```sh
python -m pip install jsonschema==4.26.0
```

**jupyter/nbformat** (316 stars)

[jupyter/nbformat](https://github.com/jupyter/nbformat) 

```python
def iter_errors(self, data, schema=None):
    """Iterate over errors in incoming data."""
    if schema is None:
        return self._default_validator.iter_errors(data)
    if hasattr(self._default_validator, "evolve"):
        return self._default_validator.evolve(schema=schema).iter_errors(data)
    return self._default_validator.iter_errors(data, schema)

```

[nbformat/json_compat.py](https://github.com/jupyter/nbformat/blob/cfb73afdd2a7f358953f2a34f747fd0d0e9d6288/nbformat/json_compat.py) · [More projects using jsonschema →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20jsonschema&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from jsonschema import validate

schema = {"type": "object", "properties": {"age": {"type": "integer"}}, "required": ["age"]}
validate({"age": 42}, schema)

```

From [README.md](https://python-jsonschema.readthedocs.io/en/stable/validate/)

### fastjsonschema

[GitHub](https://github.com/horejsek/python-fastjsonschema) · [PyPI](https://pypi.org/project/fastjsonschema) · [Docs](https://horejsek.github.io/python-fastjsonschema/)

Implements JSON Schema validation in Python with a focus on speed.

- Downloads / mo: 127.8M
- Stars: 504
- Last release: 2.22.3
- License: BSD-3-Clause
- Capabilities: [From the fastjsonschema docs](https://horejsek.github.io/python-fastjsonschema/)

```sh
python -m pip install fastjsonschema==2.22.3
```

**jupyter/nbformat** (316 stars)

[jupyter/nbformat](https://github.com/jupyter/nbformat) 

```python
def validate(self, data):
    """Validate incoming data."""
    try:
        self._validator(data)
    except _JsonSchemaException as error:
        raise ValidationError(str(error), schema_path=error.path) from error
```

[nbformat/json_compat.py](https://github.com/jupyter/nbformat/blob/cfb73afdd2a7f358953f2a34f747fd0d0e9d6288/nbformat/json_compat.py) · [More projects using fastjsonschema →](https://dashboard.exa.ai/playground/search?q=fastjsonschema%20GitHub%20projects)

**Quickstart**

```python
import fastjsonschema

validate = fastjsonschema.compile({"type": "object", "properties": {"age": {"type": "integer"}}, "required": ["age"]})
print(validate({"age": 42}))

```

From [README.md](https://horejsek.github.io/python-fastjsonschema/)

### marshmallow

[GitHub](https://github.com/marshmallow-code/marshmallow) · [PyPI](https://pypi.org/project/marshmallow) · [Docs](https://marshmallow.readthedocs.io/en/stable/quickstart.html)

Validates and deserializes records, then serializes application objects through schemas.

- Downloads / mo: 92.3M
- Stars: 7.2K
- Last release: 4.4.0
- License: MIT
- Capabilities: [From the marshmallow docs](https://marshmallow.readthedocs.io/en/stable/quickstart.html)

**Strengths**

- **Represents nested object relationships.** Use Nested fields for related objects and lists of related records.
- **Serializes objects to JSON.** Use dumps to return a JSON-encoded string.

**Watch out for**

- **Dumping skips validation.** Validate inputs with load before relying on serialized output.
- **Unknown fields raise by default.** Set unknown=EXCLUDE or INCLUDE when extra input fields are expected.

```sh
python -m pip install marshmallow==4.4.0
```

**marshmallow-code/webargs** (1.4K stars)

[marshmallow-code/webargs](https://github.com/marshmallow-code/webargs) 

```python
def _get_schema(self, argmap: ArgMap[Request], req: Request) -> ma.Schema:
    """Return a `marshmallow.Schema` for the given argmap and request.

    :param argmap: Either a `marshmallow.Schema`, `dict`
        of argname -> `marshmallow.fields.Field` pairs, or a callable that returns
        a `marshmallow.Schema` instance.
    :param req: The request object being parsed.
    :rtype: marshmallow.Schema
    """
    if isinstance(argmap, ma.Schema):
        schema: ma.Schema = argmap
    elif isinstance(argmap, type) and issubclass(argmap, ma.Schema):
        schema = argmap()
    elif isinstance(argmap, collections.abc.Mapping):
        argmap_dict = argmap if isinstance(argmap, dict) else dict(argmap)
        schema = self.schema_class.from_dict(argmap_dict)()
    elif callable(argmap):
        argmap_callable: ArgMapCallable[Request] = argmap  # type: ignore[assignment]
        schema = argmap_callable(req)
    else:
        raise TypeError(f"argmap was of unexpected type {type(argmap)}")
    return schema

```

[src/webargs/core.py](https://github.com/marshmallow-code/webargs/blob/0a3f9a2034c06a8e86402653748c8b5b06c40146/src/webargs/core.py) · [More projects using marshmallow →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20marshmallow&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from marshmallow import Schema, fields

UserSchema = Schema.from_dict({"age": fields.Integer(required=True)})
user = UserSchema().load({"age": "42"})
print(user)

```

From [quickstart.html](https://marshmallow.readthedocs.io/en/stable/quickstart.html)

### dataclasses-json

[GitHub](https://github.com/lidatong/dataclasses-json) · [PyPI](https://pypi.org/project/dataclasses-json)

Serializes dataclasses to and from JSON.

- Downloads / mo: 50.6M
- Stars: 1.5K
- Last release: 0.6.7
- License: MIT
- Capabilities: [From the dataclasses-json docs](https://github.com/lidatong/dataclasses-json)

```sh
python -m pip install dataclasses-json==0.6.7 "marshmallow>=3.18,<4"
```

**facebookresearch/fbpcs** (151 stars)

[facebookresearch/fbpcs](https://github.com/facebookresearch/fbpcs) 

```python
@classmethod
def loads_schema(cls, json_schema_str: str) -> "PrivateComputationInstance":
    json_object = json.loads(json_schema_str)

    # create infra config
    infra_config: InfraConfig = InfraConfig.schema().loads(
        json.dumps(json_object["infra_config"]),
        unknown=marshmallow.utils.EXCLUDE,
        many=None,
    )

    # create product config
    product_config: ProductConfig
    product_cleaned_json = False
    product_json = json_object["product_config"]

    while not product_cleaned_json:
        # delete json contents which are not in config class
        # this makes old PCInstance still valid when deleting attributes
        try:
            product_config = cls._product_map(json_object).loads(
                json.dumps(product_json),
                unknown=marshmallow.utils.EXCLUDE,
                many=None,
            )
            product_cleaned_json = True
        except marshmallow.exceptions.ValidationError as err:
            logging.warning(f"delete unknown contents: {err.args[0]}")
            cls._prune_json(product_json, err.args[0])

    return PrivateComputationInstance(
        infra_config=infra_config, product_config=product_config
    )

```

[fbpcs/private_computation/entity/private_computation_instance.py](https://github.com/facebookresearch/fbpcs/blob/f7c0847de52003552b3976e78acaf9836feedadb/fbpcs/private_computation/entity/private_computation_instance.py#L82-L114) · [More projects using dataclasses-json →](https://dashboard.exa.ai/playground/search?q=dataclasses-json%20GitHub%20projects)

**Quickstart**

```python
from dataclasses import dataclass
from dataclasses_json import dataclass_json

@dataclass_json
@dataclass
class User:
    name: str

user = User.schema().load({"name": "Ada"})
print(user.name)

```

From [README.md](https://github.com/lidatong/dataclasses-json)

### msgspec

[GitHub](https://github.com/msgspec/msgspec) · [PyPI](https://pypi.org/project/msgspec) · [Docs](https://msgspec.dev/api)

Serializes and validates data, with built-in support for JSON, MessagePack, YAML, and TOML.

- Downloads / mo: 40.1M
- Stars: 4.2K
- Last release: 0.22.0
- License: BSD-3-Clause
- Capabilities: [From the msgspec docs](https://msgspec.dev/api)

```sh
python -m pip install msgspec==0.22.0
```

**vllm-project/vllm** (90.9K stars)

[vllm-project/vllm](https://github.com/vllm-project/vllm) 

```python
def _convert_result(self, result_type: Sequence[str], result: Any) -> Any:
    if result_type is None:
        return result
    mod_name, name = result_type
    mod = importlib.import_module(mod_name)
    result_type = getattr(mod, name)
    return msgspec.convert(result, result_type, dec_hook=self.dec_hook)
```

[vllm/v1/serial_utils.py](https://github.com/vllm-project/vllm/blob/6f687a0836363e636740919b0ee4510aff80098f/vllm/v1/serial_utils.py) · [More projects using msgspec →](https://dashboard.exa.ai/playground/search?q=msgspec%20GitHub%20projects)

**Quickstart**

```python
import msgspec

class User(msgspec.Struct):
    age: int

user = msgspec.convert({"age": 42}, User)
print(user.age)

```

From [README.md](https://msgspec.dev/api)

### cattrs

[GitHub](https://github.com/python-attrs/cattrs) · [PyPI](https://pypi.org/project/cattrs) · [Docs](https://catt.rs/en/stable/validation.html)

Adds composable support for complex attrs and dataclasses classes.

- Downloads / mo: 38.6M
- Stars: 1.1K
- Last release: 26.2.1
- License: MIT
- Capabilities: [From the cattrs docs](https://catt.rs/en/stable/validation.html)

```sh
python -m pip install cattrs==26.2.1
```

**microsoft/lsprotocol** (160 stars)

[microsoft/lsprotocol](https://github.com/microsoft/lsprotocol) 

```python
def get_converter(
    converter: Optional[cattrs.Converter] = None,
) -> cattrs.Converter:
    """Adds cattrs hooks for LSP lsp_types to the given converter."""
    if converter is None:
        converter = cattrs.Converter()
    return _hooks.register_hooks(converter)
```

[packages/python/lsprotocol/converters.py](https://github.com/microsoft/lsprotocol/blob/24d45ab059a174344c8de21672aa1c2f1be3c99f/packages/python/lsprotocol/converters.py) · [More projects using cattrs →](https://dashboard.exa.ai/playground/search?q=cattrs%20GitHub%20projects)

**Quickstart**

```python
from dataclasses import dataclass
import cattrs

@dataclass
class User:
    age: int

user = cattrs.structure({"age": "42"}, User)
print(user.age)

```

From [validation.html](https://catt.rs/en/stable/validation.html)

### schema

[GitHub](https://github.com/keleshev/schema) · [PyPI](https://pypi.org/project/schema)

Validates data against schemas built from Python objects.

- Downloads / mo: 21.9M
- Stars: 2.9K
- Last release: 0.7.8
- License: MIT
- Capabilities: [From the schema docs](https://github.com/keleshev/schema)

```sh
python -m pip install schema==0.7.8
```

**griptape-ai/griptape** (2.6K stars)

[griptape-ai/griptape](https://github.com/griptape-ai/griptape) 

```python
def __extract_schema_from_ref(self, schema: dict, schema_ref: dict) -> Schema:
    """Extracts a schema from a $ref if present, resolving it into native schema properties."""
    if "$ref" in schema_ref:
        # Resolve the reference and retrieve the schema data
        ref_path = schema_ref["$ref"].split("/")[-1]
        schema_data = schema["components"]["schemas"].get(ref_path, {})
    else:
        # Use the provided schema directly if no $ref is found
        schema_data = schema_ref

    # Convert the schema_data dictionary into a Schema with its properties
    properties = {}
    for prop, prop_info in schema_data.get("properties", {}).items():
        prop_type = prop_info.get("type", "string")
        prop_description = prop_info.get("description", "")
        schema_prop = Literal(prop, description=prop_description)
        is_optional = prop not in schema_data.get("required", [])

        if is_optional:
            schema_prop = SchemaOptional(schema_prop)

        properties[schema_prop] = self._map_openapi_type_to_python(prop_type, prop_info)

    return Schema(properties)

```

[griptape/tools/griptape_cloud_tool/tool.py](https://github.com/griptape-ai/griptape/blob/bfa411615c655ce1787282c5713e9cd0d9153069/griptape/tools/griptape_cloud_tool/tool.py#L87-L110) · [More projects using schema →](https://dashboard.exa.ai/playground/search?q=schema%20GitHub%20projects)

**Quickstart**

```python
from schema import Schema, And, Use

validate = Schema({"age": And(Use(int), lambda value: value >= 0)})
print(validate.validate({"age": "42"}))

```

From [README.md](https://github.com/keleshev/schema)

## FAQ

### Which Python data validation library should I use?

[Pydantic](#pydantic) suits most applications that model data as annotated classes. [jsonschema](#jsonschema) suits data that must match a portable JSON Schema document. [msgspec](#msgspec) suits services that decode and validate JSON or MessagePack at high speed.

### What is Pydantic?

[Pydantic](#pydantic) builds validated Python models from annotated field types. It coerces input to those types and returns structured errors, and strict mode narrows that coercion.

### Pydantic vs msgspec: which should I use?

[Pydantic](#pydantic) suits application models with rich validation and coercion. [msgspec](#msgspec) suits serialization paths, with typed decoding into structs and built-in support for JSON, MessagePack, YAML, and TOML.

### Pydantic vs marshmallow: which should I use?

[Pydantic](#pydantic) declares fields through type annotations on the model. [marshmallow](#marshmallow) declares fields explicitly on a separate schema that deserializes, validates, and serializes objects.

### How do I validate JSON against a schema in Python?

[jsonschema](#jsonschema) checks a parsed object against a JSON Schema document and reports each violation. [fastjsonschema](#fastjsonschema) compiles a schema into a reusable validation function.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Python data validation libraries Pydantic Marshmallow jsonschema Cerberus nested records coercion custom rules multiple errors code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
