How to obtain Flask request JSON data as dictionary?

35,631

The data is being put into request.json because of the mimetype of the request. I believe you are looking for get_json.

@app.route('/projects/<name>', methods=['GET', 'POST'])
def projects(name=None):
    req_json = request.get_json()
    print(req_json['ajax'])
    if name:
        project = db.getProject(name)
        form = ProjectForm(project)

        if req_json['ajax']:
            return render_template("myform.html", form=form)
        return render_template("projectView.html", form=form)
    return render_template("projects.html")

I do not have access to my dev machine at the moment so I haven't tested this, but it should work from my understanding of the docs.

Share:
35,631
Sebastian
Author by

Sebastian

I'm an experienced developer with a wide variety of interests and a career working in diverse environments and businesses. I enjoy learning and solving problems and I'm always up for the challenge.

Updated on October 03, 2020

Comments

  • Sebastian
    Sebastian over 3 years

    Im struggling with JQuery ajax methods and Flask, trying to make an ajax call to retrieve some form.

    My js code looks like this:

    $.ajax({
           type: 'POST',
           url: '/projects/dummyName',
           data: JSON.stringify("{'ajax': 'True'}"),
           contentType: 'application/json;charset=UTF-8',
           dataType: 'html',
           success: function(responseData, textStatus, jqXHR) {
               $("#myform").text(responseData);
             },
           error: function (responseData, textStatus, errorThrown) {
               alert('Error: '+errorThrown + ". Status: "+textStatus);
           }
    }); 
    

    Basically im adding the data parameter to let the server method that this is an ajax call. But i just cant get that data in the server as a dict. Tried millon ways, im cant make it work.

    This is the dummy server method:

    @app.route('/projects/<name>', methods=['GET', 'POST'])
    def projects(name=None):
        print(request.json)
        print(request.json['ajax'])
        if name:
            project = db.getProject(name)
            form = ProjectForm(project)
    
            if request.json['ajax'] == True:
                return render_template("myform.html", form=form)
            else:
                return render_template("projectView.html", form=form)
        else:
            return render_template("projects.html")
    

    So, request.json returns a string:

    {'ajax': 'True'}

    Of course the app breaks when try to access json['ajax'] and I get a BAD RESPONSE error msg. I thought that would give me a python dict, because otherwise what would be the difference between request.json and request.data if both are strings.

    How can i get a python dict with all the data passed in the ajax call? Does it depend on the way I define the contentType? does it depend on the use of JSON.stringify or not?

    Help will be much appreciated! Thanks