Python: Implementing the REST API using Flask

This documentation is part of the Creating a REST API guide. View the full guide here: How to create a REST API using Flask.

👋 Welcome to the Stackhero documentation!

Stackhero offers a ready-to-use Python cloud solution that provides a host of benefits, including:

  • Deploy your application in seconds with a simple git push.
  • Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
  • Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
  • Get optimal performance and robust security thanks to a private and dedicated VM.

Save time and simplify your life: it only takes 5 minutes to try Stackhero's Python cloud hosting solution!

Now, let's dive into the code!

Create a file named app.py and insert the following code:

import os
from dotenv import load_dotenv
from flask import Flask, jsonify, request

# Load environment variables from the .env file when not in production
if os.environ.get('ENV') != 'production':
    load_dotenv()

# Create the Flask app
app = Flask(__name__)

# Sample data set
tasks = [
    {
        'id': 1,
        'title': 'Buy groceries',
        'description': 'Milk, Cheese, Pizza, Fruits',
        'done': False
    },
    {
        'id': 2,
        'title': 'Learn Python',
        'description': 'Learn Python programming basics',
        'done': False
    }
]

# Route '/api/tasks' (GET) to list all tasks
@app.route('/api/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

# Route '/api/tasks/<task_id>' (GET) to get a specific task by its ID
@app.route('/api/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        return jsonify({'error': 'Task not found'}), 404
    return jsonify({'task': task[0]})

# Route '/api/tasks' (POST) to create a new task
@app.route('/api/tasks', methods=['POST'])
def create_task():
    if not request.json or 'title' not in request.json:
        return jsonify({'error': 'Title is required'}), 400
    task = {
        'id': tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
    tasks.append(task)
    return jsonify({'task': task}), 201

# Start the API server
if __name__ == '__main__':
    if os.environ.get('ENV') == 'production':
        app.run()
    else:
        app.run(host='0.0.0.0', port=8080, debug=True)

To start the server, run:

python app.py

With the host='0.0.0.0' option, you can also access your API using your browser when using Code-Hero. Simply navigate to http://<XXXXXX>.stackhero-network.com:8080/api/tasks, replacing <XXXXXX> with your Code-Hero domain.