Search code examples
pythonapihttpflaskflask-restful

Explanation on how this doesn't work? ( Flask-restful API)


I'm using some code that worked some months ago, it uses Flask and Flask_restful to work and I stumped upon something really extrange, the API doesn't work, but doesn't give me an error, from flask_restful I use reqparse to get the arguments, but whenever I use the method .parse_args() the response that I have to give doesn't pass through

code example:

class Ping (Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument ("lang")
        # args = parser.parse_args()
        return {
            "message": "any message",
        }, 200

response:

{
    "message": "any message"
}

but when I use the parse_args() without even using the variable:

code:

class Ping (Resource):
    def get(self):
        parser = reqparse. RequestParser()
        parser.add_argument("lang")
        args = parser.parse_args()
        return {
            "message": "any message",
        }, 200

response:

{
    "message": "Failed to decode JSON object: None"
}

could someone explain what happens? what is happening?

I'm using python 3.8

I expected to have the message given in the code, but instead I have this message everytime, I tried different paths, rewriting the class, nothing worked, if someone knows a way to get through this or if someone knows a way to get the parameters of the url in some way it would be very helpful.


Solution

  • I have just found the solution, I saw the solution in this post: Flask-Limiter is not called on Flask-Restful API's method_decorators

    the solution to this problem is really simple, when adding an argument in the parser you have to pass an arg called 'location' which will be the name of the variable when you call parse_args()

    per example:

    instead of this

        parser = reqparse.RequestParser()
    
        parser.add_argument("lang")
    
        args = parser.parse_args()
    

    write this:

        parser = reqparse.RequestParser()
    
        parser.add_argument("lang", location='args')
    
        args = parser.parse_args()
    

    if you pass in the location a different name from the value of parser.parse_args() it will give you null values even when in the url there's a value given to the argument