u936293
u936293

Reputation: 16264

How is json data posted?

My flask code is as follows:

@app.route('/sheets/api',methods=["POST"])
def insert():
    if request.get_json():
        return "<h1>Works! </h1>"
    else:
        return "<h1>Does not work.</h1>"

When the request is:

POST /sheets/api HTTP/1.1
Host: localhost:10080
Cache-Control: no-cache

{'key':'value'}

The result is <h1>Does not work.</h1>.

When I added a Content-Type header:

POST /sheets/api HTTP/1.1
Host: localhost:10080
Content-Type: application/json
Cache-Control: no-cache

{'key':'value'}

I get a 400 error.

What am I doing wrong?

Upvotes: 1

Views: 93

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124548

You are not posting valid JSON. JSON strings use double quotes:

{"key":"value"}

With single quotes the string is not valid JSON and a 400 Bad Request response is returned.

Demo against a local Flask server implementing only your route:

>>> import requests
>>> requests.post('http://localhost:5000/sheets/api', data="{'key':'value'}", headers={'content-type': 'application/json'}).text
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>400 Bad Request</title>\n<h1>Bad Request</h1>\n<p>The browser (or proxy) sent a request that this server could not understand.</p>\n'
>>> requests.post('http://localhost:5000/sheets/api', data='{"key":"value"}', headers={'content-type': 'application/json'}).text
'<h1>Works! </h1>'

Upvotes: 5

Related Questions