How to get POSTed json in Flask?
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the post with the PostMan Chrome extension, and the JSON I post is simply {"text":"lalala"}
. I try to read the JSON using the following method:
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content
return uuid
On the browser it correctly returns the uuid I put in the GET, but on the console, it just prints out None
(where I expect it to print out the {"text":"lalala"}
. Does anybody know how I can get the posted JSON from within the Flask method?
python json post flask
add a comment |
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the post with the PostMan Chrome extension, and the JSON I post is simply {"text":"lalala"}
. I try to read the JSON using the following method:
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content
return uuid
On the browser it correctly returns the uuid I put in the GET, but on the console, it just prints out None
(where I expect it to print out the {"text":"lalala"}
. Does anybody know how I can get the posted JSON from within the Flask method?
python json post flask
add a comment |
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the post with the PostMan Chrome extension, and the JSON I post is simply {"text":"lalala"}
. I try to read the JSON using the following method:
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content
return uuid
On the browser it correctly returns the uuid I put in the GET, but on the console, it just prints out None
(where I expect it to print out the {"text":"lalala"}
. Does anybody know how I can get the posted JSON from within the Flask method?
python json post flask
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the post with the PostMan Chrome extension, and the JSON I post is simply {"text":"lalala"}
. I try to read the JSON using the following method:
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content
return uuid
On the browser it correctly returns the uuid I put in the GET, but on the console, it just prints out None
(where I expect it to print out the {"text":"lalala"}
. Does anybody know how I can get the posted JSON from within the Flask method?
python json post flask
python json post flask
edited Mar 3 '15 at 14:26
Martijn Pieters♦
715k13724972310
715k13724972310
asked Nov 15 '13 at 12:35
kramer65kramer65
10k58181321
10k58181321
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
You need to set the request content type to application/json
for the .json
property to work; it'll be None
otherwise. See the Flask Request
documentation:
This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see
is_json()
), otherwise it will beNone
.
Flask 0.10 added the request.get_json()
method, and you should use that method instead of the .json
property. You can tell the method to skip the content type requirement by setting force=True
.
Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.
3
Alright. And would you have any idea how to do that?
– kramer65
Nov 15 '13 at 12:49
8
@kramer65: How are you posting the request now? The client has to set the header; if you are usingrequests
, that'd berequest.post(url, headers={'Content-Type': 'application/json'}, data=json.dumps({'text': 'lalala'})
.
– Martijn Pieters♦
Nov 15 '13 at 12:52
1
Ah, now I understand. I had to set it at the sending party (i.e.: in PostMan). Okay, so I set that to json, butrequest.json
is still a NoneType. ANy idea what else I could do wrong?
– kramer65
Nov 15 '13 at 12:57
5
@kramer65: See the source code; Either theContent-Type
header is wrong, or the JSON you sent was'null'
, which translates toNone
. Everything else raises an exception or returns your dictionary. Tryrequest.get_json(force=True)
; this will ignore the header requirement.
– Martijn Pieters♦
Nov 15 '13 at 13:00
1
Okay! "I" fixed it! Usingget_json(force=True)
fixed it, but you were right all along; I set the content type in PostMan to JSON, but I didn't specifically set a header. So I now set the header and it all works fine. Thanks for the awesome help!
– kramer65
Nov 15 '13 at 13:04
|
show 9 more comments
For reference, here's complete code for how to send json from a Python client:
import requests
res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"})
if res.ok:
print res.json()
The "json=" input will automatically set the content-type, as discussed here: Post JSON using Python Requests
And the above client will work with this server-side code:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content['mytext']
return jsonify({"uuid":uuid})
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug=True)
This actually didn't work for me. With python 2.7 if I specify the <uuid> argument the request gets denied with a 404. This is when sending a valid JSON POST with both Postman and a ReactJS application. If I omit the arg it works just fine.
– Omortis
Feb 23 '17 at 20:28
2
This example definitely works with Python 2.7. Make sure you actually have the "<" and ">" in the app.route. The left/right carets are part of the required Flask syntax.
– Luke
Feb 24 '17 at 2:08
1
Yes, it does work. I was burying my request details in the JSON payload, not in the URI (as in: no arg supplied). Sorry for the static!
– Omortis
Feb 27 '17 at 13:01
add a comment |
This is the way I would do it and it should be
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.get_json(silent=True)
# print(content) # Do your processing
return uuid
With silent=True
set, the get_json
function will fail silently when trying to retrieve the json body. By default this is set to False
.
Setting force=True
will ignore the
request.headers.get('Content-Type') == 'application/json'
check that flask does for you. By default this is also set to False
.
See flask documentation.
I would strongly recommend leaving force=False
and make the client send the Content-Type
header to make it more explicit.
Hope this helps!
4
Isn't it better to fail on errors??
– vidstige
Oct 4 '16 at 9:02
1
Depends if the json body is optional or not, so depends on your case
– radtek
Oct 5 '16 at 18:37
1
I cannot see any case where it would make sense to some times post valid json and other times invalid json. Sounds like two different end points
– vidstige
Oct 5 '16 at 18:39
1
Like I said, if an endpoint takes "optional" json body, you can usesilent=True
. Yes this is possible, and I do use it. Its really based on how you design your API to be consumed. If there is no case like that for your endpoint, just removesilent=True
or explicitly set it toFalse
.
– radtek
Oct 5 '16 at 18:57
For clarity, theprint(content)
aftercontent = request.get_json()
prints the object... but as a valid Python object (and not as a valid JSON object). For example, it uses single quotes while JSON strictly requires double quotes for both the key values (strings) as string values. If you want the JSON representation, usejson.dumps()
with the object.
– Jochem Schulenklopper
Nov 12 '18 at 15:59
add a comment |
This solution works:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['POST'])
def hello():
return jsonify(request.json)
3
To add to this answer the request you could send to this endpoint could beresponse = request.post('http://127.0.0.1:5000/hello', json={"foo": "bar"})
. Following this runningresponse.json()
should return{'foo': 'bar'}
– ScottMcC
Jun 11 '17 at 8:54
It could be noted that{'foo': 'bar'}
isn't valid JSON though. It could be a valid Python object representation that looks a lot like JSON, but valid JSON strictly uses double quotes.
– Jochem Schulenklopper
Nov 12 '18 at 15:42
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20001229%2fhow-to-get-posted-json-in-flask%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
You need to set the request content type to application/json
for the .json
property to work; it'll be None
otherwise. See the Flask Request
documentation:
This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see
is_json()
), otherwise it will beNone
.
Flask 0.10 added the request.get_json()
method, and you should use that method instead of the .json
property. You can tell the method to skip the content type requirement by setting force=True
.
Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.
3
Alright. And would you have any idea how to do that?
– kramer65
Nov 15 '13 at 12:49
8
@kramer65: How are you posting the request now? The client has to set the header; if you are usingrequests
, that'd berequest.post(url, headers={'Content-Type': 'application/json'}, data=json.dumps({'text': 'lalala'})
.
– Martijn Pieters♦
Nov 15 '13 at 12:52
1
Ah, now I understand. I had to set it at the sending party (i.e.: in PostMan). Okay, so I set that to json, butrequest.json
is still a NoneType. ANy idea what else I could do wrong?
– kramer65
Nov 15 '13 at 12:57
5
@kramer65: See the source code; Either theContent-Type
header is wrong, or the JSON you sent was'null'
, which translates toNone
. Everything else raises an exception or returns your dictionary. Tryrequest.get_json(force=True)
; this will ignore the header requirement.
– Martijn Pieters♦
Nov 15 '13 at 13:00
1
Okay! "I" fixed it! Usingget_json(force=True)
fixed it, but you were right all along; I set the content type in PostMan to JSON, but I didn't specifically set a header. So I now set the header and it all works fine. Thanks for the awesome help!
– kramer65
Nov 15 '13 at 13:04
|
show 9 more comments
You need to set the request content type to application/json
for the .json
property to work; it'll be None
otherwise. See the Flask Request
documentation:
This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see
is_json()
), otherwise it will beNone
.
Flask 0.10 added the request.get_json()
method, and you should use that method instead of the .json
property. You can tell the method to skip the content type requirement by setting force=True
.
Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.
3
Alright. And would you have any idea how to do that?
– kramer65
Nov 15 '13 at 12:49
8
@kramer65: How are you posting the request now? The client has to set the header; if you are usingrequests
, that'd berequest.post(url, headers={'Content-Type': 'application/json'}, data=json.dumps({'text': 'lalala'})
.
– Martijn Pieters♦
Nov 15 '13 at 12:52
1
Ah, now I understand. I had to set it at the sending party (i.e.: in PostMan). Okay, so I set that to json, butrequest.json
is still a NoneType. ANy idea what else I could do wrong?
– kramer65
Nov 15 '13 at 12:57
5
@kramer65: See the source code; Either theContent-Type
header is wrong, or the JSON you sent was'null'
, which translates toNone
. Everything else raises an exception or returns your dictionary. Tryrequest.get_json(force=True)
; this will ignore the header requirement.
– Martijn Pieters♦
Nov 15 '13 at 13:00
1
Okay! "I" fixed it! Usingget_json(force=True)
fixed it, but you were right all along; I set the content type in PostMan to JSON, but I didn't specifically set a header. So I now set the header and it all works fine. Thanks for the awesome help!
– kramer65
Nov 15 '13 at 13:04
|
show 9 more comments
You need to set the request content type to application/json
for the .json
property to work; it'll be None
otherwise. See the Flask Request
documentation:
This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see
is_json()
), otherwise it will beNone
.
Flask 0.10 added the request.get_json()
method, and you should use that method instead of the .json
property. You can tell the method to skip the content type requirement by setting force=True
.
Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.
You need to set the request content type to application/json
for the .json
property to work; it'll be None
otherwise. See the Flask Request
documentation:
This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see
is_json()
), otherwise it will beNone
.
Flask 0.10 added the request.get_json()
method, and you should use that method instead of the .json
property. You can tell the method to skip the content type requirement by setting force=True
.
Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.
edited Jan 22 at 13:36
answered Nov 15 '13 at 12:38
Martijn Pieters♦Martijn Pieters
715k13724972310
715k13724972310
3
Alright. And would you have any idea how to do that?
– kramer65
Nov 15 '13 at 12:49
8
@kramer65: How are you posting the request now? The client has to set the header; if you are usingrequests
, that'd berequest.post(url, headers={'Content-Type': 'application/json'}, data=json.dumps({'text': 'lalala'})
.
– Martijn Pieters♦
Nov 15 '13 at 12:52
1
Ah, now I understand. I had to set it at the sending party (i.e.: in PostMan). Okay, so I set that to json, butrequest.json
is still a NoneType. ANy idea what else I could do wrong?
– kramer65
Nov 15 '13 at 12:57
5
@kramer65: See the source code; Either theContent-Type
header is wrong, or the JSON you sent was'null'
, which translates toNone
. Everything else raises an exception or returns your dictionary. Tryrequest.get_json(force=True)
; this will ignore the header requirement.
– Martijn Pieters♦
Nov 15 '13 at 13:00
1
Okay! "I" fixed it! Usingget_json(force=True)
fixed it, but you were right all along; I set the content type in PostMan to JSON, but I didn't specifically set a header. So I now set the header and it all works fine. Thanks for the awesome help!
– kramer65
Nov 15 '13 at 13:04
|
show 9 more comments
3
Alright. And would you have any idea how to do that?
– kramer65
Nov 15 '13 at 12:49
8
@kramer65: How are you posting the request now? The client has to set the header; if you are usingrequests
, that'd berequest.post(url, headers={'Content-Type': 'application/json'}, data=json.dumps({'text': 'lalala'})
.
– Martijn Pieters♦
Nov 15 '13 at 12:52
1
Ah, now I understand. I had to set it at the sending party (i.e.: in PostMan). Okay, so I set that to json, butrequest.json
is still a NoneType. ANy idea what else I could do wrong?
– kramer65
Nov 15 '13 at 12:57
5
@kramer65: See the source code; Either theContent-Type
header is wrong, or the JSON you sent was'null'
, which translates toNone
. Everything else raises an exception or returns your dictionary. Tryrequest.get_json(force=True)
; this will ignore the header requirement.
– Martijn Pieters♦
Nov 15 '13 at 13:00
1
Okay! "I" fixed it! Usingget_json(force=True)
fixed it, but you were right all along; I set the content type in PostMan to JSON, but I didn't specifically set a header. So I now set the header and it all works fine. Thanks for the awesome help!
– kramer65
Nov 15 '13 at 13:04
3
3
Alright. And would you have any idea how to do that?
– kramer65
Nov 15 '13 at 12:49
Alright. And would you have any idea how to do that?
– kramer65
Nov 15 '13 at 12:49
8
8
@kramer65: How are you posting the request now? The client has to set the header; if you are using
requests
, that'd be request.post(url, headers={'Content-Type': 'application/json'}, data=json.dumps({'text': 'lalala'})
.– Martijn Pieters♦
Nov 15 '13 at 12:52
@kramer65: How are you posting the request now? The client has to set the header; if you are using
requests
, that'd be request.post(url, headers={'Content-Type': 'application/json'}, data=json.dumps({'text': 'lalala'})
.– Martijn Pieters♦
Nov 15 '13 at 12:52
1
1
Ah, now I understand. I had to set it at the sending party (i.e.: in PostMan). Okay, so I set that to json, but
request.json
is still a NoneType. ANy idea what else I could do wrong?– kramer65
Nov 15 '13 at 12:57
Ah, now I understand. I had to set it at the sending party (i.e.: in PostMan). Okay, so I set that to json, but
request.json
is still a NoneType. ANy idea what else I could do wrong?– kramer65
Nov 15 '13 at 12:57
5
5
@kramer65: See the source code; Either the
Content-Type
header is wrong, or the JSON you sent was 'null'
, which translates to None
. Everything else raises an exception or returns your dictionary. Try request.get_json(force=True)
; this will ignore the header requirement.– Martijn Pieters♦
Nov 15 '13 at 13:00
@kramer65: See the source code; Either the
Content-Type
header is wrong, or the JSON you sent was 'null'
, which translates to None
. Everything else raises an exception or returns your dictionary. Try request.get_json(force=True)
; this will ignore the header requirement.– Martijn Pieters♦
Nov 15 '13 at 13:00
1
1
Okay! "I" fixed it! Using
get_json(force=True)
fixed it, but you were right all along; I set the content type in PostMan to JSON, but I didn't specifically set a header. So I now set the header and it all works fine. Thanks for the awesome help!– kramer65
Nov 15 '13 at 13:04
Okay! "I" fixed it! Using
get_json(force=True)
fixed it, but you were right all along; I set the content type in PostMan to JSON, but I didn't specifically set a header. So I now set the header and it all works fine. Thanks for the awesome help!– kramer65
Nov 15 '13 at 13:04
|
show 9 more comments
For reference, here's complete code for how to send json from a Python client:
import requests
res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"})
if res.ok:
print res.json()
The "json=" input will automatically set the content-type, as discussed here: Post JSON using Python Requests
And the above client will work with this server-side code:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content['mytext']
return jsonify({"uuid":uuid})
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug=True)
This actually didn't work for me. With python 2.7 if I specify the <uuid> argument the request gets denied with a 404. This is when sending a valid JSON POST with both Postman and a ReactJS application. If I omit the arg it works just fine.
– Omortis
Feb 23 '17 at 20:28
2
This example definitely works with Python 2.7. Make sure you actually have the "<" and ">" in the app.route. The left/right carets are part of the required Flask syntax.
– Luke
Feb 24 '17 at 2:08
1
Yes, it does work. I was burying my request details in the JSON payload, not in the URI (as in: no arg supplied). Sorry for the static!
– Omortis
Feb 27 '17 at 13:01
add a comment |
For reference, here's complete code for how to send json from a Python client:
import requests
res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"})
if res.ok:
print res.json()
The "json=" input will automatically set the content-type, as discussed here: Post JSON using Python Requests
And the above client will work with this server-side code:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content['mytext']
return jsonify({"uuid":uuid})
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug=True)
This actually didn't work for me. With python 2.7 if I specify the <uuid> argument the request gets denied with a 404. This is when sending a valid JSON POST with both Postman and a ReactJS application. If I omit the arg it works just fine.
– Omortis
Feb 23 '17 at 20:28
2
This example definitely works with Python 2.7. Make sure you actually have the "<" and ">" in the app.route. The left/right carets are part of the required Flask syntax.
– Luke
Feb 24 '17 at 2:08
1
Yes, it does work. I was burying my request details in the JSON payload, not in the URI (as in: no arg supplied). Sorry for the static!
– Omortis
Feb 27 '17 at 13:01
add a comment |
For reference, here's complete code for how to send json from a Python client:
import requests
res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"})
if res.ok:
print res.json()
The "json=" input will automatically set the content-type, as discussed here: Post JSON using Python Requests
And the above client will work with this server-side code:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content['mytext']
return jsonify({"uuid":uuid})
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug=True)
For reference, here's complete code for how to send json from a Python client:
import requests
res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"})
if res.ok:
print res.json()
The "json=" input will automatically set the content-type, as discussed here: Post JSON using Python Requests
And the above client will work with this server-side code:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content['mytext']
return jsonify({"uuid":uuid})
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug=True)
edited May 23 '17 at 12:10
Community♦
11
11
answered Feb 24 '16 at 22:15
LukeLuke
2,2381723
2,2381723
This actually didn't work for me. With python 2.7 if I specify the <uuid> argument the request gets denied with a 404. This is when sending a valid JSON POST with both Postman and a ReactJS application. If I omit the arg it works just fine.
– Omortis
Feb 23 '17 at 20:28
2
This example definitely works with Python 2.7. Make sure you actually have the "<" and ">" in the app.route. The left/right carets are part of the required Flask syntax.
– Luke
Feb 24 '17 at 2:08
1
Yes, it does work. I was burying my request details in the JSON payload, not in the URI (as in: no arg supplied). Sorry for the static!
– Omortis
Feb 27 '17 at 13:01
add a comment |
This actually didn't work for me. With python 2.7 if I specify the <uuid> argument the request gets denied with a 404. This is when sending a valid JSON POST with both Postman and a ReactJS application. If I omit the arg it works just fine.
– Omortis
Feb 23 '17 at 20:28
2
This example definitely works with Python 2.7. Make sure you actually have the "<" and ">" in the app.route. The left/right carets are part of the required Flask syntax.
– Luke
Feb 24 '17 at 2:08
1
Yes, it does work. I was burying my request details in the JSON payload, not in the URI (as in: no arg supplied). Sorry for the static!
– Omortis
Feb 27 '17 at 13:01
This actually didn't work for me. With python 2.7 if I specify the <uuid> argument the request gets denied with a 404. This is when sending a valid JSON POST with both Postman and a ReactJS application. If I omit the arg it works just fine.
– Omortis
Feb 23 '17 at 20:28
This actually didn't work for me. With python 2.7 if I specify the <uuid> argument the request gets denied with a 404. This is when sending a valid JSON POST with both Postman and a ReactJS application. If I omit the arg it works just fine.
– Omortis
Feb 23 '17 at 20:28
2
2
This example definitely works with Python 2.7. Make sure you actually have the "<" and ">" in the app.route. The left/right carets are part of the required Flask syntax.
– Luke
Feb 24 '17 at 2:08
This example definitely works with Python 2.7. Make sure you actually have the "<" and ">" in the app.route. The left/right carets are part of the required Flask syntax.
– Luke
Feb 24 '17 at 2:08
1
1
Yes, it does work. I was burying my request details in the JSON payload, not in the URI (as in: no arg supplied). Sorry for the static!
– Omortis
Feb 27 '17 at 13:01
Yes, it does work. I was burying my request details in the JSON payload, not in the URI (as in: no arg supplied). Sorry for the static!
– Omortis
Feb 27 '17 at 13:01
add a comment |
This is the way I would do it and it should be
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.get_json(silent=True)
# print(content) # Do your processing
return uuid
With silent=True
set, the get_json
function will fail silently when trying to retrieve the json body. By default this is set to False
.
Setting force=True
will ignore the
request.headers.get('Content-Type') == 'application/json'
check that flask does for you. By default this is also set to False
.
See flask documentation.
I would strongly recommend leaving force=False
and make the client send the Content-Type
header to make it more explicit.
Hope this helps!
4
Isn't it better to fail on errors??
– vidstige
Oct 4 '16 at 9:02
1
Depends if the json body is optional or not, so depends on your case
– radtek
Oct 5 '16 at 18:37
1
I cannot see any case where it would make sense to some times post valid json and other times invalid json. Sounds like two different end points
– vidstige
Oct 5 '16 at 18:39
1
Like I said, if an endpoint takes "optional" json body, you can usesilent=True
. Yes this is possible, and I do use it. Its really based on how you design your API to be consumed. If there is no case like that for your endpoint, just removesilent=True
or explicitly set it toFalse
.
– radtek
Oct 5 '16 at 18:57
For clarity, theprint(content)
aftercontent = request.get_json()
prints the object... but as a valid Python object (and not as a valid JSON object). For example, it uses single quotes while JSON strictly requires double quotes for both the key values (strings) as string values. If you want the JSON representation, usejson.dumps()
with the object.
– Jochem Schulenklopper
Nov 12 '18 at 15:59
add a comment |
This is the way I would do it and it should be
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.get_json(silent=True)
# print(content) # Do your processing
return uuid
With silent=True
set, the get_json
function will fail silently when trying to retrieve the json body. By default this is set to False
.
Setting force=True
will ignore the
request.headers.get('Content-Type') == 'application/json'
check that flask does for you. By default this is also set to False
.
See flask documentation.
I would strongly recommend leaving force=False
and make the client send the Content-Type
header to make it more explicit.
Hope this helps!
4
Isn't it better to fail on errors??
– vidstige
Oct 4 '16 at 9:02
1
Depends if the json body is optional or not, so depends on your case
– radtek
Oct 5 '16 at 18:37
1
I cannot see any case where it would make sense to some times post valid json and other times invalid json. Sounds like two different end points
– vidstige
Oct 5 '16 at 18:39
1
Like I said, if an endpoint takes "optional" json body, you can usesilent=True
. Yes this is possible, and I do use it. Its really based on how you design your API to be consumed. If there is no case like that for your endpoint, just removesilent=True
or explicitly set it toFalse
.
– radtek
Oct 5 '16 at 18:57
For clarity, theprint(content)
aftercontent = request.get_json()
prints the object... but as a valid Python object (and not as a valid JSON object). For example, it uses single quotes while JSON strictly requires double quotes for both the key values (strings) as string values. If you want the JSON representation, usejson.dumps()
with the object.
– Jochem Schulenklopper
Nov 12 '18 at 15:59
add a comment |
This is the way I would do it and it should be
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.get_json(silent=True)
# print(content) # Do your processing
return uuid
With silent=True
set, the get_json
function will fail silently when trying to retrieve the json body. By default this is set to False
.
Setting force=True
will ignore the
request.headers.get('Content-Type') == 'application/json'
check that flask does for you. By default this is also set to False
.
See flask documentation.
I would strongly recommend leaving force=False
and make the client send the Content-Type
header to make it more explicit.
Hope this helps!
This is the way I would do it and it should be
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.get_json(silent=True)
# print(content) # Do your processing
return uuid
With silent=True
set, the get_json
function will fail silently when trying to retrieve the json body. By default this is set to False
.
Setting force=True
will ignore the
request.headers.get('Content-Type') == 'application/json'
check that flask does for you. By default this is also set to False
.
See flask documentation.
I would strongly recommend leaving force=False
and make the client send the Content-Type
header to make it more explicit.
Hope this helps!
edited Dec 3 '18 at 6:55
cricket_007
82.6k1143111
82.6k1143111
answered Oct 27 '15 at 22:11
radtekradtek
15.9k68775
15.9k68775
4
Isn't it better to fail on errors??
– vidstige
Oct 4 '16 at 9:02
1
Depends if the json body is optional or not, so depends on your case
– radtek
Oct 5 '16 at 18:37
1
I cannot see any case where it would make sense to some times post valid json and other times invalid json. Sounds like two different end points
– vidstige
Oct 5 '16 at 18:39
1
Like I said, if an endpoint takes "optional" json body, you can usesilent=True
. Yes this is possible, and I do use it. Its really based on how you design your API to be consumed. If there is no case like that for your endpoint, just removesilent=True
or explicitly set it toFalse
.
– radtek
Oct 5 '16 at 18:57
For clarity, theprint(content)
aftercontent = request.get_json()
prints the object... but as a valid Python object (and not as a valid JSON object). For example, it uses single quotes while JSON strictly requires double quotes for both the key values (strings) as string values. If you want the JSON representation, usejson.dumps()
with the object.
– Jochem Schulenklopper
Nov 12 '18 at 15:59
add a comment |
4
Isn't it better to fail on errors??
– vidstige
Oct 4 '16 at 9:02
1
Depends if the json body is optional or not, so depends on your case
– radtek
Oct 5 '16 at 18:37
1
I cannot see any case where it would make sense to some times post valid json and other times invalid json. Sounds like two different end points
– vidstige
Oct 5 '16 at 18:39
1
Like I said, if an endpoint takes "optional" json body, you can usesilent=True
. Yes this is possible, and I do use it. Its really based on how you design your API to be consumed. If there is no case like that for your endpoint, just removesilent=True
or explicitly set it toFalse
.
– radtek
Oct 5 '16 at 18:57
For clarity, theprint(content)
aftercontent = request.get_json()
prints the object... but as a valid Python object (and not as a valid JSON object). For example, it uses single quotes while JSON strictly requires double quotes for both the key values (strings) as string values. If you want the JSON representation, usejson.dumps()
with the object.
– Jochem Schulenklopper
Nov 12 '18 at 15:59
4
4
Isn't it better to fail on errors??
– vidstige
Oct 4 '16 at 9:02
Isn't it better to fail on errors??
– vidstige
Oct 4 '16 at 9:02
1
1
Depends if the json body is optional or not, so depends on your case
– radtek
Oct 5 '16 at 18:37
Depends if the json body is optional or not, so depends on your case
– radtek
Oct 5 '16 at 18:37
1
1
I cannot see any case where it would make sense to some times post valid json and other times invalid json. Sounds like two different end points
– vidstige
Oct 5 '16 at 18:39
I cannot see any case where it would make sense to some times post valid json and other times invalid json. Sounds like two different end points
– vidstige
Oct 5 '16 at 18:39
1
1
Like I said, if an endpoint takes "optional" json body, you can use
silent=True
. Yes this is possible, and I do use it. Its really based on how you design your API to be consumed. If there is no case like that for your endpoint, just remove silent=True
or explicitly set it to False
.– radtek
Oct 5 '16 at 18:57
Like I said, if an endpoint takes "optional" json body, you can use
silent=True
. Yes this is possible, and I do use it. Its really based on how you design your API to be consumed. If there is no case like that for your endpoint, just remove silent=True
or explicitly set it to False
.– radtek
Oct 5 '16 at 18:57
For clarity, the
print(content)
after content = request.get_json()
prints the object... but as a valid Python object (and not as a valid JSON object). For example, it uses single quotes while JSON strictly requires double quotes for both the key values (strings) as string values. If you want the JSON representation, use json.dumps()
with the object.– Jochem Schulenklopper
Nov 12 '18 at 15:59
For clarity, the
print(content)
after content = request.get_json()
prints the object... but as a valid Python object (and not as a valid JSON object). For example, it uses single quotes while JSON strictly requires double quotes for both the key values (strings) as string values. If you want the JSON representation, use json.dumps()
with the object.– Jochem Schulenklopper
Nov 12 '18 at 15:59
add a comment |
This solution works:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['POST'])
def hello():
return jsonify(request.json)
3
To add to this answer the request you could send to this endpoint could beresponse = request.post('http://127.0.0.1:5000/hello', json={"foo": "bar"})
. Following this runningresponse.json()
should return{'foo': 'bar'}
– ScottMcC
Jun 11 '17 at 8:54
It could be noted that{'foo': 'bar'}
isn't valid JSON though. It could be a valid Python object representation that looks a lot like JSON, but valid JSON strictly uses double quotes.
– Jochem Schulenklopper
Nov 12 '18 at 15:42
add a comment |
This solution works:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['POST'])
def hello():
return jsonify(request.json)
3
To add to this answer the request you could send to this endpoint could beresponse = request.post('http://127.0.0.1:5000/hello', json={"foo": "bar"})
. Following this runningresponse.json()
should return{'foo': 'bar'}
– ScottMcC
Jun 11 '17 at 8:54
It could be noted that{'foo': 'bar'}
isn't valid JSON though. It could be a valid Python object representation that looks a lot like JSON, but valid JSON strictly uses double quotes.
– Jochem Schulenklopper
Nov 12 '18 at 15:42
add a comment |
This solution works:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['POST'])
def hello():
return jsonify(request.json)
This solution works:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['POST'])
def hello():
return jsonify(request.json)
answered Feb 28 '17 at 15:40
trojektrojek
781831
781831
3
To add to this answer the request you could send to this endpoint could beresponse = request.post('http://127.0.0.1:5000/hello', json={"foo": "bar"})
. Following this runningresponse.json()
should return{'foo': 'bar'}
– ScottMcC
Jun 11 '17 at 8:54
It could be noted that{'foo': 'bar'}
isn't valid JSON though. It could be a valid Python object representation that looks a lot like JSON, but valid JSON strictly uses double quotes.
– Jochem Schulenklopper
Nov 12 '18 at 15:42
add a comment |
3
To add to this answer the request you could send to this endpoint could beresponse = request.post('http://127.0.0.1:5000/hello', json={"foo": "bar"})
. Following this runningresponse.json()
should return{'foo': 'bar'}
– ScottMcC
Jun 11 '17 at 8:54
It could be noted that{'foo': 'bar'}
isn't valid JSON though. It could be a valid Python object representation that looks a lot like JSON, but valid JSON strictly uses double quotes.
– Jochem Schulenklopper
Nov 12 '18 at 15:42
3
3
To add to this answer the request you could send to this endpoint could be
response = request.post('http://127.0.0.1:5000/hello', json={"foo": "bar"})
. Following this running response.json()
should return {'foo': 'bar'}
– ScottMcC
Jun 11 '17 at 8:54
To add to this answer the request you could send to this endpoint could be
response = request.post('http://127.0.0.1:5000/hello', json={"foo": "bar"})
. Following this running response.json()
should return {'foo': 'bar'}
– ScottMcC
Jun 11 '17 at 8:54
It could be noted that
{'foo': 'bar'}
isn't valid JSON though. It could be a valid Python object representation that looks a lot like JSON, but valid JSON strictly uses double quotes.– Jochem Schulenklopper
Nov 12 '18 at 15:42
It could be noted that
{'foo': 'bar'}
isn't valid JSON though. It could be a valid Python object representation that looks a lot like JSON, but valid JSON strictly uses double quotes.– Jochem Schulenklopper
Nov 12 '18 at 15:42
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20001229%2fhow-to-get-posted-json-in-flask%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown