Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask POST not retrieved by request.json

I would like to create a REST-Api using Flask. As a "frame" I found this Tutorial which seemed to be really good about creating a REST-API using Flask and it also seems to be easy...

I have this function:

@app.route('/api/users', methods=['POST'])
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')

But when I try to post data using SOAPUI or HTTPRequester (in Firefox) I always get a server error 500

My application/json data looks like this:

{
 'username' : 'John',
 'password' : '1234'
}

And I checked that in both tols it is sent as application/json.

So I inserted the following before the request.json:

if not request.json:
    abort(400)

And now it aborts with code 400 - so it seems not to be a json object, right?

Then I inserted the following lines:

test = request
print test.data

Then I retrieve this in the console which looks tome like JSON:

{
    'username' : 'John',
    'password' : '1234'

    }

I know I could transform that into a dictionay using this:

dict = ast.literal_eval(test.data)

But I would like to use the standard functonality from flask.

Thank you in advance...

like image 482
Kev Avatar asked Jun 20 '26 02:06

Kev


1 Answers

First of all check your HTML headers sent by your client (JS or anything else). Content-Type should be application/json. And use request.get_json().

UPD: also you can try to use request.get_json(force=True, silent=True). And flask code for this method is very simple, you can debug it putting breakpoints or writing to log in it for better understanding what happens.

like image 93
Ivan Velichko Avatar answered Jun 21 '26 16:06

Ivan Velichko