Reputation: 3591
I have a Flask API with this endpoint :
@app.route('/classify/', methods=['POST'])
def classify():
data = request.get_json()
When I POST a request with python, eveything is fine.
But when I use Postman, I get :
<class 'werkzeug.exceptions.BadRequest'> : 400: Bad Request
I send the same Json with both (I copy/paste it to be sure). I am fairly confident the issue is caused by some "\t" in my json, which are escaped by python but not by Postman.
Is there a way to retrieve the raw json, and process it (escape what needs to be escaped) in the app ? Or another way to get the json ?
EDIT : This is a different question from the one you suggested as duplicate, because yours suggest to use get_json, which is the problem in my case.
Upvotes: 13
Views: 12503
Reputation: 56
If you are getting 400 Bad Request
or failed to decode json object: expecting value: line 1 column 1 (char 0)
, it might be because you are not sending it in json.
First verify that you are getting the request using return request.data
. Check in postman that the Content-disposition
is in json. Alternatively, use print(request.is_json)
.
When using request.get_json
with Postman, make sure that you are sending the JSON as the raw
request.
See this image, make sure to select raw and JSON from the dropdown in the body
Upvotes: 1
Reputation: 1
All error about ajax and flask send data from templates for python file.
Recive all data of ajax json.
data = request.get_json("")
print(data)
return "success!"
Send data in ajax json.
$(document).on('click','#texthide',function(){
var text = $("#textVal").val();
var font = $("#font_text").val();
var color = $("#color_text").val();
var start_text = $("#start_text").val();
var end_text = $("#end_text").val();
var vid_id = new_d
console.log(text);
$.ajax({
url: '/videos/test_text',
type: 'POST',
contentType: 'application/json; charset=utf-8',
datatype: "json",
data: JSON.stringify(
{ text: $("#textVal").val(),
font: $("#font_text").val(),
color: $("#color_text").val(),
start_text: $("#start_text").val(),
end_text: $("#end_text").val(),
video_id: new_d
})
});
});
Upvotes: -1
Reputation: 1147
use request.data
instead of request.get_json()
if your data could be empty or a bad request will be raised!
Upvotes: 3
Reputation: 3591
Ok, so it turns out you can replace :
data = request.get_json(
)
By :
data = json.loads(request.data, strict=False) # strict = False allow for escaped char
requests.data contains the json in string format, so you can process the characters that needs to be escaped.
Upvotes: 13