How to return a JSON response from a Flask API?

How to return a JSON response from a Flask API?

Flask makes it quite easy to return JSON responses from your API endpoints. Here's a step-by-step guide on how to do it:

1. Install Flask

First, you need to install Flask:

pip install Flask 

2. Create Your Flask API

Once Flask is installed, you can set up a basic Flask app. Here's a simple example:

from flask import Flask, jsonify app = Flask(__name__) @app.route('/') def hello_world(): return jsonify(message="Hello, World!") @app.route('/data') def return_data(): data = { 'name': 'John', 'age': 30, 'city': 'New York' } return jsonify(data) if __name__ == '__main__': app.run(debug=True) 

In this example:

  • We've imported jsonify from Flask, which allows you to convert Python dictionaries or multiple keyword arguments into a JSON response.

  • The hello_world function returns a simple JSON message.

  • The return_data function returns a more complex JSON object.

3. Run Your Flask App

Execute your Flask script:

python your_flask_script.py 

With the Flask server running, visiting http://127.0.0.1:5000/ in your browser will give you:

{ "message": "Hello, World!" } 

And visiting http://127.0.0.1:5000/data will give you:

{ "age": 30, "city": "New York", "name": "John" } 

That's it! With Flask's jsonify function, you can easily return JSON responses from your API endpoints.


More Tags

java type-conversion c#-5.0 es6-modules android-glide regex-group query-optimization sklearn-pandas maven-release-plugin segue

More Programming Guides

Other Guides

More Programming Examples