Flask receiving Post Json
<p>I'm working on a flask web application in which the client posts data to the server in the form of:</p>

<p>{
"sess_id" : 1 ,
"annotations" :
[ {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}, {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}, {"tag_start" : "TIME","tag_end" : "TIME","tag" : "YOUR_TAG"}]
}</p>

<p>Here is the full Ajax post...</p>

<pre><code>        $.ajax({
            url: 'http://127.0.0.1:5000/api/saveannotation',
            type: 'POST',
            headers: {'Content-Type' : 'application/json'},
            data: {'sess_id' : $('#sessionid_area').val(),
                'annotations': JSON.parse(annotations)},
            success: function(data) { alert(data.status); }
        });
</code></pre>

<p>so I can even see this on the api side, which is defined as such:</p>

<pre><code>@sessionapis.route('/saveannotation', methods=['GET', 'POST'])
@login_required
def save_annotation():
    rData = request.data
    if request.method == 'GET':
        return jsonify({'status' : 'success GET'})
    else:
        return jsonify({'status' : 'success'})
</code></pre>

<p>The issue is that data is a "byte" type, not a dict.  I also can't call request.json or request.get_json(silent=True), it returns "400 bad request".</p>

<p>Here is a sample of what is in request.data:</p>

<pre><code>b'sess_id=1&amp;annotations%5B0%5D%5Btag_start%5D=2...
</code></pre>

<p>it appears to be url encoded for some reason.  Values is also empty.  If I choose to do something wild, like leave out the content-type = json; I can get a dict-like thing, but I have to access it very oddly.  I don't get individual objects, but rather just flat access to all properties.</p>

<p>Any thoughts on how to just get the json parsed into a reasonable object?</p>

<p>Thanks for any hints!</p>

<p>Just passing a content-type header of JSON doesn't actually make the data itself into JSON. You either need to do that yourself, or tell jQuery to do so.</p>

<pre><code>$.ajax({
    url: 'http://127.0.0.1:5000/api/saveannotation',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({'sess_id' : $('#sessionid_area').val(),
        'annotations': JSON.parse(annotations)}),
    success: function(data) { alert(data.status); }
});
</code></pre>

<p>Now your data will be in JSON format and you can get it as a Python dict with <code>request.get_json()</code>.</p>

python json flask