user3515612
user3515612

Reputation: 159

Ajax call to Flask Rest API does not get JSON

I have the following ajax call to my REST API with Flask:

$.ajax({
    type: "POST",
    cache: false,
    url: "/addEvent",
    dataType: "json",
    data: JSON.stringify({
        "event_id": "e-123"
        }),
    success: function(response, status, xhr) {
        var ct = xhr.getResponseHeader("content-type") || "";        
        if ( xhr.status == 200 ) {
            console.log("Event created.");
        }
        else {
            alert("Error! status: " + xhr.status)
        }
    },
    error: function(xhr, exception) {
        console.log("error > xhr.status:" + xhr.status);
        console.log("error > exception: " + exception);
    },
    complete: function(response, status, xhr) {
        console.log("Finished!");
    }
});

My Flask REST API app.py file contains this:

from flask import Flask, request
def addEvent():
    request_data = request.get_json() 

However, 'request_data' is None while request.get_data() contains b'{"event_id":"e-123"}'

Did I make something wrong in my ajax call?

Upvotes: 0

Views: 744

Answers (2)

rafaelncarvalho
rafaelncarvalho

Reputation: 729

Add contentType: 'application/json' on your AJAX request:

$.ajax({
    type: "POST",
    cache: false,
    url: "/addEvent",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: ...

Upvotes: 1

Israel Ferreira
Israel Ferreira

Reputation: 108

You are sending a string to your Flask REST API.

Try changing your data field in ajax call from:

data: JSON.stringify({
    "event_id": "e-123"
    })

to

data: {
    "event_id": "e-123"
    }

Upvotes: 2

Related Questions