Open In App

Flask Serialization and Deserialization

Last Updated : 01 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Serialization and deserialization are fundamental concepts in web development, especially when working with REST APIs in Flask. Serialization refers to converting complex data types (such as Python objects) into a format that can be easily stored or transmitted, like JSON or XML. Deserialization, on the other hand, is the process of converting serialized data back into Python objects.

Flask provides several ways to handle serialization and deserialization efficiently, whether using built-in modules like json, third-party libraries like marshmallow or Flask-RESTful’s request parsing.

Significance of Serialization an Deserialization

  • Data Exchange: APIs need to send and receive data in a structured format.
  • Security: Proper serialization prevents data tampering and ensures data integrity.
  • Validation: Deserialization allows for data validation before processing it.
  • Performance: Optimized serialization improves API performance.

Let's discuss both of them one by one:

Serialization in Flask

Serialization involves converting Python objects into a format like JSON so they can be transmitted over the network. Without it, applications would struggle to communicate, as Python objects cannot be directly transferred over HTTP. There are several ways to serialize in Flask Python, let's see some of them with examples:

Using Flask’s jsonify

Flask provides the jsonify function, which automatically serializes Python dictionaries and lists into JSON.

Python
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/data')
def get_data():
    data = {"name": "Alice", "age": 25, "city": "New York"}
    return jsonify(data)  # Flask automatically serializes it to JSON

if __name__ == '__main__':
    app.run(debug=True)

Output
{
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

Explanation:

  • jsonify(data) converts the Python dictionary into a JSON response.
  • Flask automatically sets the correct Content-Type as application/json.

Using Python’s json Module

We can also use Python’s built-in json module for manual serialization, such as logging or saving data. It's useful in scenarios where Flask’s jsonify isn’t required.

Python
import json

data = {"name": "Bob", "age": 30}
json_data = json.dumps(data)  # Converts Python dict to JSON string
print(json_data)

Output
{"name": "Bob", "age": 30}

Deserialization in Flask

Deserialization is the reverse process of serialization. It allows a Flask application to read and process incoming JSON data, converting it into a usable Python object.

Using request.get_json()

Flask’s request.get_json() automatically parses incoming JSON requests, making it easy to extract and process data.

Python
from flask import Flask, request, jsonify  

app = Flask(__name__)  

@app.route('/submit', methods=['POST'])  
def receive_data():  
    data = request.get_json()  # Deserialize JSON request into Python dict  
    return jsonify({"message": "Data received", "data": data})  

if __name__ == '__main__':  
    app.run(debug=True)  

Explanation:

  • request.get_json() extracts the JSON data from the request body.
  • The data is returned as a Python dictionary, making it easy to work with in Flask.

Test the application in Postman API app. Make a POST request to the development URL and provide the JSON data in raw tab:

Serialization1
POST Request

Using marshmallow for Serialization and Deserialization

While Flask provides basic serialization and deserialization capabilities, marshmallow enhances them with data validation and structured schemas, ensuring data integrity.

Install marshmallow using this command:

pip install flask-marshmallow

To demonstrate the working of marshmallow let's create a Flask app in which we define a UserSchema using marshmallow, which ensures that the incoming JSON data includes a valid username and email. The schema validates the request before processing it, reducing errors and improving data integrity.

Python
from flask import Flask, request, jsonify  
from marshmallow import Schema, fields  

app = Flask(__name__)  

# Define a Schema  
class UserSchema(Schema):  
    username = fields.String(required=True)  
    email = fields.Email(required=True)  

user_schema = UserSchema()  

@app.route('/validate', methods=['POST'])  
def validate_user():  
    json_data = request.get_json()  
    errors = user_schema.validate(json_data)  
    
    if errors:  
        return jsonify(errors), 400  # Return validation errors  
    
    return jsonify({"message": "Valid data", "data": json_data})  

if __name__ == '__main__':  
    app.run(debug=True)  

Explanation:

  • /validate route accepts POST requests.
  • request.get_json() extracts incoming JSON data.
  • user_schema.validate(json_data) checks if the provided data matches the schema.
  • Return the error messages with an HTTP 400 (Bad Request) status if the validation fails.
  • If the data is valid, return a success message along with the provided data.

Run the application and then open Postman API application to test the it. Below is the snapshot of testing the application on POST method on /validate endpoint of the application:

Serialization2
POST request

Next Article
Article Tags :
Practice Tags :

Similar Reads