1

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.

1
  • always show code with correct indentation because it can change everything. Commented Sep 7 at 15:02

1 Answer 1

1
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)
Sign up to request clarification or add additional context in comments.

1 Comment

that worked correctly.👍

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.