How to Build a JSON API with Flask in Minutes

1. Setup a virtual environment

Create a new directory for your project and then create a virtual environment within it and install Flask.

# Create the virtual environment
python -m venv env

# Activate the virtual environment
source env/bin/activate

# Install Flask
pip install Flask

2. Create a basic Flask app

Create a file named app.py with the following content:

# Import Flask and its built-in JSON support
from flask import Flask, jsonify

# Initialize the Flask application
app = Flask(__name__)


# Define a route to get a list of users
@app.route("/api/users", methods=["GET"])
def get_users():
    # Sample user data
    users = [
        {"id": 1, "name": "Amanda", "email": "amanda@email.com"},
        {"id": 2, "name": "Brian", "email": "brian@email.com"},
        {"id": 3, "name": "Caitlin", "email": "caitlin@email.com"},
        {"id": 4, "name": "Daniel", "email": "daniel@email.com"},
        {"id": 5, "name": "Erica", "email": "erica@email.com"},
    ]
    # Return the user data as JSON
    return jsonify(users)


# Run the application
if __name__ == "__main__":
    app.run(debug=True)

3. Run the application

In the terminal with the activated virtual environment, tell Python to run the application:

python app.py

4. View the final result

View the running application in your web browser: http://localhost:5000/api/users

You should see some nice JSON output like this:

[
  {
    "email": "amanda@email.com",
    "id": 1,
    "name": "Amanda"
  },
  {
    "email": "brian@email.com",
    "id": 2,
    "name": "Brian"
  },
  {
    "email": "caitlin@email.com",
    "id": 3,
    "name": "Caitlin"
  },
  {
    "email": "daniel@email.com",
    "id": 4,
    "name": "Daniel"
  },
  {
    "email": "erica@email.com",
    "id": 5,
    "name": "Erica"
  }
]

How to verify the data is being returned as JSON

You can use your web browser's network inspector to look at the API endpoint's header information. Check out the response's Content-Type header:

Expanding on this basic app

Returning sample data is obviously not very useful. The next step could be to connect to a database to fetch and return more useful information, or perhaps to add new API endpoints so users can save information to the database first, which can then be returned as JSON data.

This short post is just to demonstrate how quickly and easily you can spin up a JSON API using Flask. Python and Flask have been such useful and productive tools in my work so I wanted to share this for anyone just getting started.

Have fun!
Luke

Ready to discuss your project?

Send me a message and I'll get back to you within one business day.

Let's Talk