Home > OS >  Issue with bad request syntax with flask
Issue with bad request syntax with flask

Time:04-08

I am testing/attempting to learn flask, and flast_restful. This issue I get is:

code 400, message Bad request syntax ('name=testitem')

main.py:

from flask import Flask,request
from flask_restful import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)

product_put_args = reqparse.RequestParser()
product_put_args.add_argument("name", type = str, help = "Name of the product")
product_put_args.add_argument("quantity", type = int, help = "Quantity of the item")

products = {}

class Product(Resource):
    def get(self, barcode):
        return products[barcode]

    def put(self, barcode):
        args = product_put_args.parse_args()
        return {barcode: args}

api.add_resource(Product, "/product/<int:barcode>")

if(__name__) == "__main__":
    app.run(debug = True)

and my test.py

import requests

base = "http://127.0.0.1:5000/"

response = requests.put(base   "product/1", {"name": "testitem"})
print(response.json())

I have attempted to reform mat and change around both files to figure out what is sending the issue, I feel like it is something simple, but if you can help me, I bet this will help me and many others that are trying to start creating a rest API.

CodePudding user response:

You need to add the location information to the RequestParser by default it tries to parse values from flask.Request.values, and flask.Request.json, but in your case, the values need to be parsed from a flask.request.form. Below code fixes your error

from flask import Flask,request
from flask_restful import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)

product_put_args = reqparse.RequestParser()
product_put_args.add_argument("name", type = str, help = "Name of the product", location='form')
product_put_args.add_argument("quantity", type = int, help = "Quantity of the item", location='form')

products = {}

class Product(Resource):
    def get(self, barcode):
        return products[barcode]

    def put(self, barcode):
        args = product_put_args.parse_args()
        products[barcode] = args['name']
        return {barcode: args}

api.add_resource(Product, "/product/<int:barcode>")

if(__name__) == "__main__":
    app.run(debug = True)
  • Related