How to Get Python and JavaScript to Communicate Using JSON

Joe Coburn 24-01-2017

Ever wondered how to send data between two programming languages? Ever tried to send an object or multiple pieces of data?


Today I’ll be showing you how to use JSON to send data from JavaScript to Python. I’ll be covering how to setup a web server, along with all the code you need.


You will need a few things to get started with this project. I’ll be running on Mac, which has Python installed already. You should be able to follow along reasonably well using Linux. If you are using Windows, you will need to download and install Python, and maybe brush up on your command line skills A Beginner's Guide To The Windows Command Line The command line lets you communicate directly with your computer and instruct it to perform various tasks. Read More .

You will need pip, a package manager for Python. This is installed by default with Python versions greater than 2.7.9.

Server Setup

You need a server to serve Python to a web page. There are many options for this. If you have a server setup already, you can skip this step.

There are many options you could use here. Tornado is a good choice, as is Twisted (I have written about Twisted before for a DIY network camera). I’ll be using Flask for this project.


Install Flask using pip (via the command line):

pip install Flask

That’s it! There are a few options to setup, but providing it installed correctly, you are good to go.

You may wish to consider using a Python Virtual Environment Learn How to Use the Python Virtual Environment Whether you are an experienced Python developer, or you are just getting started, learning how to setup a virtual environment is essential for any Python project. Read More , however this is entirely optional.

Python Setup

Create a new file in your favorite text editor or Integrated Development Environment (IDE). I’m using Sublime Text 3 and PyCharm, but use whatever you are comfortable with.


Now perform some initial setup of Flask:

from flask import Flask
app = Flask(__name__)

This imports the required modules and configures your app. Now set up a path:

def output():
	return "Hello World!"

This configures a path, which is like a page of a website. This may sometimes be called an endpoint or a route.

The def output() line defines a function or method called output, which will run whenever this endpoint is called. These methods do not have to use the same name as the endpoint — call it any suitable name. Inside this method is a simple Hello, World! string. Finally, setup your script to actually run when it is requested:

if __name__ == "__main__":

Go ahead and save this script as in a suitable location. Go back to your Terminal and navigate to your project folder. Run the script:


The word python is used to tell the computer that the following file should be run as a Python script. The filename afterwards is the name of the file you wish to run as Python. If everything works correctly, you should see a status message in the Terminal:

* Running on (Press CTRL+C to quit)

This shows you the IP address your server is running on, as well as the port. These will be and 5000. You can press CTRL > C to stop this running, but don’t do that just yet.

Enter the address into your browser, and you should see Hello, World! appear on the screen. You have now successfully setup a Python server and written your first script! You will need to restart the server (stop the script, then run it again) if you make any changes.


If you wish to view your scripts on a different computer on the same network, change to:"", "5010")

There are two parts to this line. The first tells Flask to serve files on your local IP address (make sure you keep this as, even though that is not your IP address). The second part specifies the port. You can change the port if you wish to. Run the script again (remember to save and restart).

You should now be able to access your scripts from a different computer on the same network. Make sure to use your IP address (run ifconfig in the command line) and the port you entered previously. You may need to configure your firewall if you are using one.

The console will show you the HTTP response, and IP address of any device that connects to your server:

Python Server Access Details

Notice how the endpoint /df returned a 404 error? The endpoint is not setup! If you wish to access this over the internet, look into port forwarding What Is Port Forwarding? Everything You Need to Know What is port forwarding? How can you set it up? Is port forwarding good for gaming? How does it help? Here's what you need to know. Read More .


Now that your server is all setup, it’s time to write some templates. You will use JSON to send data between Python and Javascript, and templates facilitate this. We have written about what JSON is What Is JSON? A Layman's Overview Whether you plan to be a web developer or not, it's a good idea to at least know what is JSON, why it's important, and why it's used all around the web. Read More in the past, so go read up if you are not sure.

You will need to use a templating language. Jinja2 comes with Flask, so there is no extra setup needed.

A templating language works in conjunction with a web server. It takes the output of your Python scripts (the back-end code), and makes it easy to output to the user using HTML (the front-end). It’s important to note that templates should not be used for logic! Keep the logic in Python, and use templates only for displaying the data. It gets very messy if you start trying to get complex with the template.

Create a folder inside your project directory called templates. Flask recognizes files inside this folder as template files. Don’t place any Python scripts in here, this is where you can put your HTML files.

Create a file called index.html. Inside it, place the following code:

{{ name }}

This is the way to access a piece of data called name, which will be found inside your scripts. Go back to your script, and modify the output function. Instead of returning hello world, enter this code:

return render_template("index.html", name="Joe")

This will load the index.html file you created earlier, and substitute the {{ name }} template tag for the string Joe. You can use this method to load any page inside your template folder, and pass them any amount of data.

The Code

Now that you know how templates work, here’s the full HTML code you need. Paste this inside your index.html file:

<script src=""></script>
<script type="text/javascript">
// setup some JSON to use
var cars = [
	{ "make":"Porsche", "model":"911S" },
	{ "make":"Mercedes-Benz", "model":"220SE" },
	{ "make":"Jaguar","model": "Mark VII" }

window.onload = function() {
	// setup the button click
	document.getElementById("theButton").onclick = function() {

function doWork() {
	// ajax the JSON to the server
	$.post("receiver", cars, function(){

	// stop link reloading the page
This will send data using AJAX to Python:<br /><br />
<a id="theButton">Click Me</a>

Notice how this does not include CSS, or any HTML headers. These are required for webpages (this example will work without them), so look into these at W3Schools if you care to.

Python JSON HTML Button

There is not too much going on in this file. A JSON list of rally cars is setup. There is a bit of text and a button. When the button is pressed, jQuery is used to POST the list of cars to the server. This will go to the receiver endpoint, which you will create next. Make sure you read our guide to jQuery if you want to learn more about how that is working in this context.

Here’s the code you need for


import sys

from flask import Flask, render_template, request, redirect, Response
import random, json

app = Flask(__name__)

def output():
	# serve index template
	return render_template('index.html', name='Joe')

@app.route('/receiver', methods = ['POST'])
def worker():
	# read json + reply
	data = request.get_json()
	result = ''

	for item in data:
		# loop over every row
		result += str(item['make']) + '\n'

	return result

if __name__ == '__main__':
	# run!

This code defines two endpoints. The default one (/) serves the previous html page. When the button is pressed, a POST request is made to the /receiver endpoint. The second part of the route definition (methods = [‘POST’]) defines how this page can be accessed. As POST is the only way specified, this route will deny any other http requests (such as GET).

This /receiver endpoint simply loops over every JSON row, and appends the car make to a string, which then gets returned after the loop. The JSON is stored in the data variable, and as the request.get_json() was used, Python is aware that this is a JSON object. The item variable inside the for loop can be thought of like a row of data. Different elements of each row can be accessed by using their name in square brackets (item[‘make’]).

Open your browser developer tools (CMD > ALT > I on Mac OS/Chrome), and navigate to the network tab. Press the button, and you should see the server response appear:

Python JSON Response

Try modifying the initial JSON and see what happens. Let’s modify the Python to do something different, depending on the JSON. Here’s the new code you need for the for loop:

	for item in data:
		# loop over every row
		make = str(item['make'])
		if(make == 'Porsche'):
			result += make + ' -- That is a good manufacturer\n'
			result += make + ' -- That is only an average manufacturer\n'

This uses a simple if statement to change the output, depending on the input. You could easily adapt this to write to a database, or run a different piece of code. Here’s what it looks like now:

Python JSON Conditional

You should now have a solid understanding of how to setup a Python server, and how you can respond to JSON requests.

Do you enjoy coding in JavaScript? Try scripting a voice-sensitive robot animation How to Script a Voice-Sensitive Robot Animation in p5.js Want to get your children interested in programming? Show them this guide to building a sound reactive animated robot head. Read More ! You might also want to upgrade your skills as a developer by mastering JavaScript arrow functions JavaScript Arrow Functions Can Make You a Better Developer Want to be better at web development? Arrow functions, added to JavaScript ES6, give you two ways to create functions for web apps. Read More and array methods 5 JavaScript Array Methods You Should Master Today Want to understand JavaScript arrays but can't get to grips with them? Check our JavaScript array examples for guidance. Read More and exploring other functional programming languages 5 Functional Programming Languages You Should Know Want to know more about programming? It's worth learning about functional programming and what programming languages support it. Read More .

Related topics: JavaScript, Python, Web Development.

Affiliate Disclosure: By buying the products we recommend, you help keep the site alive. Read more.

Whatsapp Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. George Fawn
    February 7, 2020 at 11:19 pm

    When the tutorial says "Enter the address into your browser" it should specify that the address is "" not just "".

  2. Vasanth
    April 17, 2019 at 5:24 pm

    Very helpful.Thanks for sharing

  3. Jannis
    June 5, 2018 at 10:12 am

    For god sake, why are they not updating the tutorial?? The comment section unfortunately is also not very obvious. 1h of my life wasted.

    The frustration about the two bugs aside, it was the most on point tutorial i have seen.So i guess other tutorials (without bugs) would take similar time. so thanks anyway, but for the sake of time of all people following this tutorial, please update the scripts!!

    • Yair
      July 28, 2017 at 8:38 am

      it was suppose to be written elements a and button...

    • Yair
      July 28, 2017 at 8:42 am

      I don't know why my first comment wasn't published so I will write it again:
      In this guide you missed two things:
      1) on the server side, in the get_json() function, you need to set the parameter "force" to true (i.e request.get_json(force=True)).
      see the following issue:

      2) on the client side you didn't use JSON.stringify to send your message, which might also cause problems.

      except that issues that was a great guide, I learned a lot!

      • Yao
        December 22, 2017 at 7:01 am

        thanks, these two problems troubled me a lot!

    • Yair
      July 28, 2017 at 8:43 am

      I don't know why my first comment wasn't published so I will write it again:
      In this guide you missed two things:
      1) on the server side, in the get_json() function, you need to set the parameter "force" to true (i.e request.get_json(force=True)).

      2) on the client side you didn't use JSON.stringify to send your message, which might also cause problems.

      except that issues that was a great guide, I learned a lot!

  4. Yair
    July 27, 2017 at 4:21 pm

    You have tow points missing in this guide:
    1) On the client side, you should use the JSON.stringify(string s) function in order for this to work.
    2) on the server side, in the function request.get_json, you need to set the force parameter to True like this: request.get_json(force=True), or set the mimetype (I don't know how) to application/json.
    please see the following issue:

    those two issues gave me a lot of troubles... except that, great guide!

    • Zak
      February 23, 2018 at 8:47 pm

      Thank you for posting this. I was wondering what I did wrong. So, so far:

      In python:
      - data = request.get_json(force=True)

      In javascript:
      $.post("receiver", JSON.stringify(cars), function()...

      • Anthony
        March 4, 2018 at 12:57 am

        Worked for me - thanks both for your comments

      • manuel
        May 23, 2019 at 10:25 am

        hello, I still receiving a 400 bad request error after.

      • George Fawn
        February 8, 2020 at 12:35 am

        Thanks for the help!

    • shohan
      April 3, 2018 at 11:30 am

      Thanks man!!! Why are they not correcting the tutorial?!!! >_<

    • Pavel
      April 21, 2018 at 4:32 pm

      THANKS!!! I was googling for half hour and then I looked here, thank you!