7

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.

CoMartel
  • 3,301
  • 3
  • 22
  • 42
  • 1
    check out this answer: https://stackoverflow.com/questions/27369306/flask-jsonify-how-to-escape-characters – smundlay Sep 07 '17 at 09:52
  • 1
    could you elaborate ? My issue is that get_json() is the only way to retrieve the json data, and it raises an error – CoMartel Sep 07 '17 at 10:04

3 Answers3

9

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.

CoMartel
  • 3,301
  • 3
  • 22
  • 42
2

use request.data instead of request.get_json() if your data could be empty or a bad request will be raised!

d0zingcat
  • 679
  • 7
  • 10
-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
                })
            });
        });
sbgib
  • 5,285
  • 3
  • 16
  • 24