How to add structure to my api responses, I already have schemas defined

80 views Asked by At

I have an api project which uses flask smorest and marshmallow.

This is one of endpoints:

@blp.route("/posts/<int:post_id>")
class IndividualPost(MethodView):

    @blp.response(200, PostSchema)
    def get(self, post_id):
        post = PostModel.query.get_or_404(post_id)
        return post, 200

    def delete(self, post_id):
        post = PostModel.query.get_or_404(post_id)
        db.session.delete(post)
        db.session.commit()
        return {"message":"Post deleted"}, 200

I have to make it so that every response will be in the format:

{ "message": "Appropriate message", "status": status_code, "data": data_object }

The schema for marshmallow and swagger-ui:

class PlainPostSchema(Schema):
    id = fields.Int(dump_only=True)
    description = fields.String(required=False)
    created_at = fields.DateTime(dump_only=True)
    photo = fields.Str(dump_only=True)

Is there any way i can create a schema like:

class ISchema(Schema, AnySchemaClass):
    message = fields.String()
    status = fields.Int()
    data = fields.AnySchemaClass

I tried doing this:

class ISchema(Schema, AnySchemaClass):
    message = fields.String()
    status = fields.Int()
    data = fields.AnySchemaClass

But i cant do that since its a class

0

There are 0 answers