12

This question is kind of duplicate but I could not find a solution to it. When I am calling the flask app and passing the JSON data, I am getting the error:

"Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)</p>"

Below is the flask code:

@app.route('/data_extraction', methods=['POST'])
def check_endpoint2():   
    data= request.json()
    result = data['title']
    out={"result": str(result)}
    return json.dumps(out)
    #return 'JSON Posted'

This is how I am calling it from curl

curl -i -H "Content-Type: application/json" charset=utf-8 -X POST -d '{"title":"Read a book"}' 127.0.0.1:5000/data_extraction

I also want to know how can I curl the JSON file(test_data.json), will it be like this?

curl -i -H "Content-Type: application/json" charset=utf-8 -X POST -d @test_data.json 127.0.0.1:5000/data_extraction
vvvvv
  • 25,404
  • 19
  • 49
  • 81
Cathy
  • 367
  • 1
  • 3
  • 16

5 Answers5

6

You're mostly there. The problem is the -d overrides the Content-Type header that you're providing. Try --data instead of -d.

And change data = request.json() to data = request.json.

Dave W. Smith
  • 24,318
  • 4
  • 40
  • 46
  • 1
    it did this: curl -i -H "Content-Type: application/json; charset=utf-8" -X POST --data '{"title":"Read a book"}' 127.0.0.1:5000/data_extraction – Cathy Feb 01 '19 at 16:24
3

The phrase 'charset=utf-8' should be within 'Content-Type' header, like this: "Content-Type: application/json; charset=utf-8"

haikku
  • 31
  • 2
  • it did this: curl -i -H "Content-Type: application/json; charset=utf-8" -X POST --data '{"title":"Read a book"}' 127.0.0.1:5000/data_extraction – Cathy Feb 01 '19 at 16:24
2

I encountered it in Pytest, solved it by

import json

def test_login():
   payload = {"ecosystem":'abc'}
   accept_json=[('Content-Type', 'application/json;')]
   response = client.post('/data_extraction'), data=json.dumps(payload), headers=accept_json)

   assert response.data == {'foo': 'bar'}
Deepak Sharma
  • 1,401
  • 19
  • 21
1

I know this a bit old question, but anyways, double quotes in JSON must be escaped with the backslash . Therefore, the Request should be something like:

curl -X POST http://127.0.0.1:5000/ -H "Content-Type: application/json" -d "{\"Name\":\"Nada\",\"Address\":\"my_address\"}"

So, your request can look like

curl -X POST 127.0.0.1:5000/data_extraction -H "Content-Type: application/json" -d "{\"title\":\"Read a book\"}" 
MNada
  • 353
  • 2
  • 6
  • 14
0

Maybe you should not set the Content-Type to application/json, cancel it and retry it. I have encountered the same problem as you, and I solved it like this.

Runstone
  • 368
  • 2
  • 8