JavaScript Fetch with Flask for Dynamic API Responses

Use JavaScript's fetch method to send user input to a Flask route and display the JSON response.

Discover how JavaScript's fetch method can communicate seamlessly with a Python Flask server to create dynamic two-way interactions. Learn to set up routes, handle JSON responses, and prepare your application for integration with the OpenAI API.

Key Insights

  • Utilize JavaScript's fetch method to send requests to a custom Flask server route, replacing third-party API requests, and enable real-time communication by parsing JSON responses into usable JavaScript objects.
  • Set up a Flask route that returns a JSON response using Flask's jsonify method, allowing JavaScript to display server-generated messages dynamically on the webpage.
  • Establish foundational skills in Flask and JavaScript fetch interaction, preparing to integrate user-generated inputs with Flask and eventually forward conversations to the OpenAI API for more advanced AI-driven interactions.

Note: These materials offer prospective students a preview of how our classes are structured. Students enrolled in this course will receive access to the full set of materials, including video lectures, project-based assignments, and instructor feedback.

This is a lesson preview only. For the full lesson, purchase the course here.

Hi, welcome back to Python for AI apps with the OpenAI API and a bunch of JavaScript it turns out as well. My name is Brian McLean, thanks for coming back for the next lesson.

So in the previous lesson we learned about JavaScript's fetch then then sequence to set an API request and get back and handle and parse a JSON response into an object. Then we could output that object's content to the web page. Because we're only focusing on fetch then then in JavaScript and not concerning ourselves with any Flask route, much less the OpenAI API, we didn't even worry about our chat website. We just did a request to the cat API and got back a cat fact which we parsed and put out there on the website.

So, what we want to do now that we have a handle on how to use fetch, is we're going to fetch our own route. We're going to send a fetch request to hit our own route in our Flask server called chat, or whatever we want to call it, and just return JSON to the request with an answer from Flask. It'll be a static answer—we're not engaging with the OpenAI API yet.

Then we'll be able to output not just our own messages that we typed in that green leaf chat assistant but also the incoming server-side messages that Flask will be feeding back to our JavaScript. It's gonna be really neat. It'll be the same static message from the server every time, but we'll have that two-way conversation starting.

Once we get that done, the next move is going to be: if we can get our message over to Flask and we know we can communicate between Flask and the OpenAI API, let's send the user message to the API and ask it to answer, right? Then keep track of the whole conversation because every time you send a prompt message to the OpenAI API, it needs the context. If you want to keep track of your conversation, you have to keep sending it back the whole conversation every time.

Python for Data Science Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Alright, let's get going here. This is our cat fact code from lesson seven. Let's move on to eight. We're going to use the JSFetch method to hit or request a Flask server route that'll be of our own making. We're not using a third-party API. The Flask server will return JSON, and we'll give it a message property. The cat fact had a fact property—we'll return a message property.

The first then that's chained onto fetch will parse the JSON into a usable JS object, and then the second then will output the message to the web page, which is what we did with the cat fact. We parsed the incoming cat fact with the first then and outputted the cat fact to the web page with the second then.

Step one: use fetch to send a request to Python Flask server. Now that we have an understanding of how to fetch data from an API and handle the response, the next step is to send a fetch request to a Flask server and get back a confirmation message, which will display where the cat fact used to go. We're going to do a save-as off that cat fact page. This is a key stepping stone en route to the real goal—getting Flask to forward our user chat messages to the OpenAI API and return the AI's answer each time back to JavaScript for our chat assistant windows.

We're going to do a save-as of 07, which is the cat fact API page (which I just closed), and we're going to call it 08. In 08, we're going to update the script tag to import the new JS file. We could also change the title to "08 Flask JSFetch Flask route". We're obviously not going to use the cat stuff, but we'll decatify all that as we go.

In index 08, we're going to change h1 and h2 to "Sending fetch request to Flask route". We capitalized that, right? The button is going to say "Fetch message from Flask", and the message from Flask goes here.

In script 08 JS, we're going to tell the button to call a function called fetchFlaskMessage. You already have your h2 and button, we're just changing it slightly, but the button should be above the h2 in the code—it doesn’t really matter, but let's keep that order.

Define a function to send a fetch request for the Flask server. Make the following changes to our existing function—we already have one which performs the fetch request. This is a copy of the one from the cat API. No more feline factoids, we're hitting up our own Flask route now. Change the name of the function from fetchCatFact to fetchFlaskMessage. We're going to fetch our Flask message route.

In the fetch method, change the URL to a Flask route, which we're going to call '/fetch-flask-message/'. Ensure it matches everywhere consistently. We're sending our request by GET. We are parsing the returned result with json(). Now we're going to output to the h2 the message property of our response object. We haven't written the server yet, but it'll return a message property, just like the cat fact API returned a fact property.

Now we're going to create the Flask Python script that has that Flask message route. Do a save-as from a basic server (server01) because we're not interacting with the OpenAI API yet. Name this server08. We've got a route to render 08—our index route will render the home page, index08, into the browser.

Then we're going to make another route called flask-message. The function could be named sendMessage. We're not rendering a template but returning JSON made by passing a dictionary with one property, "msg", to jsonify. Make sure you import jsonify in server08 so our route function can return JSON, which fetch is expecting. Return jsonify({"message": "Hello JS from Flask"}). Run your server to test.

When you hit the home route, the web page should appear, complete with "Fetch message from Flask". Clicking the button should send the fetch request to the flask-message route, which returns the JSON message. JavaScript parses this and displays it in the h2 on the page—a nifty little bit of hustle bustle.

That's it for this lesson. Up next is nine, where we learn how to do a round-trip message. Even though we hit the Flask-msg route here, notice we didn't send any data. In the next lesson, we'll handle sending the user's chat input to Flask and handling responses.

Brian McClain

Brian is an experienced instructor, curriculum developer, and professional web developer, who in recent years has served as Director for a coding bootcamp in New York. Brian joined Noble Desktop in 2022 and is a lead instructor for HTML & CSS, JavaScript, and Python for Data Science. He also developed Noble's cutting-edge Python for AI course. Prior to that, he taught Python Data Science and Machine Learning as an Adjunct Professor of Computer Science at Westchester County College.

More articles by Brian McClain

How to Learn Python

Master Python with hands-on training. Python is a popular object-oriented programming language used for data science, machine learning, and web development. 

Yelp Facebook LinkedIn YouTube Twitter Instagram