How to set required = True for an parameter of json in python django?

Viewed 32

I am designing a web api. I am taking request body and want some parameters to be compulsarily available or that they cannot be empty.

For e.g.:-

request body = 
{
"user" : username,
""id" : ID,
"detail" : {
    "hair" : yes,
    "height" : 111,
    "weight" : 29
    }
}

I want to set "id" to be required=True, and "height" also required=True.

I searched and got how to set "id" required=True {fields.Str(required=True)}, But I am not getting how to set "height" required=True.

Thanks

1 Answers

You have to use the nested field: https://marshmallow.readthedocs.io/en/stable/marshmallow.fields.html#marshmallow.fields.Nested

For the height parameter, you can create a serializer for processing the "detail" field with marshmallow like this :

from rest_marshmallow import fields, Schema

class DetailSchema(Schema):
    hair = fields.String()
    width = fields.Integer()
    height = fields.Integer(required=True)

class RequestSchema(Schema):
    user = fields.String()
    id = fields.Integer(required=True)
    artist = fields.Nested(DetailSchema)

Related