pythonflask

Flask Post api not returning created object data as response


I am writing a flask sample application in which I have the following model and schemas.

PlainStore schema is as following:

class PlainStoreSchema(Schema):
    id = fields.Str(dump_only=True)
    name = fields.Str(required=True)

Item schema is like:

class ItemSchema(PlainItemSchema):
    store_id = fields.Int(required=True)
    store_name = fields.Nested(PlainStoreSchema(), dump_only=True)

Store schema is:

class StoreSchema(Schema):
    # store_id = fields.Int(dump_only=True)
    items = fields.List(fields.Nested(PlainItemSchema()), dump_only=True)

I am writing a POST API endpoint which will accept just a name as a parameter and create a store but response to that I need to return is id and name of store. Below is the code for the endpoint:

@blp.route("/store")
class StoreList(MethodView):
    @blp.response(200, StoreSchema(many=True))
    def get(self):
        return StoreModel.query.all()

    @blp.arguments(PlainStoreSchema)
    @blp.response(201, StoreSchema)
    def post(self, store_data):
        try:
            store = StoreModel(**store_data)
            db.session.add(store)
            db.session.commit()
        except IntegrityError:
            abort(400, message="Store already exists")
        except SQLAlchemyError as e:
            abort(500, message="Error occurred while saving store data")
        return store, 201

Store model is:

class StoreModel(db.Model):
    __tablename__ = "store"

    id = db.Column(db.Integer, primary_key=True, unique=True)
    name = db.Column(db.String(100), nullable=False, unique=True)
    items = db.relationship("ItemModel", back_populates="store", lazy="dynamic")

    def __repr__(self):
        return f"<StoreModel id={self.id} name={self.name}>"

With all this code when I try to hit POST API with name parameter I get only following in response

{
    "items": []
}

I tried referred this Python Flask post and return json objects but here they are manually trying to return json response.


Solution

  • class StoreSchema(Schema):
        items = fields.List(fields.Nested(PlainItemSchema()), dump_only=True)
    

    Rather than this you need to inherit from PlainStoreSchema for the id.

    class StoreSchema(PlainStoreSchema):
        items = fields.List(fields.Nested(PlainItemSchema()), dump_only=True)