How to Build a REST API with Flask: A Step-by-Step Tutorial

Flask is a lightweight Python framework perfect for quickly building REST APIs. With minimal setup, you can handle HTTP methods, parse JSON data, and return structured responses. This tutorial walks you through creating a simple API for managing tasks.

Article illustration

1. Setting Up the Environment

Install Flask via pip:

  • pip install flask
  • Create a new file, app.py, and import Flask:
from flask import Flask, jsonify, request

2. Defining Routes and HTTP Methods

Create an in-memory list of tasks for demonstration.

app = Flask(__name__)
tasks = []

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

@app.route('/tasks', methods=['POST'])
def add_task():
    data = request.get_json()
    tasks.append(data)
    return jsonify(data), 201

Use @app.route with the endpoint and allowed methods. jsonify converts Python dicts to JSON responses.

3. Handling Dynamic Routes and Data

Use URL parameters for individual resources.

@app.route('/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
    task = next((t for t in tasks if t['id'] == task_id), None)
    if task:
        return jsonify(task)
    return jsonify({'error': 'Not found'}), 404

@app.route('/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    data = request.get_json()
    for t in tasks:
        if t['id'] == task_id:
            t.update(data)
            return jsonify(t)
    return jsonify({'error': 'Not found'}), 404

4. Running the API

Add the boilerplate to run the server:

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

Test endpoints with curl or Postman.

Conclusion: You now have a working REST API with Flask. Extend it with Flask-RESTful for more structure or add databases like SQLite. Flask’s simplicity lets you focus on logic rather than boilerplate.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *