
In modern web development, REST APIs (Representational State Transfer Application Programming Interfaces) play a crucial role in connecting front-end applications with back-end servers. Flask, a lightweight Python web framework, makes it easy to build and deploy APIs efficiently. In this guide, we’ll walk through the steps to create a simple REST API using Flask.
1. What Is a REST API?
A REST API allows different applications to communicate over HTTP by following REST principles, such as:
- Statelessness – Each request from a client contains all the information needed, without relying on past requests.
- Resource-Based Architecture – Data is represented as resources, typically accessed via URLs.
- Standard HTTP Methods:
- GET – Retrieve data
- POST – Create new data
- PUT/PATCH – Update existing data
- DELETE – Remove data
2. Setting Up Your Flask API
Step 1: Install Flask
If you haven’t installed Flask yet, you can do so using pip:
pip install Flask
Step 2: Create the Flask App
Create a new Python file (e.g., app.py) and set up a basic Flask application:
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return {"message": "Welcome to the Flask API"} if __name__ == '__main__': app.run(debug=True)
Run the script using:
python app.py
Your API will be accessible at http://127.0.0.1:5000/.
3. Adding CRUD Operations
Let’s create an API that manages a list of books.
Step 3: Define a Data Store
We’ll use a simple list to store book data:
books = [ {"id": 1, "title": "1984", "author": "George Orwell"}, {"id": 2, "title": "To Kill a Mockingbird", "author": "Harper Lee"} ]
Step 4: Create API Endpoints
Get All Books (GET Request)
from flask import jsonify @app.route('/books', methods=['GET']) def get_books(): return jsonify(books)
Get a Single Book by ID (GET Request)
@app.route('/books/<int:book_id>', methods=['GET']) def get_book(book_id): book = next((b for b in books if b["id"] == book_id), None) return jsonify(book) if book else ({"error": "Book not found"}, 404)
Add a New Book (POST Request)
from flask import request @app.route('/books', methods=['POST']) def add_book(): new_book = request.json books.append(new_book) return jsonify(new_book), 201
Update a Book (PUT Request)
@app.route('/books/<int:book_id>', methods=['PUT']) def update_book(book_id): book = next((b for b in books if b["id"] == book_id), None) if not book: return {"error": "Book not found"}, 404 data = request.json book.update(data) return jsonify(book)
Delete a Book (DELETE Request)
@app.route('/books/<int:book_id>', methods=['DELETE']) def delete_book(book_id): global books books = [b for b in books if b["id"] != book_id] return {"message": "Book deleted"}, 200
4. Testing Your API
You can test your API using Postman or cURL:
- Get all books:
curl http://127.0.0.1:5000/books
- Get a single book:
curl http://127.0.0.1:5000/books/1
- Add a new book:
curl -X POST http://127.0.0.1:5000/books -H "Content-Type: application/json" -d '{"id": 3, "title": "Dune", "author": "Frank Herbert"}'
- Update a book:
curl -X PUT http://127.0.0.1:5000/books/1 -H "Content-Type: application/json" -d '{"title": "Nineteen Eighty-Four"}'
- Delete a book:
curl -X DELETE http://127.0.0.1:5000/books/1
5. Conclusion
Building a REST API with Flask is straightforward and scalable. By implementing CRUD operations, we’ve created a fully functional API that can manage data efficiently. You can extend this project by integrating a database (SQLite, PostgreSQL) or adding authentication for secure access.
Would you like me to add authentication or database integration to this example? Let me know how you’d like to expand it!