0

With reference to the below code, I am getting an error while parsing the parameters for a GET request in Flask Restful.

from flask_restful import Resource, reqparse

class View_Result(Resource):

    def get(self):

        parser = reqparse.RequestParser()
        parser.add_argument('aid', type=str)
        print('Here 1')
        data = parser.parse_args()
        print('Here 2')

URL: http://127.0.0.1:8502/view_result?aid=1

Console:

Here 1
127.0.0.1 - - [09/Nov/2022 01:52:43] "GET /view_result?aid=1 HTTP/1.1" 400 -

Webpage:

{
    "message": "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."
}
Amit Pathak
  • 1,145
  • 11
  • 26

1 Answers1

1

First, you've defined a get method, but reqparse is designed to work with a JSON request body in a POST (or PUT) request. You would need:

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

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

class View_Result(Resource):

    def post(self):

        parser = reqparse.RequestParser()
        parser.add_argument('aid', type=str)
        print('Here 1')
        data = parser.parse_args()
        print('Here 2', data)

api.add_resource(View_Result, '/')

If I place the above code in resultful.py and then run it:

flask --debug --app restful run

I can make the following request:

curl localhost:5000 -H 'content-type: application/json' -d '{"aid": "foo"}'

And see on the application console:

Here 1
Here 2 {'aid': 'foo'}
127.0.0.1 - - [08/Nov/2022 17:23:08] "POST / HTTP/1.1" 200 -
larsks
  • 277,717
  • 41
  • 399
  • 399
  • I would like to have a `GET` request instead. But to my knowledge, I have already used `reqparse` with `GET` requests in some applications and it works fine. Any thoughts? – Amit Pathak Nov 09 '22 at 19:05
  • A GET request can't have a body, so `reqparse` seems like the wrong tool for the job. – larsks Nov 09 '22 at 20:42
  • I just came across [this answer](https://stackoverflow.com/a/30779996/11608962) which mentions that `reqparse` is deprecated. Used `request.args` to get these arguments. – Amit Pathak Nov 10 '22 at 17:03