9

I'm setting up a simple rest api using flask and flask-restful. Right now all I'm trying to do is create a post request with some Json data, and then return it just to see if it works. I always get the same error "message": "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)"

Below is my code

from flask import Flask, jsonify, request
from flask_restful import Resource, Api

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


class Tester(Resource):
   def get(self):
       return {'about': 'Hello World'}

   def post(self):
       data_json = request.get_json(force=True)
       return {'you sent': data_json}


api.add_resource(Tester, '/')

if __name__ == '__main__':
    app.run(debug=True)

The curl request I am making to test this is below, I've also tried making request using postman

curl -H "Content-Type: application/json" -X POST -d '{'username':"abc",'password':"abc"}' http://localhost:5000
FProlog
  • 173
  • 1
  • 1
  • 9

4 Answers4

11

You need to select raw -> JSON (application/json) in Postman like this:

enter image description here

When it comes to your cURL request, answer explains that windows's command line lacks support of strings with single quotes, so use:

curl -i -H "Content-Type: application/json" -X POST -d "{\"username\":\"abc\", \"password\":\"abc\"}" 127.0.0.1:5000

instead:

curl -H "Content-Type: application/json" -X POST -d '{'username':"abc",'password':"abc"}' http://localhost:5000

\ escapes " character.

alessiosavi
  • 2,753
  • 2
  • 19
  • 38
bc291
  • 1,071
  • 11
  • 23
3

You also need to have the Content-Length header enabled.

Without header

With header

Anon
  • 99
  • 7
2

Some additional information in case you are using python script to test your flask api like me - you have to dumps before adding the dictionary to the data field.

import requests
import json

response = requests.post(
    'http://localhost:5000', 
    data = json.dumps({'username':"abc",'password':"abc"}),
    headers = {"Content-Type": "application/json"}
    )

ChrisQIU
  • 306
  • 2
  • 6
  • This answer solved my problem. Got rid of the JSON decode error and also converts `datetime.datetime(2019, 4, 3, 9, 47, 9, 427000)` to `2019-04-03 09:47:09.427000` on the fly. `>>> json.dumps({'datetime':'datetime.datetime(2019, 4, 3, 9, 47, 9, 427000)'})` `output: {'datetime':'2019-04-03 09:47:09.427000'}` – Banty Feb 06 '23 at 18:04
0

The curl request (payload) is incorrect. Use double quotes in the payload.

curl -H "Content-Type: application/json" -X POST -d '{"username":"abc","password":"abc"}' http://localhost:5000
DhoTjai
  • 151
  • 1
  • 6