Flask is a lightweight WSGI web application framework in Python. It is designed with simplicity in mind and allows you to create web applications with ease. One of the common tasks when building web applications is implementing CRUD operations—Create, Read, Update, and Delete. In this blog, we will delve into how to implement CRUD operations using Flask to build a REST API. We will use a real-world example to demonstrate these concepts, making it easier for you to follow along.
Table of Contents
- Introduction to CRUD Operations
- Setting Up Your Environment
- Creating a Flask Application
- Setting Up a SQLite Database
- Defining the Model
- Implementing CRUD Operations
- Create Operation
- Read Operation
- Update Operation
- Delete Operation
- Testing the API with Postman
- Conclusion
1. Introduction to CRUD Operations
CRUD stands for Create, Read, Update, and Delete—the four basic operations for interacting with a database. These operations are essential for managing data in any application. Let’s break down each operation:
- Create: Adding new data to the database.
- Read: Retrieving data from the database.
- Update: Modifying existing data in the database.
- Delete: Removing data from the database.
In this blog, we will build a simple REST API using Flask that performs these operations on a sample dataset.
2. Setting Up Your Environment
Before we start coding, we need to set up our development environment. We will be using Windows OS for this tutorial.
Prerequisites
- Python 3.x installed on your system. You can download it from the official Python website.
- A code editor such as Visual Studio Code or PyCharm.
- Postman for testing the API. You can download it from the official Postman website.
Installing Flask and Other Dependencies
Open your terminal (Command Prompt or PowerShell) and run the following commands to create a virtual environment and install Flask:
# Create a virtual environment
python -m venv venv
# Activate the virtual environment
# For Command Prompt
venv\Scripts\activate
# For PowerShell
venv\Scripts\Activate.ps1
# Install Flask
pip install Flask
# Install SQLAlchemy for database interactions
pip install Flask-SQLAlchemy
# Install Flask-Migrate for database migrations
pip install Flask-Migrate
3. Creating a Flask Application
With Flask installed, let’s create the basic structure of our Flask application.
Step 1: Create a Project Directory
Create a new directory for your project and navigate into it:
mkdir flask_crud
cd flask_crud
Step 2: Create the Application Structure
Inside the project directory, create the following structure:
flask_crud/
│
├── app/
│ ├── __init__.py
│ ├── models.py
│ ├── routes.py
│ ├── config.py
│
├── migrations/
│
├── venv/
│
├── run.py
Step 3: Initialize the Flask Application
In app/__init__.py
, initialize the Flask application and set up the database:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
db = SQLAlchemy()
migrate = Migrate()
def create_app():
app = Flask(__name__)
# Load configuration from config.py
app.config.from_object('app.config.Config')
# Initialize extensions
db.init_app(app)
migrate.init_app(app, db)
# Register blueprints
from .routes import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
Step 4: Configuration
Create a configuration file app/config.py
:
import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'a_secret_key'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///site.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
Step 5: Run the Application
In run.py
, create an entry point to run the application:
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
4. Setting Up a SQLite Database
We will use SQLite as our database for simplicity. SQLite is a lightweight database that is easy to set up and does not require a separate server.
5. Defining the Model
In app/models.py
, define a model for our database. For this tutorial, we’ll create a simple model to store information about books.
from . import db
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)
description = db.Column(db.Text, nullable=True)
6. Implementing CRUD Operations
Now, let’s implement the CRUD operations in app/routes.py
.
Step 1: Create a Blueprint
First, create a blueprint to organize our routes:
from flask import Blueprint
main = Blueprint('main', __name__)
Step 2: Create Operation
To create a new book entry, we need a POST endpoint. Add the following code to app/routes.py
:
from flask import request, jsonify
from . import db
from .models import Book
from . import main
@main.route('/books', methods=['POST'])
def create_book():
data = request.get_json()
new_book = Book(
title=data['title'],
author=data['author'],
description=data.get('description')
)
db.session.add(new_book)
db.session.commit()
return jsonify({'message': 'Book created successfully'}), 201
Step 3: Read Operation
To read the book entries, we need a GET endpoint. Add the following code to app/routes.py
:
@main.route('/books', methods=['GET'])
def get_books():
books = Book.query.all()
output = []
for book in books:
book_data = {
'id': book.id,
'title': book.title,
'author': book.author,
'description': book.description
}
output.append(book_data)
return jsonify({'books': output})
To get a single book by ID, add:
@main.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = Book.query.get_or_404(book_id)
book_data = {
'id': book.id,
'title': book.title,
'author': book.author,
'description': book.description
}
return jsonify(book_data)
Step 4: Update Operation
To update an existing book entry, we need a PUT endpoint. Add the following code to app/routes.py
:
@main.route('/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
data = request.get_json()
book = Book.query.get_or_404(book_id)
book.title = data['title']
book.author = data['author']
book.description = data.get('description')
db.session.commit()
return jsonify({'message': 'Book updated successfully'})
Step 5: Delete Operation
To delete a book entry, we need a DELETE endpoint. Add the following code to app/routes.py
:
@main.route('/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
book = Book.query.get_or_404(book_id)
db.session.delete(book)
db.session.commit()
return jsonify({'message': 'Book deleted successfully'})
7. Testing the API with Postman
Now that our CRUD operations are implemented, we need to test our API to ensure it works as expected. We will use Postman for this purpose.
Step 1: Start the Flask Application
First, start your Flask application by running the following command in your terminal:
python run.py
Step 2: Create a New Book
Open Postman and create a new POST request to http://127.0.0.1:5000/books
. In the body of the request, select raw
and JSON
, and enter the following JSON data:
{
"title": "Flask for Beginners",
"author": "John Doe",
"description": "A comprehensive guide to Flask."
}
Click the Send
button. You should receive a response indicating that the book was created successfully.
Step 3: Read All Books
Create a new GET request to http://127.0.0.1:5000/books
and click Send
. You should see a list of all books in the response.
Step 4: Read a Single Book
Create a new GET request to http://127.0.0.1:5000/books/1
(replace 1
with the ID of an existing book) and click Send
. You should see the details of the specified book.
Step 5: Update a Book
Create a new PUT request to http://127.0.0.1:5000/books/1
(replace `1
with the ID of an existing book). In the body of the request, select
rawand
JSON`, and enter the following JSON data:
{
"title": "Flask for Beginners - Updated",
"author": "Jane Doe",
"description": "An updated comprehensive guide to Flask."
}
Click the Send
button. You should receive a response indicating that the book was updated successfully.
Step 6: Delete a Book
Create a new DELETE request to http://127.0.0.1:5000/books/1
(replace 1
with the ID of an existing book) and click Send
. You should receive a response indicating that the book was deleted successfully.
8. Conclusion
In this blog, we covered the basics of implementing CRUD operations using Flask to build a REST API. We started by setting up our development environment, creating a Flask application, and defining a model for our database. We then implemented the CRUD operations and tested our API using Postman.
This tutorial provides a solid foundation for building more complex applications with Flask. You can extend this project by adding user authentication, more complex data models, and additional functionality. The skills you’ve learned here will serve you well in your journey as a software developer.
Happy coding!