Post/Code

HomeAboutUsesNow

Flask-RESTplus Nested Models.

It is often useful to nest models when working with Flask-RESTplus.

Let's say that you ultimately wanted your JSON output for a hypothetical restaurant to look as follows:

{
    "name": "The Fancy Restaurant",
    "description": "The best fusion cuisine in the world!",
    "location": {
        "lat": -99.999999,
        "lng": 99.999999
    },
    "social": {
        "instagram": "https://www.instagram.com/eatfancy"
    }
}

In order to do so, you could define your Flask-RESTplus models as follows.

Note - these are not the same as your SQLAlchemy models

...
from flask_restplus import Namespace, Resource, fields
...

api = Namespace("restaurants", description="Restaurants resource")

LOCATION = api.model(
    "LOCATION",
    {
        "lat": fields.Float(
            required=True,
            description="The made-up latitude co-ordinates of the restaurant",
            example="-99.999999",
        ),
        "lng": fields.Float(
            required=True,
            description="The made-up longitude co-ordinates of the restaurant",
            example="99.999999",
        ),
    },
)


SOCIAL = api.model(
    "SOCIAL",
    {
        "instagram": fields.String(
            required=False,
            description="The official Instragram handle for the restaurant",
        )
    },
)

RESTAURANT = api.model(
    "RESTAURANT",
    {
        "id": fields.String(
            readOnly=True, description="The restaurant id", example="1"
        ),
        "name": fields.String(
            required=True,
            description="The name of the restaurant",
            example="The Fancy Restaurant",
        ),
        "description": fields.String(
            required=True,
            description="A short (less than 255 characters) description of the restaurant",
            example="The best fusion cuisine in the world!",
        ),
        "location": fields.Nested(LOCATION),
        "social": fields.Nested(SOCIAL),
    },
)
...