How to combine Flask REST API and Flask Web App?

630 views Asked by At

I am trying to combine api with app, but I have problems with POST.

I am able to do GET, when I try to POST 'item' using Web App GUI I receive: Method Not Allowed The method is not allowed for the requested URL.

Main section

api.add_resource(Item, '/api/v1/item/<string:name>')

if __name__ == '__main__':
    db.init_app(app)
    app.run(port=5001, debug=True)

API section

class Item(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument('price',
                    type=float,
                    required=True,
                    help="This field cannot be left blank!"
                    )
    parser.add_argument('store_id',
                    type=int,
                    required=True,
                    help="Every item needs a store id."
                    )

    def post(self, name):
        if ItemModel.find_by_name(name):
            return {'message': "An item with name '{}' already exists.".format(name)}, 400

        data = Item.parser.parse_args()
        item = ItemModel(name, **data)  # data['price'], data['store_id']

        try:
            item.save_to_db()
        except:
            return {"message": "An error occured inserting the item."}, 500  # Internal Server error

        return item.json(), 201

APP section

@app.route('/item/<name>', methods=['POST'])
def item(name):
    data = {
        'price': '16.99',
        'store_id': '1',
    }

    r = requests.post('http://localhost:5001/api/v1/item/'+name, data)
    return r.status_code

ItemModel

class ItemModel(db.Model):
     __tablename__ = 'items'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    price = db.Column(db.Float(precision=2))
    store_id = db.Column(db.Integer, db.ForeignKey('stores.id'))

    store = db.relationship("StoreModel")

def __init__(self, name, price, store_id):
    self.name = name
    self.price = price
    self.store_id = store_id

def json(self):
    return {
            'id': self.id,
            'name': self.name,
            'price': self.price,
            'store_id': self.store_id
        }

My point is that I would like to add items via GUI, form...

0

There are 0 answers