Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Flask API with AJAX

I am experimenting with Flask and AJAX, I have a simple API route here , hosted at OpenShift. I want to call the API in a Javascript file with Ajax. The OpenShift Python file is simple:

from flask import Flask
app = Flask(__name__)

import json

@app.route('/hello/<name>')
def hello_world(name=None):
    str = {'key':'Hello World!', 'q':name}
    #out = {'key':str}
    res = json.dumps(str)
    return res

if __name__ == '__main__':
    app.run()

And here is the Ajax call:

$.ajax({
    type:"GET",
    dataType: "json",
    data:'Payam',
    url: "http://mypythonapp-spacepirate.rhcloud.com/hello/",
    success: function(data){
        buf1=data;
        console.log(data);
    }
})

But this makes a call to this url which results in 404. How can I solve this? Just to mention CORS is not an issue.

http://mypythonapp-spacepirate.rhcloud.com/hello/?Payam
like image 731
Payam Mesgari Avatar asked Dec 16 '16 19:12

Payam Mesgari


People also ask

Can we use ajax in flask?

We can also use Ajax to handle the user input rather than rendering a template. After carrying out the calculation client-side we will then pass the user input and results to the server to store in a database.

Can I use flask for API?

Flask is a popular micro framework for building web applications. Since it is a micro-framework, it is very easy to use and lacks most of the advanced functionality which is found in a full-fledged framework. Therefore, building a REST API in Flask is very simple.

Can we use ajax in Python?

From IDEA to Product Using Python / Django Ajax essentially is a combination of technologies that are integrated together to reduce the number of page loads. We generally use Ajax to ease end-user experience. Using Ajax in Django can be done by directly using an Ajax library like JQuery or others.

Does flask support jQuery?

This template will load jQuery as above and have a little form where we can add two numbers and a link to trigger the function on the server side. Note that we are using the get() method here which will never fail. If the key is missing a default value (here 0 ) is returned.


1 Answers

Try changing your url property to

url: "http://mypythonapp-spacepirate.rhcloud.com/hello/world",

Then you will get a 200 response status, instead of the 404. The reason is the flask route you created has a required parameter after the hello/.

edit: followup to question about using variable for the data

  • method1: just add encode the parameter to the url

    url: "http://mypythonapp-spacepirate.rhcloud.com/hello/" + encodeURIComponent(xyz)

  • method2: use the data parameter to the ajax call as you have started to do. I think that jquery will translate that into the URL query string for a get, like this. Notice the ? delimiting the start of query string:

    http://mypythonapp-spacepirate.rhcloud.com/hello/?xyz

    You can verify that by checking in your browser dev tools and seeing what URL the ajax call is actually requesting. Also note that in the flask handler you would then need to check for request.query_string to get the data, because <name> parameter would be empty.

like image 100
Alex G Rice Avatar answered Sep 28 '22 03:09

Alex G Rice