Marshmallow with Python Flask
Marshmallow is a popular Python library used for object serialization and deserialization, often used with Flask, a web framework. It’s particularly useful for validating and transforming JSON data in Flask applications.
1. Setup Your Flask Application
First, you need to set up a basic Flask application. If you haven’t already, install Flask and Marshmallow:
pip install Flask MarshmallowCreate a file, app.py, and set up your Flask app:
from flask import Flask, request, jsonify
from marshmallow import Schema, fields, ValidationError
app = Flask(__name__)2. Define Your Schema with Marshmallow
Define a schema for your JSON data. This schema dictates how the data should be structured and what types are expected. For instance, if you’re expecting a JSON object with a name and age:
class UserSchema(Schema):
name = fields.Str(required=True)
age = fields.Int(required=True)3. Create a Route to Receive JSON Data
Now, create a Flask route where you’ll receive and validate JSON data:
@app.route('/user', methods=['POST'])
def create_user():
json_data = request.get_json()
if not json_data:
return jsonify({'message': 'No input data provided'}), 400
# Validate and deserialize input
schema = UserSchema()
try:
data = schema.load(json_data)
except ValidationError as err:
return jsonify(err.messages), 422
# Process the valid data (e.g., save to database)
# ...
return jsonify({'message': 'User created successfully', 'data': data}), 2014. Run Your Flask Application
Run your Flask application:
FLASK_APP=app.py flask run5. Test the API
You can test the API using a tool like curl or Postman. Send a POST request to http://localhost:5000/user with a JSON body. For example:
curl -X POST http://localhost:5000/user -H "Content-Type: application/json" -d '{"name":"John", "age":30}'This will return a success message if the JSON is valid or an error message if the JSON doesn’t match the schema.
Complex JSON Schema
Suppose you’re dealing with JSON data representing a user, where each user has a name, age, email, and a list of addresses. Each address itself is an object with street, city, and zip code.
Get Nithin Bharadwaj’s stories in your inbox
Join Medium for free to get updates from this writer.
Here’s how you can set up the Marshmallow schema for this complex JSON structure:
class AddressSchema(Schema):
street = fields.Str(required=True)
city = fields.Str(required=True)
zip_code = fields.Str(required=True)
class UserSchema(Schema):
name = fields.Str(required=True)
age = fields.Int(required=True)
email = fields.Email(required=True)
addresses = fields.List(fields.Nested(AddressSchema), required=True)@app.route('/user', methods=['POST'])
def create_user():
json_data = request.get_json()
if not json_data:
return jsonify({'message': 'No input data provided'}), 400
schema = UserSchema()
try:
data = schema.load(json_data)
except ValidationError as err:
return jsonify(err.messages), 422
# Process the validated data (e.g., save to a database)
# ...
return jsonify({'message': 'User created successfully', 'data': data}), 201Conclusion
This example demonstrates the basics of using Marshmallow with Flask for validating incoming JSON requests. This is a very basic setup, and for a real-world application, you’d likely need to add more complexity, such as database interactions, more comprehensive error handling, and possibly more complex validation logic.






