I'm creating a frontend in Angular, and the backend in Flask with the RESTful extension. By default, Angular likes to send data back as a payload (eg this is what it appears like in Chrome Developer tools: ). I am also aware it can easily format this in to a JSON payload, which will be preferable for a few other cases on other endpoints.
What is the best way to use the argument parser in RESTful to deal with this? If I encode things as form data they can be read by reqparse, but not just a raw payload like this (although from reading their documentation and source, it seems like it should be able to handle more than this). I am aware that by using the 'location' arg in reqparse it will look elsewhere (by default it looks in form
and json
). However, anything not sent via form fields does not seem to be parsed, despite anything I try (Even when explicitly setting location to include every attribute of the request
, eg json, args). Sample code appears like:
class Login(restful.Resource):
def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('user', type=str, required=True)
self.parser.add_argument('passw', type=str, required=True)
def post(self):
args = self.parser.parse_args()
# Some logic here
return self.response
Is there something I am doing wrong to not be able to read args?
It seems like Flask-Restful isn't actively maintained anymore according to https://github.com/flask-restful/flask-restful/issues/883, which lists alternatives, including Marshmallow in place of reqparse.
Flask Restful is an extension for Flask that adds support for building REST APIs in Python using Flask as the back-end. It encourages best practices and is very easy to set up. Flask restful is very easy to pick up if you're already familiar with flask.
reqparse has been deprecated (https://flask-restful.readthedocs.io/en/latest/reqparse.html):
With resources defined and everything connected with Blueprints, it's time to handle incoming arguments. Flask-RESTful provides a solid tool known as Reqparse for specifying and validating submitted data.
You will, I think, need to do the following:
(1) Make location='json'
explicit in add_argument
:
self.parser.add_argument('user', type=str, location='json', required=True)
self.parser.add_argument('passw', type=str, location='json', required=True)
(2) Ensure the header field Content-Type
of the http request from the client is application/json
(3) The request payload should look like this:
{
"user": "abc",
"passw": "123456"
}
I routinely parse JSON requests with flask-restful without any trouble. One small difference is that I don't have my request parser as an instance field of the resource. Not sure if that is causing you trouble, but it might be worth a try to move it out if you are still stuck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With