Python: Implementing the REST API with Flask

This documentation is part of the Creating a REST API guide. You can view the complete guide here: Step-by-step guide to building a REST API with Flask in Python.

👋 Welcome to the Stackhero documentation!

Stackhero offers a ready-to-use Python cloud solution designed to simplify your deployments:

  • Deploy your application to production in just seconds with a simple git push.
  • Use your own domain name, with automatic HTTPS certificate setup for secure connections managed for you.
  • Take advantage of automatic backups, one-click updates, and predictable pricing, so you can focus on your code instead of infrastructure management.
  • Benefit from high performance and security on a private, dedicated infrastructure. Your environment is isolated and protected.

Save time and streamline your workflow: your code can be up and running with Stackhero's Python cloud hosting in just 5 minutes.

Now you're ready to write your API code.

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

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

# Load environment variables from .env for non-production environments
if os.environ.get('ENV') != 'production':
    load_dotenv()

app = Flask(__name__)

# Example tasks data
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
    }
]

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

@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 not task:
        return jsonify({'error': 'Task not found'}), 404
    return jsonify({'task': task[0]})

@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

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

You can start the server with:

python app.py

With host='0.0.0.0', your API is accessible from your browser when using Code-Hero. Go to http://<XXXXXX>.stackhero-network.com:8080/api/tasks, replacing <XXXXXX> with your Code-Hero domain.