Ensure you have Flask installed or install it using pip:
pip install flask
Create a file app.py
and set up the basic Flask application:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/", methods=["GET"])
def home():
return jsonify({"message": "Welcome to the Flask REST API!"})
if __name__ == "__main__":
app.run(debug=True)
python app.py
.http://127.0.0.1:5000/
to see the JSON response.For this guide, we will use a simple list to store books instead of a database:
books = [
{"id": 1, "title": "Flask for Beginners", "author": "John Doe"},
{"id": 2, "title": "Advanced Flask", "author": "Jane Smith"}
]
@app.route("/books", methods=["GET"])
def get_books():
return jsonify(books)
Visit http://127.0.0.1:5000/books
in the browser to see the list of books.
@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 jsonify({"error": "Book not found"}), 404
Visit http://127.0.0.1:5000/books/1
to fetch a specific book.
from flask import request
@app.route("/books", methods=["POST"])
def add_book():
new_book = request.get_json()
books.append(new_book)
return jsonify(new_book), 201
{
"id": 3,
"title": "Flask REST API Guide",
"author": "Mike Lee"
}
Step 7: Update an Existing 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 jsonify({"error": "Book not found"}), 404
data = request.get_json()
book.update(data)
return jsonify(book)
@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 jsonify({"message": "Book deleted successfully"})
Visit http://127.0.0.1:5000/books/1
and send a DELETE request.
Visit http://127.0.0.1:5000/books/1 and send a DELETE request.
Run the Flask app using:
python app.py
Use Postman or cURL to send requests and verify the API responses.
In this guide, you learned how to:
✅ Set up a Flask REST API
✅ Create GET, POST, PUT, and DELETE routes
✅ Use Flask’s request and jsonify modules
✅ Handle CRUD operations with a simple in-memory dataset
This is a basic setup for Flask REST APIs, and you can extend it by integrating databases, authentication, and middleware. 🚀