Skip to content

KaiCodes

Contact

How to display JSON data to a front-end app using Flask

Python, JavaScript, Full Stack1 min read

https://stackoverflow.com/questions/57965942/how-to-display-json-data-to-front-end-interface-using-flask

There are two ways to get data from the server to a front-end application. You can embed data from the server into the front-end app, or you can send data to the front-end app either on request or in realtime.

In this tutorial, I will show you how to use server-side rendering to embed JSON data into an app. I will also show you how to create an API endpoint and use a front-end app to request the JSON data.

Setup Project

Create Project Boilerplate

Pro tip: Open the file in Visual Studio Code and run html:5 to automatically generate the file boilerplate. You can press the tab key to navigate through each field and set the value

index.html

Add this JSON data to pets.json in the data folder.

pets.json

.flaskenv

Create Virtual Environment

Create venv docs

Server-side Render

You can send the index.html file down with the data embedded in the file.

With render_template, you are accessing Jinja, a python templating engine. Jinja allows you to get data from the python app to an HTML file in the templates folder.

To pass in the data to the index.html file, you pass in the pets JSON data as a named parameter to render_template. From there you can pipe the data variable to the tojson function and it will convert it to a text string that is properly formatted as a JavaScript object.

Now all that's left is to start the server and look and the Browser Developer tools to make sure the data got logged! Do start the server run:

Client-side Fetch

Final app.py