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:
1 2 3 4 5 6 7 8 9 10 11 |
from flask import Flask, jsonify app = Flask(__name__) @app.route("/api/data") def api_data(): data = {"name": "John Doe", "age": 30} return jsonify(data) if __name__ == '__main__': app.run() |
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:
1 2 3 4 |
{ "name": "John Doe", "age": 30 } |
Learn More on Python
- How to Add Matplotlib in TKinter Window
- How to Create Bar Plot with Pandas
- How to send Message to Instagram with Python
- TKinter Application with Dialogs
- Build Multi Window Application with TKinter
- How to Build Charts in TKinter
- How to Install TKinter in Windows and Linux
- How to Use ChatGPT in Python
- Which Websites are Made with Django