MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Data Serialization & Validation with Marshmallow0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
8.1Building JSON APIs with jsonify & Status Codes8.2Data Serialization & Validation with Marshmallow8.3Stateless JWT Authentication with Flask-JWT-Extended
HomeTutorialsFlaskData Serialization & Validation with Marshmallow
Stateless JWT Authentication with Flask-JWT-Extended

Data Serialization & Validation with Marshmallow

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While manually parsing dictionaries (data["title"]) works for simple endpoints, enterprise REST APIs require strict contract enforcement: schema validation, type coercion, and serializing complex SQLAlchemy ORM models into clean JSON dictionaries.

Marshmallow is the industry-standard Python library for object serialization, deserialization, and validation.


1. Installing Marshmallow & Flask Integration

1pip install marshmallow flask-marshmallow marshmallow-sqlalchemy
  • marshmallow: Core schema engine.
  • flask-marshmallow: Flask routing integration (e.g. hyperlinking).
  • marshmallow-sqlalchemy: Automatically generates schemas from SQLAlchemy models!

2. Defining Schemas

A Schema declares how fields are serialized (ORM to JSON) and deserialized (JSON to Python):

1from marshmallow import Schema, fields, validate, post_load
2 
3class CourseSchema(Schema):
4 # Read-only primary key (dump_only: serialized to output, ignored on input)
5 id = fields.Int(dump_only=True)
6
7 title = fields.Str(
8 required=True,
9 validate=[
10 validate.Length(min=5, max=150, error="Title must be between 5 and 150 characters.")
11 ]
12 )
13 slug = fields.Str(required=True)
14 price = fields.Decimal(
15 as_string=True,
16 required=True,
17 validate=[validate.Range(min=0, error="Price cannot be negative.")]
18 )
19 is_published = fields.Bool(load_default=False)
20 created_at = fields.DateTime(dump_only=True)
21 
22# Instantiate schemas for single objects and collections
23course_schema = CourseSchema()
24courses_schema = CourseSchema(many=True)

3. Serialization (Dumping: Python Object -> JSON Dict)

Convert SQLAlchemy model instances into JSON-serializable dictionaries using .dump():

1from flask import jsonify
2from models import Course
3 
4@app.route("/api/v1/courses")
5def get_courses():
6 courses = Course.query.filter_by(is_published=True).all()
7
8 # Serializes list of Course ORM models into clean list of dicts!
9 result = courses_schema.dump(courses)
10 return jsonify(result), 200
11 
12@app.route("/api/v1/courses/<int:course_id>")
13def get_course(course_id):
14 course = Course.query.get_or_404(course_id)
15 return jsonify(course_schema.dump(course)), 200

4. Deserialization & Validation (Loading: JSON Dict -> Clean Python Data)

When creating or updating resources, use .load() to validate incoming payloads. If validation fails, Marshmallow raises a ValidationError containing an organized dictionary of field errors:

1from flask import request, jsonify
2from marshmallow import ValidationError
3from models import db, Course
4 
5@app.route("/api/v1/courses", methods=["POST"])
6def create_course():
7 json_data = request.get_json(silent=True)
8 if not json_data:
9 return jsonify({"error": "No input data provided"}), 400
10 
11 try:
12 # Validate and deserialize input
13 clean_data = course_schema.load(json_data)
14 except ValidationError as err:
15 # Returns organized map of field errors with HTTP 422!
16 # e.g.: {"price": ["Price cannot be negative."], "title": ["Field is required."]}
17 return jsonify({"errors": err.messages}), 422
18 
19 # Instantiate model with validated data
20 new_course = Course(**clean_data)
21 db.session.add(new_course)
22 db.session.commit()
23 
24 return jsonify(course_schema.dump(new_course)), 201

5. Automated Schemas with SQLAlchemyAutoSchema

With marshmallow-sqlalchemy, you do not need to rewrite columns that already exist on your model:

1from flask_marshmallow import Marshmallow
2from models import Course
3 
4ma = Marshmallow(app)
5 
6class CourseAutoSchema(ma.SQLAlchemyAutoSchema):
7 class Meta:
8 model = Course
9 load_instance = True # Automatically deserializes into Course() instances!
10 include_fk = True
11 
12auto_course_schema = CourseAutoSchema()

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What Marshmallow method converts a Python/ORM object into a JSON-compatible dictionary?
Question 2
What method validates and deserializes incoming JSON data into clean Python data?
Question 3
What exception is raised by Marshmallow when input data violates validation constraints?
Question 4
What does setting dump_only=True on a schema field accomplish?
Question 5
How do you serialize a list of multiple model objects using a Marshmallow schema?
Next Lesson

Stateless JWT Authentication with Flask-JWT-Extended

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Building JSON APIs with jsonify & Status CodesStateless JWT Authentication with Flask-JWT-Extended

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext