How to Get Python and JavaScript to Communicate Using JSON
Are you wondering how you can send data from JavaScript to Python? Well, that’s easy with an application programming interface (API).
Programming languages communicate and exchange data using APIs. Typically, in such communication, a backend technology (API provider) responds with data after receiving a request from a front-end script. There are many request types, though; in this article, you’ll learn how to use the POST request to send JSON format data from JavaScript to the server using a Python API.
Python and Flask Server Installations
If you’re on Windows and don’t have Python installed already, download it from the python.org website. Mac users need not download Python as the OS comes with it by default. You’ll be able to follow along reasonably well using Linux as well.
Server Setup and Installation
You’ll need a server to create a Python REST API. There are many Python web frameworks for this. Flask, Django, FastAPI, Tornado, and many others come in handy for writing REST APIs in Python.
Nonetheless, you’ll use Flask for this tutorial, as it’s easy to understand and API-friendly.
First, create a Python virtual environment. Open your terminal to your project root folder. Then, install Flask and flask-cors using pip:
pip install Flask, flask-cors
The flask-cors package is Flask’s built-in CORS module for bypassing the cross-origin resource policy while requesting from the API endpoint. You’ll see how to set this up with Flask as you move on.
That’s all for the installation part.
Flask Skeletal Structure
Next, create a new file in your project root folder. Ensure that it has the .py file extension. For example, it can be app.py.
Open that file into your favorite code editor and set up your Flask app as follows:
from flask import Flask, request, jsonify
from flask_cors import CORS
#Set up Flask:
app = Flask(__name__)
#Set up Flask to bypass CORS at the front end:
cors = CORS(app)
#Run the app:
if __name__ == "__main__":
app.run()
The above code imports the required modules and configures your app. The extra code at the tail end (app.run()) sets the app to run on a default port, usually port 5000.
Create a POST API Endpoint
In this tutorial, you’ll send JSON data containing different car brands and their models from JavaScript to the server using a Flask endpoint. In your JavaScript, you’ll assign the data to a variable called cars. You can give it any name you like, though.
But first, open the app.py file, set up a POST API endpoint, and call it receiver. Have it in mind that you can use any naming convention you like.
Here’s how your Python file looks now:
from flask import Flask, request, jsonify
from flask_cors import CORS
#Set up Flask:
app = Flask(__name__)
#Set up Flask to bypass CORS:
cors = CORS(app)
#Create the receiver API POST endpoint:
@app.route("/receiver", methods=["POST"])
def postME():
data = request.get_json()
data = jsonify(data)
return data
if __name__ == "__main__":
app.run(debug=True)
Post Data From JavaScript to Python Flask API
Since the POST API endpoint is ready, create a JavaScript and HTML file in your project root folder (where your flask app is). Give them any name you like (data.js and index.html in this case).
But first, here’s how index.html looks:
<!DOCTYPE html>
<html>
<head>
<title>
Python sending
</title>
</head>
<body>
<button id="theButton">Post to Python</button>
<h3 id = "info"></h3>
<!-- Link to the JavaScript file here: -->
<script src="data.js"></script>
</body>
</html>
Notably, the HTML file above describes a button that listens to a click event to display the posted data, either in the console or the DOM.
The h3 tag serves as a container for the incoming data if you later decide to display it in the DOM. Note that this is not a convention—you can display the incoming data in any HTML container you like.
After setting up the HTML file, use the JavaScripts built-in Fetch API to post the data (cars) to the server.
Here’s the JavaScript:
// Get the button and container elements from HTML:
const button = document.getElementById("theButton")
const data = document.getElementById("info")
// Create an array of cars to send to the server:
const cars = [
{ "make":"Porsche", "model":"911S" },
{ "make":"Mercedes-Benz", "model":"220SE" },
{ "make":"Jaguar","model": "Mark VII" }
];
// Create an event listener on the button element:
button.onclick= function(){
// Get the reciever endpoint from Python using fetch:
fetch("http://127.0.0.1:5000/receiver",
{
method: 'POST',
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
},
// Strigify the payload into JSON:
body:JSON.stringify(cars)}).then(res=>{
if(res.ok){
return res.json()
}else{
alert("something is wrong")
}
}).then(jsonResponse=>{
// Log the response data in the console
console.log(jsonResponse)
}
).catch((err) => console.error(err));
}
The above script contains a JSON array of rally cars. The button.click function is a click event listener attached to the button in the HTML file you created earlier.
Hence, when a user clicks the button, fetch uses the POST request to send the array of cars to the server. The receiver endpoint in Flask receives this request and sends response data to JavaScript (front end), which displays in the browser console.
Now, launch the HTML file in your browser and open the developer console (on Windows: Ctrl + Shift + I, on Mac: CMD + ALT + I). Go to the Console section, and you’ll see the returned JSON response.
To track the JSON response in real-time, click Network in the developer console (on Chrome). Below the network timeline, select receiver or the name of your Flask endpoint. Then click Response at the top of that submenu.
The response should look something like this:
Also, you can click Headers to view the response status of the request. This should be 200, which means your API has returned a valid response.
Next, you can now write the data to the DOM with additional logic in your JavaScript:
// Get the button and container from HTML:
const button = document.getElementById("theButton")
const data = document.getElementById("info")
// Create an event listener on the button element:
button.onclick= function(){
// Get the receiver endpoint from Python using fetch:
fetch("http://127.0.0.1:5000/receiver",
{
method: 'POST',
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
},
// Strigify the payload into JSON:
body:JSON.stringify(cars)}).then(res=>{
if(res.ok){
return res.json()
}else{
alert("something is wrong")
}
}).then(jsonResponse=>{
// Iterate through the data with Map and write your rendering logic:
jsonResponse.map(Main=>
Main.make==="Porsche"? data.innerHTML +="<p>"+ Main.make+" "+" is a good product":
data.innerHTML +="<p>"+ Main.make+" "+"is an average product" )
}
).catch((err) => console.error(err)); }
Using the map function, the above script loops through the response data. The Main.make attribute gets the name of each car from the response data returned from the server. The ternary logic within the map function then instructs JavaScript on what to display with each make.
Hence, when you click the post button, here’s what you get:
There you go! You now know how to set up a Flask endpoint and post data to the server asynchronously using JavaScript.
Keep Exploring REST APIs in Web Development
APIs offer the best way to separate your backend from the front. One of its advantages is it lets you decouple the client-side from the server-side easily. You’ve seen how to connect JavaScript to Python and send data to the server, but that’s only a scratch of the surface.
You can dig deeper by connecting the Flask REST API to a database like MongoDB—so this lets you have a repository to store the posted data. You might even turn this into a full-blown project by sending the data to the database using a form field.