How to return a JSON response form a Flask API

In this lesson we want to learn How to return a JSON response form a Flask API, Flask is web framework for Python. Flask micro web framework that provides basic tools for building web application including routing, request handling and template engine. It is designed to be simple and lightweight and it makes it easy to get started and allowing developers to focus on writing their application logic instead of worrying about the underlying infrastructure. Flask is popular choice for building small to medium sized web applications and is often used as  starting point for larger, more complex projects.



How to return a JSON response form a Flask API ?

In Flask you can return JSON response from a API endpoint by using jsonify function from the flask package. make sure that you have installed flask using pip command: pip install flask

Here’s an example of how to return a JSON response:


In this example the api_data function returns JSON response that contains dictionary with two keys: name and age. jsonify function converts the dictionary to JSON string and sets the appropriate Content-Type header to application/json.

When you make GET request to the /api/data endpoint, API will return JSON response that looks like this:



Learn More on Python

Leave a Comment