Ensure Flask and SQLAlchemy are installed:
pip install flask flask-sqlalchemy
Create a file app.py
and set up the Flask application:
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Configure SQLite Database
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///books.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
author = db.Column(db.String(100), nullable=False)
def to_dict(self):
return {"id": self.id, "title": self.title, "author": self.author}
# Create database tables
with app.app_context():
db.create_all()
@app.route("/books", methods=["POST"])
def add_book():
data = request.get_json()
new_book = Book(title=data["title"], author=data["author"])
db.session.add(new_book)
db.session.commit()
return jsonify(new_book.to_dict()), 201
Use Postman or cURL to send a POST request with JSON data:
{
"title": "Flask for Beginners",
"author": "John Doe"
}
Step 5: Get All Books (GET Request)
@app.route("/books", methods=["GET"])
def get_books():
books = Book.query.all()
return jsonify([book.to_dict() for book in books])
Step 6: Get a Single Book by ID
@app.route("/books/<int:book_id>", methods=["GET"])
def get_book(book_id):
book = Book.query.get(book_id)
return jsonify(book.to_dict()) if book else jsonify({"error": "Book not found"}), 404
@app.route("/books/<int:book_id>", methods=["PUT"])
def update_book(book_id):
book = Book.query.get(book_id)
if not book:
return jsonify({"error": "Book not found"}), 404
data = request.get_json()
book.title = data.get("title", book.title)
book.author = data.get("author", book.author)
db.session.commit()
return jsonify(book.to_dict())
Step 8: Delete a Book (DELETE Request)
@app.route("/books/<int:book_id>", methods=["DELETE"])
def delete_book(book_id):
book = Book.query.get(book_id)
if not book:
return jsonify({"error": "Book not found"}), 404
db.session.delete(book)
db.session.commit()
return jsonify({"message": "Book deleted successfully"})
Run the Flask app:
python app.py
In this guide, you learned how to:
✅ Set up a Flask CRUD API with SQLite
✅ Implement POST, GET, PUT, DELETE requests
✅ Use Flask-SQLAlchemy for database management
✅ Handle errors and return JSON responses
You can extend this app by adding user authentication, pagination, and better error handling. 🚀