1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Flask Post api not returning created object data as response

Discussão em 'Python' iniciado por Stack, Setembro 7, 2025.

  1. Stack

    Stack Membro Participativo

    I am writing flask sample application in which i have 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 parameter and create a store but response to that i need to return is id and name of store.Below if the code for 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.

    Continue reading...

Compartilhe esta Página