Posted on 5/1/2025 11:04:54 PM by Admin

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

Are you looking to create a RESTful API using Flask but don’t know where to start? You’re in the right place!

In this step-by-step guide, we’ll walk you through the process of building a simple yet powerful REST API using Python and Flask. Whether you're a beginner or an experienced developer, this tutorial will help you understand the fundamentals of API development with Flask.

By the end, you’ll have a fully functional API that can handle HTTP requests (GET, POST, PUT, DELETE) and interact with a database.

Let’s get started!


What is a RESTful API?

Before diving into coding, let’s quickly understand what a RESTful API is.

  • REST (Representational State Transfer) is an architectural style for designing networked applications.

  • RESTful API uses HTTP requests to perform CRUD (Create, Read, Update, Delete) operations.

  • It follows stateless communication, meaning each request from a client contains all the information needed to process it.

Flask is a lightweight Python web framework that makes it easy to build APIs quickly.


Prerequisites

To follow along, you’ll need:

✅ Python 3.6+ installed
✅ Basic knowledge of Python
✅ A code editor (VS Code, PyCharm, etc.)
✅ Flask and Flask-RESTful (we’ll install them)


Step 1: Setting Up Your Project

First, let’s create a project folder and set up a virtual environment.

1. Create a Project Folder

Open your terminal and run:

bash

mkdir flask_rest_api
cd flask_rest_api

2. Set Up a Virtual Environment

A virtual environment keeps dependencies isolated.

bash

python -m venv venv
  • Activate the virtual environment:

    • Windows:

      bash

      venv\Scripts\activate
    • Mac/Linux:

      bash

      source venv/bin/activate

3. Install Flask

Now, install Flask and Flask-RESTful:

bash

pip install flask flask-restful

Step 2: Creating a Basic Flask API

Let’s start by creating a simple API that returns a "Hello, World!" message.

1. Create app.py

Open your code editor and create a new file app.py.

python

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, World!"

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

2. Run the Flask App

In the terminal, run:

bash

python app.py

Open your browser and go to:

http://127.0.0.1:5000/

You should see:

Hello, World!

🎉 Congratulations! You’ve just created your first Flask API.


Step 3: Building a RESTful API with Flask-RESTful

Now, let’s build a more structured REST API using Flask-RESTful, an extension that simplifies API development.

1. Modify app.py

Update the file to use Flask-RESTful:

python

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'message': 'Hello, World!'}

api.add_resource(HelloWorld, '/')

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

2. Test the API

Run the app again and visit:

http://127.0.0.1:5000/

Now, you’ll see a JSON response:

json

{
    "message": "Hello, World!"
}

This is a RESTful response!


Step 4: Creating a CRUD API for a Task Manager

Let’s build a Task Manager API where we can:

  • GET all tasks

  • POST a new task

  • GET a single task by ID

  • PUT (update) a task

  • DELETE a task

1. Define Task Data (Temporary Storage)

For simplicity, we’ll use a Python list instead of a database.

python

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

2. Create API Endpoints

Update app.py:

python

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

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

class TaskList(Resource):
    def get(self):
        return {"tasks": tasks}

    def post(self):
        new_task = {
            "id": len(tasks) + 1,
            "task": request.json['task'],
            "completed": False
        }
        tasks.append(new_task)
        return {"message": "Task added!", "task": new_task}, 201

class Task(Resource):
    def get(self, task_id):
        task = next((task for task in tasks if task["id"] == task_id), None)
        if task:
            return {"task": task}
        return {"message": "Task not found!"}, 404

    def put(self, task_id):
        task = next((task for task in tasks if task["id"] == task_id), None)
        if task:
            task.update({
                "task": request.json.get('task', task['task']),
                "completed": request.json.get('completed', task['completed'])
            })
            return {"message": "Task updated!", "task": task}
        return {"message": "Task not found!"}, 404

    def delete(self, task_id):
        global tasks
        tasks = [task for task in tasks if task["id"] != task_id]
        return {"message": "Task deleted!"}

api.add_resource(TaskList, '/tasks')
api.add_resource(Task, '/tasks/<int:task_id>')

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

3. Test the API with Postman or cURL

Now, let’s test our API endpoints:

GET All Tasks

bash

curl http://127.0.0.1:5000/tasks

POST a New Task

bash

curl -X POST -H "Content-Type: application/json" -d '{"task": "Deploy API"}' http://127.0.0.1:5000/tasks

GET a Single Task

bash

curl http://127.0.0.1:5000/tasks/1

UPDATE a Task

bash

curl -X PUT -H "Content-Type: application/json" -d '{"task": "Learn Flask-RESTful", "completed": true}' http://127.0.0.1:5000/tasks/1

DELETE a Task

bash

curl -X DELETE http://127.0.0.1:5000/tasks/1

Step 5: Connecting to a Database (SQLite)

For a real-world app, we should use a database instead of a Python list. Let’s integrate SQLite.

1. Install SQLAlchemy

bash

pip install flask-sqlalchemy

2. Update app.py

python

from flask import Flask, request
from flask_restful import Resource, Api
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tasks.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class TaskModel(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    task = db.Column(db.String(200), nullable=False)
    completed = db.Column(db.Boolean, default=False)

    def __repr__(self):
        return f"Task(id={self.id}, task='{self.task}', completed={self.completed})"

# Create the database tables
with app.app_context():
    db.create_all()

class TaskList(Resource):
    def get(self):
        tasks = TaskModel.query.all()
        return {"tasks": [{"id": task.id, "task": task.task, "completed": task.completed} for task in tasks]}

    def post(self):
        data = request.get_json()
        new_task = TaskModel(task=data['task'], completed=False)
        db.session.add(new_task)
        db.session.commit()
        return {"message": "Task added!", "task": {"id": new_task.id, "task": new_task.task, "completed": new_task.completed}}, 201

class Task(Resource):
    def get(self, task_id):
        task = TaskModel.query.get(task_id)
        if task:
            return {"task": {"id": task.id, "task": task.task, "completed": task.completed}}
        return {"message": "Task not found!"}, 404

    def put(self, task_id):
        task = TaskModel.query.get(task_id)
        if task:
            data = request.get_json()
            task.task = data.get('task', task.task)
            task.completed = data.get('completed', task.completed)
            db.session.commit()
            return {"message": "Task updated!", "task": {"id": task.id, "task": task.task, "completed": task.completed}}
        return {"message": "Task not found!"}, 404

    def delete(self, task_id):
        task = TaskModel.query.get(task_id)
        if task:
            db.session.delete(task)
            db.session.commit()
            return {"message": "Task deleted!"}
        return {"message": "Task not found!"}, 404

api.add_resource(TaskList, '/tasks')
api.add_resource(Task, '/tasks/<int:task_id>')

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

Now, your API is database-powered!


Conclusion

You’ve just built a fully functional RESTful API with Flask! 🚀

Here’s what we covered:

✔ Setting up a Flask project
✔ Creating basic API endpoints
✔ Implementing CRUD operations
✔ Connecting to SQLite for persistent storage

Next Steps

  • Add authentication (JWT, OAuth)

  • Deploy your API to Heroku or AWS

  • Use Postman for API testing

Want to dive deeper? Check out our advanced Flask tutorials!

Happy coding! 💻🔥

 


Sharpen Your Skills with These Next Guides