Skip to content
Sarvesh's AI Newsletter

Building a RESTful Library Management API Using Flask and JWT

Creating a Library Management Library system using RESTful API

Sarvesh Talele

· 39 min read

Share:

Image Created by AI

Image Created by AI

Developing a library management system from scratch can sound daunting, but breaking it down into a RESTful API with Flask makes it fun and manageable. In this blog post, we’ll build a Library Management API step-by-step with a casually techie vibe — explaining concepts like REST, HTTP methods, Flask, SQLAlchemy, JWT (JSON Web Tokens), and password hashing with bcrypt (via Passlib). We’ll also walk through the actual code (from the GitHub repo) 📁, explaining each part in plain English, with examples of how to use the API. By the end, you’ll know how all the pieces fit together to create a secure (🔐) and scalable library management backend.

Table of Contents

  • Introduction & Key Concepts
  • Project Overview: Library Management API Features
  • Project Setup and Entry Point (run.py)
  • Dependencies (requirements.txt)
  • Configuration (config.py)
  • Data Models (models.py)
  • Application Factory (__init__.py)
  • Authentication Routes (auth.py)
  • User Routes (users.py)
  • Book Routes (books.py)
  • Transaction Routes (transactions.py)
  • Testing the API (VS Code REST Client and test.http)
  • Conclusion: Scaling, Deploying, and Extending

Let’s dive in! 🎉

Introduction & Key Concepts 📖

Before we jump into the code, let’s clarify some key concepts and tools we’ll be using in this blog

RESTful APIs: A RESTful API (Representational State Transfer) is a way to structure a web service using standard HTTP methods to interact with resources. Think of resources as nouns (like “books” or “users” in a library) and HTTP methods as verbs that act on them. The main HTTP methods we’ll use are:

  • GET — Retrieve data (e.g., get a list of books or details of one book)
  • POST — Create new data (e.g., add a new book or register a new user)
  • PUT — Update existing data (e.g., edit a book’s info)
  • DELETE — Remove data (e.g., delete a book record)

The API will be RESTful — meaning it will use these methods at meaningful URLs (endpoints) to manage library data. For example, GET /books to list books, POST /books to add one, etc.

  1. Flask Framework: Flask is a lightweight Python web framework that makes it easy to build web APIs. It’s minimal but extensible, meaning you can plug in extensions for database integration, authentication, etc. We’ll use Flask’s Blueprints feature to organize our code modularly (different parts of the API in different files). Flask is known for being simple to get started with — “Hello World” in Flask is just a few lines. Perfect for a project like this!
  2. SQLAlchemy ORM: We need to store data (users, books, transactions), and for simplicity, we’ll use a SQLite database by default. SQLAlchemy is an Object-Relational Mapper (ORM) that lets us interact with the database using Python classes instead of writing raw SQL. We’ll define Python classes for User, Book, and Transaction, and SQLAlchemy will handle creating tables and CRUD operations behind the scenes. This improves productivity and keeps our code Pythonic 🐍.
  3. JWT Authentication: Our API will secure specific endpoints (like adding books or viewing all users) so only authorized users can access them. We’ll use JSON Web Tokens (JWT) for authentication. A JWT is a signed token that the server issues to a client upon login; the client then sends this token with each request (usually in a Authorization: Bearer <token> header). Flask has an extension, Flask-JWT-Extended, that makes working with JWTs easier. With it, we can protect routes by simply adding a decorator and generating tokens with one function call. JWTs allow stateless auth – no need to keep sessions on the server, the token itself proves the user’s identity.
  4. Password Hashing with bcrypt (Passlib): We never store passwords in plain text — that’s a big no-no ❌. Instead, we’ll hash passwords using the bcrypt algorithm via the Passlib library. Bcrypt is a battle-tested hashing algorithm designed for passwords: it’s slow (intentionally, to thwart brute-force attacks) and salted (to protect against rainbow table attacks). Passlib’s bcrypt utility makes it easy to hash a password (one line of code) and verify a password against a hash (another one-liner). For example, bcrypt.hash("mysecret") returns a secure hash, and bcrypt.verify("mysecret", stored_hash) Checks if a given password matches the stored hash. This way, even if our database is compromised, the actual passwords remain unknown.

Now that we have a handle on the concepts, let’s overview what our Library Management API will do.

Project Overview: Library Management API Features 🌟

Our Library Management API is a web service that handles common library operations in a RESTful way. In a nutshell, it supports:

  1. User Registration & Roles: Anyone can register a new user via the API (for simplicity). Users have a role, which can be "user" (regular patron) or "admin" (librarian). Roles determine what actions they can perform. By default, new users are regular users, but we can create an admin by specifying "role": "admin" in the registration request.
  2. JWT-based Login: A registered user can log in by providing their username and password, and if the credentials are correct, the API issues a JWT access token. This token must be sent with protected requests to prove authentication. For example, to add a book or list all users, you need to be logged in (and sometimes need to be an admin). The token is usually included in headers like:
Authorization: Bearer <your_jwt_token>

3. Book Management (CRUD): The API lets you C reate, R ead, U pdate, and D elete books in the library:

  • Admins can add new books (POST /books), edit book details (PUT /books/<id>), or delete a book (DELETE /books/<id>). These actions are restricted to admin users only.
  • Any logged-in user can view the list of books (GET /books). We even support query filters – for example, GET /books?author=Mark Twain would return books by Mark Twain. (Internally, we use simple query parameters to filter by title, author, or ISBN.)

Borrowing & Returning Books: Users can borrow books and return them via the API:

  • To borrow a book: POST /transactions/borrow with a JSON body like {"book_id": 5} will mark that book as borrowed by the current user (provided it’s available). This decreases the available quantity of that book by 1 and records a transaction.
  • To return a book: POST /transactions/return with {"book_id": 5} will mark the book as returned (if that user had previously borrowed it and not yet returned it), increasing its quantity by 1 and timestamping the transaction as returned.

Transactions Tracking: Every borrow/return action creates or updates a Transaction record. This helps in tracking which user has borrowed which book and when, and if/when they returned it. (Useful for checking overdue books or usage stats in a real system!)

Role-Based Access Control: Certain endpoints require the user to be an admin. For example, listing all users (GET /users) or creating/editing/deleting books should only be done by an admin. We enforce this in code by checking the user’s role from the JWT token and returning 403 Forbidden if they lack privileges. Regular users can borrow/return books and view the book list, but not meddle with other users or the library inventory.

In essence, the API covers the basics of a library system: user management, authentication, managing books, and recording borrow/return transactions. It’s all built with Flask, using SQLAlchemy for the database and JWT for security. Now, let’s get our hands dirty with the code! 🔧

(The full source code is available on GitHub: Wyverical/library-management-application-using-REST-API . We’ll reference parts of it below.)

GitHub - Wyverical/library-management-application-using-REST-API

Project Setup and Entry Point (run.py)

First, how do we start the Flask application? The entry point of the app is the run.py file. It’s very short – essentially just initializing the app and running the development server. Here’s what it contains:

# run.py
from library_api import create_app

app = create_app()
if __name__ == "__main__":
    app.run(debug=True)

What does this do?

  • It imports create_app from our library_api package (which is the main application package containing all our code).
  • It calls create_app() to get a Flask application instance. This follows the application factory pattern – a function that sets up and returns a Flask app object.
  • It then runs the app if the script is executed directly (__name__ == "__main__"). debug=True means we run in development mode, so we get hot reloading and helpful error messages.

By running python run.py, Flask will start a local development server (by default on ** http://127.0.0.1:5000). The app itself is created inside library_api/__init__.py (which we’ll examine soon).

So run.py is just a thin wrapper to bootstrap our app. This is a common Flask project structure: keep the creation of app (and initialization of extensions) in a factory function, and use a separate script (or WSGI file) to launch it.

Dependencies (requirements.txt)

Our project relies on several Python packages. The requirements.txt file pins these dependencies. Key libraries include:

  • Flask 3.1.0 — The web framework powering API
  • Flask-SQLAlchemy 3.0.3 — Provides SQLAlchemy integration with Flask (so we can use db = SQLAlchemy(app) smoothly.
  • Flask-JWT-Extended 4.7.1 — Adds JWT authentication support (decorators for protected routes, token creation, etc).
  • SQLAlchemy 2.0.3 — The core ORM library for database operations.
  • Passlib 1.7.4 (with bcrypt backend) — For hashing passwords securely.
  • Other common Flask dependencies like Werkzeug, Jinja2, etc., come along for ride.

When setting up the project, you would typically run pip install -r requirements.txt to install all these. The GitHub README even highlights these, noting the versions used for compatibily. The nice thing about requirements.txt is that it ensures everyone uses the same library versions, avoiding “it works on my machine” issues.

Configuration (config.py)

Configuration settings for Flask (and extensions) are centralized in library_api/config.py. Instead of hardcoding values all over the place, we use a Config class and load it into the Flask app. This makes it easy to adjust settings or use environment variables. Here’s the config:

# library_api/config.py
import os
from datetime import timedelta

class Config:
    SECRET_KEY = os.environ.get("SECRET_KEY") or "super-secret-key"
    SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL") or "sqlite:///library.db"
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    JWT_SECRET_KEY = os.environ.get("JWT_SECRET_KEY") or "jwt-secret-key"
    JWT_ACCESS_TOKEN_EXPIRES = timedelta(days=1)

Let’s break down these settings:

  • SECRET_KEY: A secret string used by Flask (and some extensions) for security-related things. For instance, Flask-WTF uses it to protect forms, and it’s generally good to have it for session signing. Here it tries to fetch an environment variable SECRET_KEY if set, otherwise falls back to "super-secret-key". (In production, you’d want to set a strong secret in the environment; the hardcoded default is just for development convenience.)
  • SQLALCHEMY_DATABASE_URI: This tells SQLAlchemy what database to use. It first checks for an env var DATABASE_URL – if not found, it defaults to a SQLite database file named library.db in the project directory. SQLite is great for testing or small deployments because it’s just a file on disk (no separate server needed). You could point this to a Postgres or MySQL URI in a real deployment (e.g., via an env var).
  • SQLALCHEMY_TRACK_MODIFICATIONS: This is set to False to disable a feature we don’t need. It saves a bit of overhead by not tracking object changes explicitly — useful to turn off in all SQLAlchemy apps (it’s mainly for signalling support which we don’t use).
  • JWT_SECRET_KEY: A secret key specifically for signing JWTs. Flask-JWT-Extended uses this to sign and verify tokens. We keep it separate from the main SECRET_KEY for clarity. Again, it checks the environment first and defaults to "jwt-secret-key". In production, you’d want this to be a long random string so that tokens cannot be forged.
  • JWT_ACCESS_TOKEN_EXPIRES: This configures how long our JWTs are valid. We set it to 1 day (using Python’s timedelta(days=1)). This means when a user logs in and gets a token, that token will expire in 24 hours. You can adjust this as needed (shorter for more security, or longer for convenience, or even use refresh tokens – but that’s beyond our basic setup).

All these settings will be loaded into the app later via app.config.from_object(Config) . Using a class for config is a common Flask pattern, and it allows default values that can be overridden by environment variables, which is handy for different environments (dev, test, production).

Data Models (models.py)

Now, onto defining the data structure of our library system. In library_api/models.py we define three SQLAlchemy models: User, Book, and Transaction. Each corresponds to a database table. SQLAlchemy makes this easy by letting our classes inherit db.Model and defining attributes as columns.

We start by importing the db object (the SQLAlchemy instance) and other needed things:

# library_api/models.py (imports and setup)
from . import db
from datetime import datetime
from passlib.hash import bcrypt

Here from . import db grabs the db object that will be initialized in our app (we’ll see in __init__.py that db = SQLAlchemy() is created at the package level). We also import datetime for timestamping, and bcrypt from Passlib for password hashing.

User Model 👥

class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.Text, nullable=False)
    role = db.Column(db.String(10), nullable=False, default="user")

    def __init__(self, username, password, role="user"):
        self.username = username
        self.password = bcrypt.hash(password)
        self.role = role
    def verify_password(self, password):
        return bcrypt.verify(password, self.password)

This defines a table “users” with columns:

  • id: Integer primary key, auto-generated.
  • username: String (up to 80 chars), must be unique (no two users with same username) and not null.
  • password: Text field (we’ll store hashed passwords here, so length can vary, hence Text type).
  • role: String (up to 10 chars) indicating user role; not null and defaults to "user" (so regular user). We’ll use "admin" for admin users.

Inside the class, we have a custom __init__ and a method:

  • The __init__ takes username, password, and an optional role. It immediately hashes the plain password using bcrypt.hash() before storing it. For example, if password = "secret123", after bcrypt.hash(password) it might store something like "$2b$12$GhvMmNVjRW...Tr8m" – a bcrypt hash which includes salt and cannot be reversed. This means even we (as developers) never see the actual password, only the hash.
  • The verify_password method takes a plain password and uses bcrypt.verify(candidate_password, stored_hash) to check if it matches the saved hash. This is used during login: we compare the provided password with the hash in DB.

🔒 Security note: Using bcrypt via Passlib gives us a strong hashing mechanism automatically. We don’t have to manage salts or work factors manually — Passlib does it. This makes our life easier and our users’ passwords safer.

Book Model 📚

class Book(db.Model):
    __tablename__ = "books"
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), nullable=False)
    author = db.Column(db.String(120), nullable=False)
    isbn = db.Column(db.String(50), nullable=False)
    published_year = db.Column(db.Integer, nullable=False)
    category = db.Column(db.String(120))
    quantity = db.Column(db.Integer, default=1)

The Book model is straightforward:

  • id: Primary key.
  • title: Title of the book (e.g., “The Great Gatsby”), required.
  • author: Author name, required.
  • isbn: ISBN number (as a string to include hyphens or X if needed), required.
  • published_year: The year the book was published, as an integer, required.
  • category: Category/genre of the book (e.g., “Fiction”, “Science Fiction”), optional (nullable by default if not specified).
  • quantity: How many copies are available in the library, defaulting to 1. Each borrow will decrement this, each return will increment it.

We don’t define custom methods for Book here — all our logic for adding/updating books will live in the route functions. But by defining this model, SQLAlchemy can create a books table and we can use Book.query to search, etc.

Transaction Model 🔄

class Transaction(db.Model):
    __tablename__ = "transactions"
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
    book_id = db.Column(db.Integer, db.ForeignKey("books.id"), nullable=False)
    date_borrowed = db.Column(db.DateTime, default=datetime.utcnow)
    date_returned = db.Column(db.DateTime, nullable=True)

The Transaction model links a User to a Book, with timestamps:

  • id: Primary key.
  • user_id: Foreign key to a user (the one who borrowed the book). db.ForeignKey("users.id") means this must match an id from the users table.
  • book_id: Foreign key to a book (the book that was borrowed).
  • date_borrowed: DateTime of when the borrow happened. It defaults to the current UTC time on creation.
  • date_returned: DateTime of when the book was returned, if it has been returned. It’s nullable, and will remain NULL (or None in SQLAlchemy) until a return is processed. So an active loan is one with date_returned == None.

We don’t explicitly add relationships here (like back-references), but SQLAlchemy can be used to navigate relationships if needed. For simplicity, our logic will manually query and link these.

With these models, we have our database structure. How do they become actual tables? In our app factory (next section), we call db.create_all() which creates tables for all models that don’t yet exist. During development, this is an easy way to get started (in production, you might use migrations instead, but that’s another story).

Application Factory (__init__.py)

The library_api/__init__.py sets up the Flask app, configures it, and registers all our blueprints (the different route modules). This is where everything comes together. Let’s examine the critical parts of this file:

# library_api/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from .config import Configdb = SQLAlchemy()
jwt = JWTManager()

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    # Initialize extensions
    db.init_app(app)
    jwt.init_app(app)
    with app.app_context():
        from . import models  # import models to register them
        db.create_all()
    # Register blueprints for modular routes
    from .routes.auth import auth_bp
    from .routes.users import users_bp
    from .routes.books import books_bp
    from .routes.transactions import transactions_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(users_bp, url_prefix='/users')
    app.register_blueprint(books_bp, url_prefix='/books')
    app.register_blueprint(transactions_bp, url_prefix='/transactions')
    @app.route('/')
    def index():
        return "Library Management System API is running", 200
    return app

Here’s what’s happening step by step:

  • We import Flask and the extensions (SQLAlchemy, JWTManager) and our Config class.
  • We create db = SQLAlchemy() and jwt = JWTManager() at the top level (but note, we haven’t tied them to an app yet). This pattern allows us to avoid needing a global Flask app context during import – we will initialize them later with the app.
  • create_app function: This is our factory. When called, it:
  1. Creates a Flask app instance.
  2. Loads configuration into it: app.config.from_object(Config) loads all the uppercase attributes from our Config class into app.config. Now the app knows the database URI, secret keys, etc.
  3. Initializes the extensions with this app:
  • db.init_app(app) ties our SQLAlchemy object to this Flask app. Now db is active and knows about the app’s config.
  • jwt.init_app(app) does the same for JWT management. This sets up JWT handling (flask-jwt-extended will now read JWT_SECRET_KEY, etc.).

4. It enters an application context (with app.app_context():) – this is needed because we are about to create tables. Within this context:

  • It imports the models module (from . import models). This ensures the model classes are defined (remember, we define tables when the model classes are imported). If we don’t import them, db.create_all() might not know about them. This import line has a side effect of registering model classes with SQLAlchemy.
  • Calls db.create_all(). This tells SQLAlchemy to create database tables for any models that don5†L309-L317】. On first run, it will create users, books, transactions tables as defined. In subsequent runs (with the same database file), it won’t overwrite existing tables (so data stays persistent).

5. After that, we register blueprints:

We import each blueprint: auth_bp, users_bp, books_bp, transactions_bp from their respective modules in library_api/routes/*.py.

We register each with app.register_blueprint(), specifying a URL prefix for each:

  • The auth blueprint will be accessible under URLs that start with /auth (e.g., login route will become /auth/login).
  • Users blueprint under /users (e.g., create user is /users with POST).
  • Books under /books, Transactions under /transactions. This modularizes our endpoints. Each blueprint handles a specific set of related routes.

6. We define a simple index route "/" that just returns a message “Library Management System API is running”. This is a quick sanity check endpoint – useful to see if the server is up (it returns HTTP 200 with that message). It’s not strictly necessary, but nice to have.

7. Finally, create_app() returns the configured app object.

So when run.py calls create_app(), all of this setup happens: config loaded, database ready, blueprints registered, and we have all our endpoints in place. 💡 One important detail: The JWTManager extension doesn’t require much setup here beyond init_app. But under the hood, it will, for example, set up default behaviors for expired tokens, etc. We could customize JWT callbacks (like what to do on expired token) in this function if needed, but by default it’s okay.

At this point, if you run the app and visit the base URL (e.g., http://127.0.0.1:5000/), you’d see the “…API is running” message confirming everything’s wired up. Now let’s look at each group of routes in the routes/ directory to see how requests are handled.

Authentication Routes (auth.py)

Authentication (login) is handled in library_api/routes/auth.py. We use a Flask Blueprint here called auth_bp to group auth-related routes (maybe in the future we’d add a logout or token refresh here, but currently we just have login).

Key imports and setup in auth.py:

from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token
from library_api.models import User
from library_api import db

auth_bp = Blueprint("auth", __name__)
  • We import Blueprint, request, jsonify from Flask. request will give us the JSON payload, jsonify helps craft JSON responses easily.
  • Import create_access_token from flask_jwt_extended – this function will generate a JWT for us.
  • Import the User model to query the database for user info.
  • Create the blueprint: auth_bp = Blueprint("auth", __name__). The first argument is the blueprint’s name (used internally by Flask), second is the module’s name.

Now the login route:

@auth_bp.route("/login", methods=["POST"])
def login():
    data = request.get_json()
    if not data:
        return jsonify({"msg": "Missing JSON in request"}), 400

username = data.get("username")
    password = data.get("password")
    if not username or not password:
        return jsonify({"msg": "Missing username or password"}), 400
    user = User.query.filter_by(username=username).first()
    if user and user.verify_password(password):
        access_token = create_access_token(identity=user.username)
        return jsonify({"access_token": access_token}), 200
    else:
        return jsonify({"msg": "Bad username or password"}), 401

Explanation:

  • The route is /login on this blueprint, which will map to /auth/login overall (since we registered the blueprint under /auth). It only allows POST requests.
  • We grab the JSON body via request.get_json(). If the client didn’t send JSON, this could be None, so we check and return a 400 error if no JSON was found (perhaps the client forgot to set Content-Type: application/json or sent nothing).
  • We then extract username and password from the JSON. If either is missing, respond with a 400 Bad Request saying “Missing username or password”. (The client should provide both.)
  • Next, we query our database for a user with the given username: User.query.filter_by(username=username).first(). This will return the first User object with that username, or None if not found.
  • We then check: if a user is found anduser.verify_password(password) returns True, then the credentials are correct. verify_password (which we defined on the model) will hash the given password and compare with the stored hash.
  • If valid, we create a JWT: access_token = create_access_token(identity=user.username). The identity of the JWT is set to user.username – meaning when we decode the token later, we’ll use the username to identify the user. (We could also use user ID or any identifier; username is fine here since it’s unique.) The JWT will be signed using our JWT_SECRET_KEY and by default include an expiration (we set 1 day expiry in config).
  • We return a JSON response with the token: {"access_token": "..."} and HTTP 200 OK.
  • If the user wasn’t found or the password check failed, we return a 401 Unauthorized with message “Bad username or password”.

Important: We do not tell the client exactly what was wrong (for security, we avoid saying “user not found” vs “wrong password” — just a generic message). This route is not protected by JWT (obviously, since its purpose is to login and obtain a JWT).

Here’s an example of how a login request and response would look:

Request:POST /auth/login

{
  "username": "alice",
  "password": "alice123"
}

Response (200 OK)

{
  "access_token": "<long_jwt_token_string>"
}

The client should store this access_token (typically in memory or localstorage if a browser app) and then present it in the Authorization header for subsequent requests.

That’s it for auth.py — just a login endpoint. We don’t have a logout (with JWT, “logout” is usually handled client-side by discarding the token, or by having short expirations or a token revocation list on server — beyond our scope here).

User Routes (users.py)

User management (creating users, possibly listing or editing users) is handled in library_api/routes/users.py. This blueprint is for user-related operations. Right now, our implementation focuses on creating users (registration). The README mentioned an endpoint to list users (admin only) and update users, but let’s see what’s in the code:

Imports and setup:

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from library_api.models import User
from library_api import db
from library_api.utils import is_admin
from passlib.hash import bcrypt

users_bp = Blueprint("users", __name__)

We import Flask’s usual stuff, plus:

  • jwt_required and get_jwt_identity from flask_jwt_extended. jwt_required is a decorator to protect routes (requires a valid JWT), and get_jwt_identity() allows us to retrieve the identity (username, in our case) from the token of the current request.
  • The User model and db as usual.
  • A utility function is_admin from library_api/utils.py – presumably this checks if the current JWT identity belongs to an admin user.
  • bcrypt from Passlib (perhaps to hash a password manually if needed, though we also use User’s constructor which already hashes).

Define the blueprint: users_bp = Blueprint("users", __name__).

Now the Create User route:

@users_bp.route("", methods=["POST"])
def create_user():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"msg": "Missing JSON in request"}), 400
        username = data.get("username")
        password = data.get("password")
        role = data.get("role", "user")
        if not username or not password:
            return jsonify({"msg": "Missing username or password"}), 400
        if User.query.filter_by(username=username).first():
            return jsonify({"msg": "Username already exists"}), 400
        new_user = User(username, password, role)
        # Print the hash for debugging (remove in production)
        print(f"Created user hash for '{username}': {new_user.password}")
        db.session.add(new_user)
        db.session.commit()
        return jsonify({"msg": f"User '{username}' created successfully"}), 201
    except Exception as e:
        print("Error creating user:", e)
        return jsonify({"msg": "Internal server error"}), 500

Explanation:

  • Route is POST /users (note the empty string "" in route decorator, meaning the blueprint’s prefix /users is the whole path). This is the registration endpoint.
  • It’s not protected by jwt_required here, meaning anyone can hit it. In a real app, you might allow open registration or restrict it to admins – here it’s open (so the first user can create an admin account, etc.).
  • We parse JSON and ensure it’s present. If not, 400 error.
  • Extract username, password, and role. If role is not provided, default to "user". This lets us create an admin by specifying "role": "admin" in the request, otherwise the user will be a regular user.
  • If username or password is missing, return 400.
  • We then check the database to see if a user with that username already exists (User.query.filter_by(username=username).first()). If yes, we return 400 with message that username already exists. This prevents duplicate usernames.
  • If all good, we instantiate a User object: new_user = User(username, password, role). As we saw, this will automatically hash the password thanks to the User model’s __init__. We even have a debug print of the hash (this was probably used during development to verify that hashing works).
  • We add the new user to the database session and commit it: this will INSERT the new user into the users table.
  • On success, we return a 201 Created with a message confirming the username was created.
  • If any exception is thrown in the process (for example, a database error), we catch it, print an error on the server console, and return a generic 500 Internal Server Error.

Example request to create a user:

POST /users
Content-Type: application/json

{
  "username": "admin",
  "password": "admin123",
  "role": "admin"
}

Example response (201 Created):

{ "msg": "User 'admin' created successfully" }

Now we have an admin user in the system. 🎉

The code above doesn’t explicitly enforce that only admins can create users. In some systems, you might want only an admin to create another admin. Our implementation is simple — it allows anyone to call this. This could be one area to extend (e.g., require an admin JWT to create another admin).

What about listing users or updating users? The GitHub README suggests there is a GET /users for admins to list all users, and a PUT /users/<id> for upda. If we had those, we’d likely use @jwt_required() and check is_admin() for GET (to allow only admins) and for PUT (to allow admin or the user themselves). However, in the code snippet we have, those routes are not present. It’s possible they were planned but not implemented fully in code.

If we were to implement them, it might look like:

@users_bp.route("", methods=["GET"])
@jwt_required()
def list_users():
    if not is_admin():
        return jsonify({"msg": "Admin privilege required"}), 403
    users = User.query.all()
    output = [ {"id": u.id, "username": u.username, "role": u.role} for u in users ]
    return jsonify(output), 200

And for updating a user:

@users_bp.route("/<int:user_id>", methods=["PUT"])
@jwt_required()
def update_user(user_id):
    current_user = get_jwt_identity()  # current username from token
    user = User.query.get_or_404(user_id)
    # allow if current user is admin or it's the same user updating their own profile
    updater = User.query.filter_by(username=current_user).first()
    if updater.role != "admin" and updater.id != user.id:
        return jsonify({"msg": "Unauthorized"}), 403
    data = request.get_json()
    # ... update fields accordingly ...
    db.session.commit()
    return jsonify({"msg": f"User '{user_id}' updated"}), 200

But again, these are not in the provided code, so we’ll not dwell too much. Just know that using jwt_required() and is_admin() in similar fashion as the Books routes (which we’ll see next) would enforce those permissions.

Now that users (and an admin) can be created and we have login, let’s move to the book management.

Book Routes (books.py)

All book-related endpoints live in library_api/routes/books.py. This is one of the larger route files, since we have four main actions: create a book, list books, update a book, delete a book. The blueprint is set up similarly:

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from library_api.models import Book
from library_api import db
from library_api.utils import is_admin

books_bp = Blueprint("books", __name__)

We import what we need: Flask basics, the jwt_required decorator, the Book model, the db, and our is_admin utility to check admin rights.

Now the routes:

1. Create a Book (Admin Only)

@books_bp.route("", methods=["POST"])
@jwt_required()
def create_book():
    if not is_admin():
        return jsonify({"msg": "Admin privilege required"}), 403
    data = request.get_json()
    if not data:
        return jsonify({"msg": "Missing JSON in request"}), 400
    title = data.get("title")
    author = data.get("author")
    isbn = data.get("isbn")
    published_year = data.get("published_year")
    category = data.get("category", "")
    quantity = data.get("quantity", 1)
    if not all([title, author, isbn, published_year]):
        return jsonify({"msg": "Missing required book fields"}), 400
    new_book = Book(
        title=title,
        author=author,
        isbn=isbn,
        published_year=published_year,
        category=category,
        quantity=quantity,
    )
    db.session.add(new_book)
    db.session.commit()
    return jsonify({"msg": f"Book '{title}' created"}), 201

Explanation

  • Endpoint: POST /books (since blueprint prefix is /books and route is empty string). Protected by @jwt_required(), meaning a valid JWT must be provided or Flask-JWT-Extended will automatically block the request with a 401 error.
  • After that, we manually call is_admin(). Let’s quickly check is_admin in utils.py:
# library_api/utils.py
from flask_jwt_extended import get_jwt_identity
from .models import User

def is_admin():
    current_username = get_jwt_identity()
    user = User.query.filter_by(username=current_username).first()
    return user is not None and user.role.lower() == "admin"

This utility gets the current JWT identity (which we set as username in the token) and looks up the user in DB, then returns True if that user exists and ha. So it’s a quick way to check admin rights. We use this in various routes.

  • If is_admin() returns False, we immediately return 403 Forbidden with message “Admin privilege required”. This ensures only admin users can create books.
  • Assuming the user is admin, we parse JSON and ensure it exists.
  • We extract required fields: title, author, isbn, published_year. Category and quantity are optional (category default to empty string if not given, quantity default to 1).
  • We verify that title, author, isbn, and published_year are all provided (not all([...]) check). If any of these core fields is missing, we return 400 error telling that required book fields are missing.
  • If everything is present, we create a Book instance with those fields.
  • Add it to session and commit — writing the new book to the database.
  • Return 201 Created with a message including the book title.

Example request (admin token required):

POST /books
Authorization: Bearer <ADMIN_JWT_TOKEN>
Content-Type: application/json

{
  "title": "Flask for Beginners",
  "author": "John Doe",
  "isbn": "1234567890",
  "published_year": 2021,
  "category": "Programming",
  "quantity": 5
}

Response:201 Created

{ "msg": "Book 'Flask for Beginners' created" }

If a non-admin tried this, they would get 403 {"msg": "Admin privilege required"}. If any field was missing, a 400 {"msg": "Missing required book fields"}.

2. List Books (All Users)

@books_bp.route("", methods=["GET"])
@jwt_required()
def list_books():
    title = request.args.get("title")
    author = request.args.get("author")
    isbn = request.args.get("isbn")

    query = Book.query
    if title:
        query = query.filter(Book.title.ilike(f"%{title}%"))
    if author:
        query = query.filter(Book.author.ilike(f"%{author}%"))
    if isbn:
        query = query.filter(Book.isbn.ilike(f"%{isbn}%"))

    books = query.all()
    output = []
    for book in books:
        output.append({
            "id": book.id,
            "title": book.title,
            "author": book.author,
            "isbn": book.isbn,
            "published_year": book.published_year,
            "category": book.category,
            "quantity": book.quantity,
        })
    return jsonify(output), 200

Expanation:

  • Endpoint: GET /books. Protected by jwt_required() – so you must be logged in (user or admin, any role) to list books. (If we wanted, we could make listing books public by removing jwt_required, but perhaps we assume an authenticated app context.)
  • We don’t require admin here, because even regular users should be able to see what books are available.
  • We check query parameters (request.args) for title, author, isbn. If provided, we’ll filter results by those. We use ilike (case-insensitive LIKE) with wildcards %term% to allow partial matches. So you could search for books by partial title or author name.
  • We build the query dynamically: start with Book.query (which is SELECT * FROM books essentially). If a filter is present, add a filter condition.
  • After applying possible filters, we call .all() to execute and get all matching books.
  • We then prepare an output list of dictionaries, where each dictionary has the book’s details. We include id, title, author, etc. This is because we want to return JSON; we could also use something like marshmallow or manual serialization. Here it’s manual: iterate over books and append dicts.
  • Return the output list as JSON with 200 OK.

If no query params are given, this returns all books. If there are none, it returns an empty list [].

Example: GET /books (with a valid token) could return:

[\
  {\
    "id": 1,\
    "title": "Flask for Beginners",\
    "author": "John Doe",\
    "isbn": "1234567890",\
    "published_year": 2021,\
    "category": "Programming",\
    "quantity": 5\
  },\
  {\
    "id": 2,\
    "title": "Introduction to Python",\
    "author": "Jane Smith",\
    "isbn": "9876543210",\
    "published_year": 2019,\
    "category": "Programming",\
    "quantity": 2\
  }\
]

If we only wanted books by John Doe, GET /books?author=John Doe would filter accordingly.

3. Update Book (Admin Only)

@books_bp.route("/<int:book_id>", methods=["PUT"])
@jwt_required()
def update_book(book_id):
    if not is_admin():
        return jsonify({"msg": "Admin privilege required"}), 403

    book = Book.query.get_or_404(book_id)
    data = request.get_json()
    # Update only provided fields, leave others unchanged
    book.title = data.get("title", book.title)
    book.author = data.get("author", book.author)
    book.isbn = data.get("isbn", book.isbn)
    book.published_year = data.get("published_year", book.published_year)
    book.category = data.get("category", book.category)
    book.quantity = data.get("quantity", book.quantity)

    db.session.commit()
    return jsonify({"msg": f"Book '{book_id}' updated"}), 200

Expanation:

  • Endpoint: PUT /books/<book_id> (e.g., /books/1 to update book with id 1). Protected by JWT and admin check.
  • If not admin: 403 returned.
  • We fetch the book by ID: Book.query.get_or_404(book_id). This is a handy method – it will return the book if found, or automatically return a 404 error if not found. So if someone tries to update a non-existing book, they get a 404.
  • We parse JSON body into data. We then update each field if provided in the JSON, otherwise we keep the old value:
  • book.title = data.get("title", book.title) means “update the title if title is in the request, otherwise keep book.title as is”.
  • We do the same for author, isbn, published_year, category, quantity.
  • This way, the client can send just the fields they want to change. For example, one could send {"quantity": 10} to update only the quantity.
  • Commit the changes to the database.
  • Return 200 OK with a message.

Example: say we want to change the title and quantity of book 1:

PUT /books/1
Authorization: Bearer <ADMIN_JWT_TOKEN>
Content-Type: application/json

{
  "title": "Flask for Absolute Beginners",
  "quantity": 10
}

Response: 200 OK

{ "msg": "Book '1' updated" }

If a non-admin tries, they get 403. If book 1 doesn’t exist, they’d get a 404 error (handled by get_or_404 raising that automatically).

4. Delete Book (Admin Only)

@books_bp.route("/<int:book_id>", methods=["DELETE"])
@jwt_required()
def delete_book(book_id):
    if not is_admin():
        return jsonify({"msg": "Admin privilege required"}), 403

    book = Book.query.get_or_404(book_id)
    db.session.delete(book)
    db.session.commit()
    return jsonify({"msg": f"Book '{book_id}' deleted"}),
  • Endpoint: DELETE /books/<book_id>. JWT & admin required.
  • If not admin, 403.
  • Find the book or 404 if not found.
  • db.session.delete(book) marks it for deletion, commit to apply.
  • Return 200 OK with message.

Simple as that. If the book didn’t exist, the user gets 404. If successful, they get confirmation.

For example: DELETE /books/1 by an admin -> Response 200 {"msg": "Book '1' deleted"}.

With these, our book inventory can be fully managed by an admin user via the API.

Transaction Routes (transactions.py)

Finally, borrowing and returning books are handled in library_api/routes/transactions.py. This blueprint deals with transactions (borrow/return events). Let’s see:

Imports and blueprint setup:

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from library_api.models import Transaction, Book, User
from library_api import db
from datetime import datetime

transactions_bp = Blueprint("transactions", __name__)

We import get_jwt_identity to identify the user making the request, and import the Transaction, Book, User models because we’ll interact with all three.

Two main routes here: borrow a book and return a book. Both are POST requests (since they create or modify a transaction record). We could have used PUT for return, but treating both as actions via POST is okay (since they aren’t idempotent and represent actions).

1. Borrow a Book

@transactions_bp.route("/borrow", methods=["POST"])
@jwt_required()
def borrow_book():
    current_username = get_jwt_identity()
    user = User.query.filter_by(username=current_username).first()

    data = request.get_json()
    if not data:
        return jsonify({"msg": "Missing JSON in request"}), 400

    book_id = data.get("book_id")
    if not book_id:
        return jsonify({"msg": "book_id is required"}), 400

    book = Book.query.get_or_404(book_id)
    if book.quantity < 1:
        return jsonify({"msg": "Book not available"}), 400

    book.quantity -= 1
    transaction = Transaction(user_id=user.id, book_id=book.id)
    db.session.add(transaction)
    db.session.commit()
    return jsonify({"msg": f"Book '{book.title}' borrowed"}), 200

Explanation:

  • Endpoint: POST /transactions/borrow. Requires JWT (so only logged-in users can borrow).
  • We get current_username from token and retrieve the User object for that username. This is the user who is borrowing.
  • Parse JSON; ensure it’s present.
  • Get book_id from JSON. If not provided, return 400 “book_id is required” – the user must specify which book to borrow.
  • Fetch the Book by that ID (404 if not found).
  • Check book.quantity. If it’s less than 1, that means no copies available to borrow (all copies are already lent out). We return 400 “Book not available”. (Alternatively, could be 409 Conflict or something semantically, but 400 is used here for simplicity.)
  • If available, decrement book.quantity by 1 to indicate one copy is now taken.
  • Create a Transaction record with user_id and book_id. The date_borrowed will auto-set to now (default).
  • Add it to session and commit. This will save both the updated book quantity and the new transaction in one go (because they’re in the same session).
  • Return 200 OK with message like “Book ‘Flask for Beginners’ borrowed”.

Example request:

POST /transactions/borrow
Authorization: Bearer <USER_JWT_TOKEN>
Content-Type: application/json

{ "book_id": 1 }

If book 1 exists and quantity was > 0, and user is logged in, Response might be:

{ "msg": "Book 'Flask for Beginners' borrowed" }

Now book 1’s quantity is decreased by 1, and a transaction is recorded linking this user and book with date_borrowed set.

If the book was not available (quantity 0), response: 400 {"msg": "Book not available"}. If book_id missing: 400 {"msg": "book_id is required"}.

2. Return a Book

@transactions_bp.route("/return", methods=["POST"])
@jwt_required()
def return_book():
    current_username = get_jwt_identity()
    user = User.query.filter_by(username=current_username).first()

    data = request.get_json()
    if not data:
        return jsonify({"msg": "Missing JSON in request"}), 400

    book_id = data.get("book_id")
    if not book_id:
        return jsonify({"msg": "book_id is required"}), 400

    transaction = Transaction.query.filter_by(user_id=user.id, book_id=book_id, date_returned=None).first()
    if not transaction:
        return jsonify({"msg": "No active borrow transaction found"}), 400

    transaction.date_returned = datetime.utcnow()
    book = Book.query.get(book_id)
    book.quantity += 1
    db.session.commit()
    return jsonify({"msg": f"Book '{book.title}' returned"}), 200

Explanation:

  • Endpoint: POST /transactions/return. JWT required.
  • Identify current user (same pattern: get username, fetch user object).
  • Require JSON and book_id in it (similar checks as borrow).
  • Now we look for a Transaction that matches this user and book and has date_returned is None (meaning the book is currently borrowed and not yet returned by this user).
  • Transaction.query.filter_by(user_id=user.id, book_id=book_id, date_returned=None).first()
  • We use .first() to get one if exists. (Assuming a user can only have one active transaction per book; if the user borrowed the same book multiple times separately, there would be multiple records but only one with date_returned null at a time.)
  • If no such transaction is found, it means the user doesn’t currently have that book borrowed. Maybe they never borrowed it or already returned it. We return 400 “No active borrow transaction found”.
  • If we found a transaction, we set its date_returned to now (UTC). This marks the book as returned in the record.
  • We then get the Book and increment its quantity by 1, since one copy is back on the shelf.
  • Commit the session to save both the transaction update and book update.
  • Return 200 OK “Book ‘Title’ returned”.

Example request:

POST /transactions/return
Authorization: Bearer <USER_JWT_TOKEN>
Content-Type: application/json

{ "book_id": 1 }

If the user had borrowed book 1 and not yet returned it, the response:

{ "msg": "Book 'Flask for Beginners' returned" }

If the user didn’t have an active borrow for book 1, they’d get 400 {"msg": "No active borrow transaction found"} (maybe they already returned it or never borrowed it).

After returning, the book’s quantity is incremented back.

That covers the main logic of borrowing and returning.

A couple of things to note:

  • We don’t enforce any limit on how many books a user can borrow simultaneously, or any due date concept (though date_returned allows calculating how long a borrow lasted).
  • There’s no check for admin here — any logged-in user can borrow or return because that’s the normal use case.
  • We trust the user to return the correct book they borrowed — our check ensures they had borrowed it.

Now that we’ve covered all routes, let’s talk a bit about testing these APIs.

Testing the API (VS Code REST Client and test.http)

Once our API is running (via python run.py), we’ll want to test these endpoints. You can use tools like Postman, cURL, or even Python scripts. The GitHub repo provides a convenient way to test using the VS Code REST Client extension. This extension lets you write HTTP requests in a .http file and send them easily.

There’s a file test.http in the repo which contains sample requests for all the endpoints. Using it, you can simulate an entire flow. For example, it likely includes:

  1. Create an Admin User — a POST /users with { "username": "admin", "password": "admin123", "role": "admin" }.
  2. Login as Admin — POST /auth/login with the admin credentials to get a token.
  3. Create a Book — POST /books with some book data (using the admin token in Authorization header).
  4. Create a Regular User — POST /users with role user.
  5. Login as Regular User — to get a user token.
  6. List Books — GET /books with the user token.
  7. Borrow a Book — POST /transactions/borrow with user token and a book_id.
  8. Return a Book — POST /transactions/return with user token and the same book_id.

The REST Client file allows sequential execution and uses variables for tokens etc. If using VS Code, you can open test.http, hover over each request and click “Send Request”. It’s a quick way to verify everything works as expected.

For instance, after creating an admin and logging in, the Authorization: Bearer <token> header in subsequent requests can be set to use the returned JWT. The test file might do that for you by capturing the token.

Even without VS Code, you can mimic these with cURL commands in a terminal:

curl -X POST <http://127.0.0.1:5000/users> -H "Content-Type: application/json" -d '{"username": "admin", "password": "admin123", "role": "admin"}'

…and so on for each endpoint.

The key is to always include the JWT for protected endpoints. If you forget, you’ll get a 401 Unauthorized with a message like “Missing Authorization Header” from Flased.

Testing is crucial to ensure each piece works: creating users, logging in, forbidden access for non-admins, etc. The provided test.http helps automate that manual testing to a degree.

Conclusion: Scaling, Deploying, and Extending 🚀

We’ve built a complete RESTful API for a library system with Python and Flask! Let’s reflect and consider next steps:

Recap of what we built: A Flask app with modular blueprints, connected to a SQLite database via SQLAlchemy. We implemented user registration and login with hashed passwords and JWT auth. We added role-based access control so only admins can modify users or books. We created endpoints to manage books and to handle borrowing/returning transactions. The API is secured by JWT tokens and checks for admin rights where appropriate.

Scaling Considerations: While SQLite is fine for development and small deployments, a larger scale system should use a more robust database (like PostgreSQL or MySQL). SQLAlchemy makes that switch easy — just change the SQLALCHEMY_DATABASE_URI to a new engine (and probably use migrations for schema changes). The app structure with Flask is solid for scaling out: you could run multiple instances behind a load balancer, as the app is stateless (JWT means the session is kept client-side, and the database can be a single source of truth). If the user base grows, you might implement caching for book lists or use pagination on the /books endpoint (so we don’t send thousands of records at once). For deployment, consider using a production WSGI server (like Gunicorn or uWSGI) instead of the Flask dev server, and possibly containerize the app with Docker for consistency.

Security Improvements: Our JWT tokens last 1 day. In a real app, you might add a refresh token system to allow long-lived sessions without risking stolen tokens, or shorten the access token lifespan. We might also want to enforce HTTPS in production so tokens are not intercepted. Additionally, some admin-only actions might benefit from extra confirmation or logging.

Extending the API: There are many features you could add:

  • User Profile Editing: Right now, users can’t even change their password via the API. We could add a PUT /users/<id> so users can update their info (and admins can update anyone’s info). This would involve verifying identity (user can only edit themselves unless admin).
  • Delete User or Change Role: An admin might need to promote a user to admin or remove a user — endpoints for that could be added.
  • More Book Info: We could add fields like description, publisher, etc., or support multiple ISBN editions. Also, searching could be expanded (by category, or a general search endpoint).
  • Transaction History: Endpoints to list what books a user has borrowed, or which users have borrowed a particular book. For example, GET /users/<id>/transactions or GET /books/<id>/borrowers.
  • Due Dates and Overdue Management: We could add a due date to transactions (say 14 days from borrow) and have logic to mark books overdue if not returned in time. This could notify or restrict further borrows.
  • Testing & CI: We manually tested via HTTP requests. For a maintainable project, one could write automated tests (using PyTest and maybe Flask’s test client) to ensure each endpoint works and enforces permissions correctly.

Blueprint Modularization: We separated routes into files by concern (auth, users, books, transactions). This modular design is handy as the project grows — e.g., if we wanted a separate blueprint for, say, “reports” or “notifications”, we could add it without cluttering the existing code. Blueprints can also be moved into packages for even larger apps. Our use of an application factory and Blueprints follows good practices35】.

Deployment: Running in debug mode is not for production. We’d switch debug=False and maybe use environment variables for configuration (we already respect env vars for secrets and DB URL). Deploying to a platform like Heroku or AWS would involve setting those env vars and using a proper server. Because our code uses only standard libraries and the database is abstracted by SQLAlchemy, deployment is straightforward. Just remember to run db.create_all() or use migrations to set up the database schema on first run.

Community & Next Steps: The libraries used (Flask, Flask-JWT-Extended, SQLAlchemy, Passlib) have great documentation and communities. If you’re looking to extend this project, you can find more in Flask’s docs on features like error handlers or Flask-JWT-Extended’s docs for things like token refreshing and complex claims. For example, Flask-JWT-Extended allows adding custom claims to the JWT (maybe store the user’s role in the token to avoid DB lookup on each request, though that has trade-offs).

In conclusion, we’ve created a fully functional API that demonstrates how to put together authentication, database operations, and route handling in Flask. 🎉 It’s like having the library’s backend under control with a few hundred lines of Python. With this foundation, you can build upon and tweak it to fit more complex requirements.


Originally published on Medium.

Share:

More articles

Back to Sarvesh's AI Newsletter
Search everything on the site