# Python Marshmallow Module

Marshmallow is an ORM/ODM/framework-agnostic library for converting complex data types, such as objects, to and from native Python datatypes. It is widely used for data validation and serialization.

## Installation

```bash
pip install marshmallow
```

## Defining a Schema

You define a schema to validate and serialize data.

```python
from marshmallow import Schema, fields

class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()
    created_at = fields.DateTime()
```

## Serialization (Dumping)

Converting objects to dictionaries (or JSON strings).

```python
from datetime import datetime

user_data = {
    "name": "Monty",
    "email": "monty@python.org",
    "created_at": datetime.now()
}

schema = UserSchema()
result = schema.dump(user_data)

print(result)
# Output: {'name': 'Monty', 'email': 'monty@python.org', 'created_at': '...'}
```

## Deserialization (Loading)

Converting dictionaries to objects (and validating them).

```python
json_input = {
    "name": "Monty",
    "email": "monty@python.org"
}

try:
    result = schema.load(json_input)
    print(result)
except ValidationError as err:
    print(err.messages)
```

## Validation

Marshmallow automatically validates data during deserialization based on field types.

[[programming/python/python]]