Building a REST API with Python and Flask

Flask Logo

Flask is a lightweight and flexible Python web framework that is perfect for building REST APIs. This guide shows you how to create a simple API to manage a list of tasks.

Setting Up

pip install Flask

Creating the API

We'll create an API with endpoints to get all tasks and get a single task by its ID.

from flask import Flask, jsonify, request

app = Flask(__name__)

tasks = [
    {'id': 1, 'title': 'Learn Python', 'done': True},
    {'id': 2, 'title': 'Build an API', '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 = next((task for task in tasks if task['id'] == task_id), None)
    if task is None:
        return jsonify({'error': 'Task not found'}), 404
    return jsonify({'task': task})

if __name__ == '__main__':
    app.run(debug=True)

Comments