Nested Schemas for Complex Data Structures

Nested Schemas for Complex Data Structures

Good to see at another lesson! In this unit, we will explore how to handle and validate complex data structures by creating nested schemas. This is an essential skill when dealing with real-world data, which often includes nested relationships such as user profiles with nested address details.

By the end of this lesson, you will be able to:

  • Define and integrate nested schemas using Marshmallow.
  • Validate nested data structures within a Flask endpoint.

Let's dive in!

Basic Setup with Nested Data

Before we get started, let's briefly recap our basic Flask setup. This time we also introduced address information to our mock database to demonstrate handling nested data more effectively:

from flask import Flask

# Initialize a Flask app instance
app = Flask(__name__)

# Mock database as a list of dictionaries
database = [
    {"id": 1, "username": "cosmo", "email": "cosmo@example.com", "address": {"street": "123 Cosmic St", "city": "Cosmopolis"}},
    {"id": 2, "username": "jake", "email": "jake@example.com", "address": {"street": "456 Jake Blvd", "city": "Jaketown"}},
    {"id": 3, "username": "emma", "email": "emma@example.com", "address": {"street": "789 Emma Rd", "city": "Emmaville"}}
]

Now, let's build on this by adding functionality to handle nested data structures.

Creating Nested Schemas

First, we need to understand what nested schemas are. Nested schemas allow us to represent and validate complex data structures, where one schema is nested within another. For example, a user may have an address with its own schema.

We'll start by defining an AddressSchema for handling nested address data:

from marshmallow import Schema, fields

# Define a nested schema for address
class AddressSchema(Schema):
    street = fields.Str(required=True)
    city = fields.Str(required=True)

In this example:

  • We define the AddressSchema with two required fields: street and city.
  • The required=True argument ensures that both fields must be provided and follow their respective data types (string).

Defining the Main Schema with Nested Fields

Next, we integrate the AddressSchema into the main UserSchema to model complex user data that includes address information:

# Define a main schema for user with nested address
class UserSchema(Schema):
    id = fields.Int()
    username = fields.Str(required=True)
    email = fields.Email(required=True)
    address = fields.Nested(AddressSchema, required=True)

# Create an instance of the User schema
user_schema = UserSchema()

In this main schema, we introduce the address field using fields.Nested(). This means that the address field must conform to the structure and validation rules defined in the AddressSchema, and with the required=True argument, it ensures that the address field is mandatory.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal