Reputation: 876
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?
Upvotes: 5
Views: 5670
Reputation: 88378
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.
Upvotes: 7