Creating REST APIs with Flask: Complete Guide

Flask is one of Python’s most popular microframeworks — lightweight, flexible, and perfect for creating RESTful APIs fast.
If you’ve ever wanted to connect your frontend, mobile app, or machine learning model to a backend, Flask gives you the perfect starting point.

In this guide, we’ll walk through everything from setup to building and testing your first API endpoint.


⚙️ 1️⃣ Setting Up Your Flask Environment

Before you begin, make sure Flask is installed. Open your terminal and run:

pip install flask

Then, create a new Python file — say, app.py.

Here’s the simplest possible Flask app:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to your Flask API!"

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

Run it using:

python app.py

Your API is now live at http://127.0.0.1:5000/ 🎉


🧠 2️⃣ Understanding REST API Basics

REST (Representational State Transfer) is an architectural style for designing networked applications.
A REST API communicates using HTTP methods such as:

  • GET → Retrieve data
  • POST → Add new data
  • PUT → Update data
  • DELETE → Remove data

Flask handles these methods seamlessly using decorators.


🛠️ 3️⃣ Building Your First Endpoint

Let’s create a simple API that manages a list of tasks.

from flask import Flask, jsonify, request

app = Flask(__name__)

tasks = [
    {"id": 1, "title": "Learn Flask", "done": False},
    {"id": 2, "title": "Build an API", "done": False}
]

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

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

You can now GET and POST data to /tasks. Try it using Postman, curl, or your frontend app.


🔁 4️⃣ Adding Update and Delete Endpoints

APIs should allow modification too.
Here’s how to handle updating and deleting a task:

@app.route('/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    for task in tasks:
        if task["id"] == task_id:
            task["title"] = request.json.get("title", task["title"])
            task["done"] = request.json.get("done", task["done"])
            return jsonify(task)
    return jsonify({"error": "Task not found"}), 404


@app.route('/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
    global tasks
    tasks = [task for task in tasks if task["id"] != task_id]
    return jsonify({"result": "Task deleted"})

Now you have a fully functional CRUD API.


🔒 5️⃣ Adding Basic Error Handling

Good APIs return meaningful responses.
For instance, if a task doesn’t exist, return a clear error message.

@app.errorhandler(404)
def not_found(error):
    return jsonify({"error": "Not Found"}), 404

Structured JSON responses make your API more consistent and easier to debug.


🌍 6️⃣ Running Your API in Production

While app.run(debug=True) is fine for development, for production use Gunicorn or uWSGI with Nginx:

pip install gunicorn
gunicorn app:app

Deploying your Flask API to platforms like Render, Railway, or Vercel is quick and free for basic usage.


🚀 7️⃣ Bonus: Connect Flask with a Database

If you want your API to persist data, integrate SQLite or SQLAlchemy:

from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tasks.db'
db = SQLAlchemy(app)

With just a few lines, you can turn your mock data into a real backend.


🧭 Final Thoughts

Flask’s power lies in its simplicity. In less than 50 lines of code, you’ve built a working REST API — something that can easily evolve into a microservice, backend for your app, or AI-powered automation system.

Once you’re comfortable, consider adding authentication, JWT tokens, and request validation to make your API production-grade.

Scroll to Top
WhatsApp Chat on WhatsApp