How to Build a REST API with Flask: A Step-by-Step Guide
Building a REST API with Flask is straightforward thanks to its lightweight design and Python simplicity. This tutorial will walk you through creating a basic API for managing items, covering setup, routes, and data handling. You’ll need Python and pip installed.
Setting Up Flask
First, create a project folder and set up a virtual environment:
mkdir flask-api && cd flask-apipython -m venv venv- Activate it:
venv\Scripts\activate(Windows) orsource venv/bin/activate(Mac/Linux) - Install Flask:
pip install Flask
Now create a file named app.py and import Flask.
Defining Routes and Data
Start with a simple in-memory data store (a list of dictionaries). Define your first route for GET requests:
from flask import Flask, jsonify, request
app = Flask(__name__)
items = [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}]
@app.route('/items', methods=['GET'])
def get_items():
return jsonify(items)
Handling POST, PUT, and DELETE
Add endpoints to create, update, and delete items. Use request.json to parse incoming data:
- POST /items: Add a new item with a generated ID.
- PUT /items/<id>: Update the name of an existing item.
- DELETE /items/<id>: Remove an item by ID.
Here’s a sample POST handler:
@app.route('/items', methods=['POST'])
def create_item():
data = request.json
new_id = max(item["id"] for item in items) + 1
items.append({"id": new_id, "name": data["name"]})
return jsonify(items[-1]), 201
Testing the API
Run your app with python app.py (by default on port 5000). Test using curl or Postman:
curl http://127.0.0.1:5000/itemscurl -X POST -H "Content-Type: application/json" -d '{"name":"New Item"}' http://127.0.0.1:5000/items
You’ll see JSON responses. For production, add error handling, validation, and a database.
Conclusion
This gives you a working REST API with Flask in minutes. Extend it by adding SQLAlchemy for persistence, Flask-RESTful for structured endpoints, or authentication. Flask’s flexibility makes it ideal for both quick prototypes and scalable services.