Welcome to the backend API for the Bookstore Management System! This is a robust, full-featured REST API built with FastAPI that handles everything a modern online bookstore needs: from customer shopping carts and secure checkouts to automated admin inventory restocks, 7-day persistent authentications, and live database integrations.
- Framework: FastAPI (High performance, easy to learn, fast to code, ready for production)
- Database: PostgreSQL (Robust relational database hosted on Render)
- ORM: SQLAlchemy (Object Relational Mapper for database interactions)
- Data Validation: Pydantic (Type hints at runtime for robust payload validation)
- Authentication: JWT (JSON Web Tokens) explicitly secured via HttpOnly, SameSite Cookies.
- Security: Passlib (bcrypt) for secure password hashing
- Package Manager:
uv(Extremely fast Python package installer and resolver)
This API is divided into two main roles: Customers (Standard Users) and Admins (Store Managers/Owners).
- Registration: New users can sign up providing a
first_nameandlast_name. The system intelligently auto-generates unique usernames. - Login: Secure login returning a JWT access token baked inside a secure browser cookie. The cookie implements
max_age=604800(7 days) for persistent logins without sacrificing security headers. - Profile Management:
- Users can view their profile (
GET /users/me). - Users can dynamically update their names, addresses, and phone numbers (
PUT /users/me). - Users can securely change their passwords (
PUT /users/me/password).
- Users can view their profile (
- Admin Powers: Admins can permanently delete user accounts (
DELETE /users/{user_id}).
- Public Browsing: Anyone (even unauthenticated users) can view the book catalog.
- Supports pagination (
skip,limit). - Supports dynamic fuzzy searching by Title, Author, or ISBN (using PostgreSQL
pg_trgmextension for typo tolerance). - Supports array-based filtering by Category, Min Price, and Max Price.
- Supports sorting results via
sort_by(price_asc,price_desc,newest).
- Supports pagination (
- Detailed Views: Fetching a single book (
GET /books/{id}) automatically eager-loads and displays all user reviews. - Admin Powers:
- Add new books (
POST /books/). - Update book details entirely (
PUT /books/{id}) or partially (PATCH /books/{id}). - Upload high-quality book covers that are served statically (
POST /books/{id}/cover). - Soft-delete books from the inventory, preserving historical sales data (
DELETE /books/{id}).
- Add new books (
- Cart Management:
- Add items to cart (
POST /sales/). The API validates that sufficientstock_quantityexists before allowing the addition. - View cart (
GET /sales/cart). The API dynamically calculates thetotal_pricebased on current prices (and applies any active book discounts!). - Update quantities (
PUT /sales/cart/{item_id}). - Remove items (
DELETE /sales/cart/{item_id}).
- Add items to cart (
- Checkout:
- Process the entire cart (
POST /sales/sale). - The API uses SQLAlchemy
with_for_update()to lock the book rows, preventing race conditions if two customers try to buy the last copy simultaneously! - Upon successful checkout, stock is decremented, cart is cleared, and historical
unit_pricemarkers are permanently recorded in theSalerecords.
- Process the entire cart (
- Order History: Customers can view their past orders and track their delivery status (
GET /sales/history). - Admin Powers:
- Admins can update order statuses (e.g., from "Pending" to "Shipped" or "Delivered") (
PUT /sales/{sale_id}/status).
- Admins can update order statuses (e.g., from "Pending" to "Shipped" or "Delivered") (
- Wishlists: Customers can save books for later (
POST /favorites/). - Reviews: Customers can leave exactly one review per book. The API actively prevents duplicate reviews from the same user.
- Dashboard Stats: An insanely fast endpoint (
GET /admin/dashboard) designed for frontend UIs to display:- Total system revenue.
- Total successful orders.
- Total registered customers and catalog size.
- Active low-stock alerts.
- Advanced SQL Analytics:
- Top 5 Best Selling Books: Calculates lifetime copies sold.
- Top 5 Highest Spending Customers: Calculates lifetime revenue per user.
- Top Vendors: Calculates the admins who have sold the highest total quantity of books (
GET /sales/top-vendors). - Best Deals: Retrieves the books with the highest active discount percentages (
GET /books/best-deals).
- Manual Orders: Admins can place a pending order to publishers to restock books (
POST /requisitions/). - Smart Auto-Ordering:
- Admins can trigger
POST /requisitions/auto. - The API scans for any book dipping below
10copies in stock. - If a low-stock book has NO pending orders, the API calculates exactly how many copies of that book sold in the last 3 months (90 days).
- It automatically drafts an order for exactly that many copies (or a default of 10 if it's a new book), ensuring the store never runs out of bestsellers!
- Admins can trigger
- Receiving Inventory: When the publisher delivers the books, Admins hit
PUT /requisitions/{id}/receiveto mark it complete and magically increment thestock_quantityin the store!
To ensure the backend can handle thousands of concurrent users and massive order histories without slowing down, we implemented strategic PostgeSQL B-Tree Indexing and Query Optimization.
- Foreign Key Indexes: Every single foreign key in the database (
user_idandbook_idacross the Carts, Sales, Reviews, Favorites, and Requisitions tables) is explicitly indexed (index=True). - The Benefit: Without these indexes, an endpoint like "View Order History" (
GET /sales/history) would force PostgreSQL to perform a Sequential Scan (checking every single row in the Sales table one by one). By creating indexes, Postgres instantly looks up the user's records in a highly optimized hash map, dropping query latency from hundreds of milliseconds (or worse at scale) down to virtually1ms. - Preventing N+1 Query Problems: In endpoints that return complex relationships (like fetching a single book and all of its reviews), we actively use SQLAlchemy's
joinedload()(Eager Loading). Instead of Pydantic secretly triggering dozens of individual SQL queries behind the scenes while serializing the JSON response, we force SQLAlchemy to fetch the parent row and all child rows simultaneously in one single, highly-optimized SQLJOINquery. - Asynchronous Background Tasks: Heavy operations, such as calculating the "Auto-Restock" algorithm (
POST /requisitions/auto) for the entire catalog, are pushed to FastAPIBackgroundTasks. The API immediately returns a202 Acceptedresponse to the Admin, keeping the frontend snappy and preventing gateway timeouts, while the intensive database math is processed silently on a separate worker thread. - Memory Management (Pagination): All endpoints capable of returning unbounded lists of records (such as Book Catalogs, Sales Histories, and Requisition Reports) proactively enforce strict
skipandlimitpagination (defaulting to 50 records per page). This prevents the dreaded "Out of Memory" crash when pulling tens of thousands of rows out of PostgreSQL into the Python runtime. - Database Connection Pooling: The SQLAlchemy engine is tuned to handle High Availability scenarios. Instead of crashing PostgreSQL with "too many clients" during a traffic spike, the engine maintains a strict pool of
20persistent connections, with amax_overflowof10, and apool_timeout. This gracefully queues incoming requests during extreme load, ensuring the database stays upright. - API Rate Limiting (DDoS Protection): The application integrates
SlowAPIto actively defend against bot spam and DDoS attacks. Public endpoints (likeGET /books/) are strictly hard-capped at60 requests per minuteper IP address. If a user exceeds this limit, FastAPI automatically blocks them with a429 Too Many Requestserror, preserving server resources. - Response Caching (FastAPI-Cache): The highly-trafficked book catalog uses
fastapi-cache2. The backend executes the complex SQL queries for the book catalog once, and holds the JSON output in server RAM. For the next 60 seconds, any customer browsing the store receives an instant, pre-calculated response without the backend ever touching PostgreSQL. - Strict Data Sanitization: Pydantic
Fieldvalidations are aggressively enforced across all schemas (ge,le,min_length,max_length). This mathematically guarantees no blank strings, negative prices, or extreme cart quantities (like 1000 items) can bypass the API and corrupt the database. - HTTP-Only Cookies & CORS: To prevent Cross-Site Scripting (XSS) attacks, the authentication system was migrated from raw
Bearertokens to secure,HttpOnlySet-Cookies. JWT access tokens are safely managed by the browser. Because of this, the FastAPICORSMiddlewareinsrc/main.pyis strictly tuned to only allow requests from explicit frontend origins (e.g.http://localhost:5173) while rejecting wildcard requests.
To prevent testing against an empty database, we included an automated seeder script!
By running uv run python seed_db.py, the system:
- Validates and generates 3 permanent system Admin users.
- Iterates through 10 popular book genres.
- Rapidly calls the Google Books API to scrape 100+ real-world books, accurate authors, ISBNs, and HTTPS cover thumbnail images.
- Auto-assigns the inventory sequentially to the new Vendor Admins.
- Prerequisites: Ensure you have Python and
uvinstalled. - Environment Variables: Setup your database URL in the
.envfile (DATABASE_URL=postgresql://...). - Install Dependencies:
uv sync
- Start the Server:
uv run uvicorn src.main:app --reload
- View Documentation:
- Navigate to:
http://127.0.0.1:8000/docs. - You can login, authenticate, and test every single endpoint right from your browser!
- Navigate to: