Sitemap

Flask-Marshmallow

2 min readOct 9, 2023

--

Press enter or click to view image in full size
Photo by Eliyah Reygaerts on Unsplash

Flask-Marshmallow is a bridge between Flask, a Python web framework and marshmallow which is a well received library for number of reasons, mainly for serialization and deserialization that provide additional features to marshmallow, including URL, and Hyperlinks fields for HATEOAS-ready APIs. It adds several functionalities such as data-validation and data-formatting.

Installation and set-up process:

Get Harpreet Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

Step 1: Write below written code into your terminal

pip install flask-marshmallow

Step 2: Add required imports and create your app.

from flask import Flask
from flask_marshmallow import Marshmallow

app = Flask(__name__)
ma = Marshmallow(app)

Step 3: Create models as per requirement of your application.

class User(db.Model):
__tablename__ = "users"

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
email = db.Column(db.String, unique=True)
_password_hash = db.Column(db.String)

Step 4: Now, generate your marshmallow schema. We can name schema like as I did in below snippet (singular/plural_user-schema) or we can also follow the generic way of doing it by naming it as user_schema and users_schema.

class UserSchema(ma.SQLAlchemySchema):
class Meta:
model = User

id = ma.auto_field()
name = ma.auto_field()
email = ma.auto_field()
_password_hash = ma.auto_field()

singular_user_schema = UserSchema(only=("id", "name", "email", "date_joined", "discussions"))
plural_user_schema = UserSchema(only=("id", "name", "email", "date_joined", "discussions"),many=True)

Step 5: Construct your API actions as per application requirement such as Get, Post, Patch and Delete.

class CurrentUser(Resource):
def get(self):

user_id = session.get("user_id")

user = User.query.get(user_id)

if not user:
return {"errors": ["User not found"]}, 404


return singular_user_schema.dump(user), 200

api.add_resource(CurrentUser, "/current_user")

Step 6: Now, with a proper database and POSTMAN we can test our APIs.

Press enter or click to view image in full size

Key attributes of flask-marshmallows:

  1. It enables the functionality to define validation rules for incoming data such as request parameter or JSON payload.
  2. We can convert complex data types into JSON or other web-suited formats and then later deserialize it into Python Objects, making it easier to work with data in the application.
  3. Flask-marshmallow is designed to integrate with Flask applications. It provides decorators and functionality of defining routes and different operations such as GET, POST, PATCH or DELETE as per requirement.
  4. In Flash-Marshmallow, data validations and serialization/deserialization rules are defined using “schemas”. These schemas act as building block in how data should look like and how it should be processed

--

--