Building a REST API with Flask: A Comprehensive Example
Flask, a popular Python microframework, is an excellent choice for creating simple and secure REST APIs. It's lightweight, flexible, and easy to get started with. In this guide, we'll walk you through a comprehensive example of building a basic REST API with Flask, including CRUD (Create, Read, Update, Delete) operations.
Setting Up the Project and Environment
First, ensure you have Python and pip installed. Then, install Flask and Flask-SQLAlchemy, a popular Object-Relational Mapping (ORM) library, using pip:
pip install flask flask_sqlalchemy
Create a new folder for your project and navigate to it. Inside this folder, create the following files and folders:

- app.py
- config.py
- models.py
- requirements.txt
config.py
This file will store our configuration settings:
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'your-secret-key'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
models.py
Here, we'll define our data model. For this example, let's use a simple 'Task' model:
from app import db
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
description = db.Column(db.Text, nullable=True)
done = db.Column(db.Boolean, default=False)
def __repr__(self):
return f''
Creating the Flask Application
In app.py, we'll create our Flask application and configure it:

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from config import Config
from models import Task
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
Creating the API Endpoints
Now, let's create the CRUD API endpoints:
Get All Tasks
To get all tasks, we'll use the GET method and route it to /tasks:
@app.route('/tasks', methods=['GET'])
def get_tasks():
tasks = Task.query.all()
return jsonify([task.__dict__ for task in tasks])
Create a New Task
To create a new task, we'll use the POST method and route it to /tasks. We'll expect a JSON payload with 'title' and 'description' fields:

@app.route('/tasks', methods=['POST'])
def create_task():
data = request.get_json()
new_task = Task(title=data['title'], description=data.get('description', ''))
db.session.add(new_task)
db.session.commit()
return jsonify(new_task.__dict__), 201
Get, Update, and Delete a Task
For getting, updating, and deleting tasks, we'll use the GET, PUT, and DELETE methods respectively, routing them to /tasks/{id}:
| Method | Route | Description |
|---|---|---|
| GET | /tasks/{id} | Returns the task with the given ID. |
| PUT | /tasks/{id} | Updates the task with the given ID using a JSON payload. |
| DELETE | /tasks/{id} | Deletes the task with the given ID. |
Here's an example of the GET method implementation:
@app.route('/tasks/', methods=['GET'])
def get_task(id):
task = Task.query.get_or_404(id)
return jsonify(task.__dict__)
Implement the PUT and DELETE methods similarly, using the appropriate database operations.
Running the Application
Finally, add the following code to the end of app.py to run the application:
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
Now, run your application using python app.py. Your REST API should now be up and running at http://127.0.0.1:5000/.





















