3

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.

ishy147
  • 33
  • 1
  • 6
  • What is the output if you add `print(args['name'])` before returning in the put method of Product class in main.py – darth baba Apr 08 '22 at 10:18
  • 2
    i got `{'message': "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."}` – ishy147 Apr 08 '22 at 10:47

1 Answers1

11

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)
darth baba
  • 1,277
  • 5
  • 13