In this tutorial, we will walk through the process of building a simple REST API using Flask, a lightweight and flexible web framework for Python. We will cover setting up the Flask environment, creating endpoints, handling HTTP requests, and returning JSON responses.
Introduction to REST APIs
A REST API (Representational State Transfer Application Programming Interface) is a set of rules that allow applications to communicate with each other over the web. REST APIs are commonly used to build web services and are known for their simplicity and scalability. They rely on stateless communication, typically using HTTP methods like GET, POST, PUT, DELETE, etc.
Setting Up the Flask Environment
Step 1: Install Flask
Make sure Python is installed on your machine. Then, install Flask using pip:
pip install Flask
Step 2: Create a Project Directory
mkdir flask_rest_api
cd flask_rest_api
Step 3: Create a Virtual Environment
python -m venv venv
Activate the virtual environment:
venv\Scripts\activate
source venv/bin/activate
Building the REST API
Step 1: Create the Flask Application
Create a file named app.py
and add:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to the Flask REST API!"
if __name__ == '__main__':
app.run(debug=True)
Run the application:
python app.py
Visit http://127.0.0.1:5000/
in your browser to see the welcome message.
Step 2: Create an API Endpoint
from flask import Flask, jsonify
app = Flask(__name__)
items = [
{"id": 1, "name": "Item 1", "price": 100},
{"id": 2, "name": "Item 2", "price": 150},
{"id": 3, "name": "Item 3", "price": 200}
]
@app.route('/api/items', methods=['GET'])
def get_items():
return jsonify(items)
if __name__ == '__main__':
app.run(debug=True)
Step 3: Handle HTTP Methods (GET, POST, PUT, DELETE)
from flask import Flask, jsonify, request, abort
app = Flask(__name__)
items = [
{"id": 1, "name": "Item 1", "price": 100},
{"id": 2, "name": "Item 2", "price": 150},
{"id": 3, "name": "Item 3", "price": 200}
]
@app.route('/api/items', methods=['GET'])
def get_items():
return jsonify(items)
@app.route('/api/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
item = next((item for item in items if item["id"] == item_id), None)
if item is None:
abort(404)
return jsonify(item)
@app.route('/api/items', methods=['POST'])
def create_item():
if not request.json or 'name' not in request.json or 'price' not in request.json:
abort(400)
new_item = {
"id": items[-1]['id'] + 1 if items else 1,
"name": request.json['name'],
"price": request.json['price']
}
items.append(new_item)
return jsonify(new_item), 201
@app.route('/api/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
item = next((item for item in items if item["id"] == item_id), None)
if item is None:
abort(404)
if not request.json:
abort(400)
item['name'] = request.json.get('name', item['name'])
item['price'] = request.json.get('price', item['price'])
return jsonify(item)
@app.route('/api/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
item = next((item for item in items if item["id"] == item_id), None)
if item is None:
abort(404)
items.remove(item)
return jsonify({"result": True})
if __name__ == '__main__':
app.run(debug=True)
Explanation
Method | Endpoint | Description |
---|
GET | /api/items | Retrieves all items. |
GET | /api/items/<item_id> | Retrieves a specific item by ID. |
POST | /api/items | Adds a new item (requires name and price ). |
PUT | /api/items/<item_id> | Updates an existing item by ID. |
DELETE | /api/items/<item_id> | Deletes an item by ID. |
Testing the API
You can use Postman or curl
to test the API.
curl http://127.0.0.1:5000/api/items
curl http://127.0.0.1:5000/api/items/1
curl -X POST -H "Content-Type: application/json" -d '{"name": "Item 4", "price": 250}' http://127.0.0.1:5000/api/items
curl -X PUT -H "Content-Type: application/json" -d '{"name": "Updated Item 2"}' http://127.0.0.1:5000/api/items/2
curl -X DELETE http://127.0.0.1:5000/api/items/3
Conclusion
In this tutorial, we built a simple REST API using Flask that can handle basic CRUD operations. This fundamental skill is crucial for web developers and serves as a solid foundation for building more complex APIs. You can extend this by adding authentication, database integration, and deploying your Flask application to production.