How to Use API Data in Flask Application (Display API Content in Jinja Template)

If you want to display content from 3rd part API services or from headless CMS like Strapi, this tutorial definitely going to help you.

flask access 3rd party api content

json.loads – It takes a string as input and returns a dictionary as output.

json.dumps – It takes a dictionary as input and returns a string as output. It turns python data like dict, list and returns this JSON as a string.

.json() – If the API URL returned JSON as a result, then use this

Example:-

import requests
response = requests.get('https://reqres.in/api/users')
output_dict = response.json()
print(output_dict)

Reference:

json — JSON encoder and decoder (From Official Python Documentation)

SEE ALSO: Web API for Beginners

Common Error When Accessing JSON data in Flask(Python) App

Error 1: JSON object must be str, bytes or bytearray, not dict

When you try to call json.loads with dict as input, this kind of error will appear.

Solution

First, add the input in json.dumps and store the value in a new variable,

Now load the new variable as json.loads input

Example:-

json_content = {"('Hello',)": 6, "('Hi',)": 5}
v1 = json.dumps(json_content)
v2= json.loads(v1)

Source: https://stackoverflow.com/a/42354033

Error 2: dump() missing 1 required positional argument: ‘fp’

Solution:-

Use json.dumps() instead. json.dump()

Source: https://stackoverflow.com/a/46396854

Leave a Reply

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