LouisFernando1204/fastbook-backend
FastBook Backend is my comprehensive project for mastering Python FastAPI development, built with PostgreSQL, Redis, and Celery. It's a modern backend service for a book review platform, featuring a robust async architecture with JWT authentication, email verification, and role-based access control.
FastBook: A RESTful Book Management API ๐โก
โจ Overview
Welcome to FastBook, a robust REST API designed for managing a modern book collection and review system. Built with Python, FastAPI, and PostgreSQL, this backend service provides a fast, scalable, and efficient foundation for a book management application. It follows modern API design principles with comprehensive authentication, asynchronous operations, and clean separation of concerns, making it highly maintainable and performant.
๐ Key Features
- ๐ JWT Authentication โ Secure endpoints using JSON Web Tokens (JWT) with refresh token support, ensuring that only authenticated users can access protected resources.
- ๐๏ธ Clean Architecture โ Organized into distinct layers (Routes, Services, Models) for a clear separation of concerns, making the codebase easy to understand, test, and scale.
- ๐ฆ Full CRUD Operations โ Comprehensive Create, Read, Update, and Delete functionality for all core entities:
- Users: Complete user management with secure password hashing, email verification, and role-based access control.
- Books: Manage book catalog with detailed information and user associations.
- Reviews: Allow users to rate and review books with comment functionality.
- Tags: Organize books with tagging system for better categorization.
- ๐ง Email System โ Integrated email functionality with Celery background tasks for:
- Account verification emails
- Password reset notifications
- Welcome messages
- ๐ Background Tasks โ Asynchronous email processing using Celery and Redis for improved performance.
- ๐ก๏ธ Request Validation โ Built-in validation using Pydantic models to ensure data integrity and type safety.
- ๐ PostgreSQL Integration โ Utilizes PostgreSQL with SQLModel (SQLAlchemy) for robust and reliable async data storage.
- ๐ High Performance โ Built on FastAPI for automatic API documentation, async support, and blazing-fast performance.
- ๐ Token Blacklisting โ Redis-based token blacklisting for secure logout functionality.
- ๐ Database Migrations โ Alembic integration for database schema versioning and migrations.
- โ๏ธ Centralized Configuration โ Manages all environment-specific settings securely through environment variables.
๐งโ๐ป How It Works
- User registers by sending their details to the
/signupendpoint and receives an email verification link. - User verifies email by clicking the verification link and can then authenticate via
/loginto receive JWT tokens. - The client includes the JWT as a Bearer Token in the
Authorizationheader for all subsequent requests to protected endpoints. - JWT Middleware intercepts and validates tokens, checking against Redis blacklist for revoked tokens.
- The Routes layer receives requests, validates data using Pydantic schemas, and calls appropriate Service layer methods.
- The Service layer executes core business logic, handles exceptions, and coordinates with the Models layer.
- The Models layer manages database interactions using SQLModel and async SQLAlchemy sessions.
- Background tasks handle email sending asynchronously via Celery workers.
- A structured JSON response with comprehensive error handling is returned to the client.
โ๏ธ Tech Stack
- ๐ Python 3.12+
- โก FastAPI (Modern Web Framework)
- ๐ PostgreSQL (Database)
- ๐ SQLModel (ORM with SQLAlchemy)
- ๐ python-jose (JWT Implementation)
- ๐ก๏ธ passlib (Password Hashing with bcrypt)
- โ Pydantic (Data Validation)
- ๐ง fastapi-mail (Email Integration)
- ๐ Celery (Background Task Processing)
- ๐๏ธ Redis (Token Blacklisting & Celery Broker)
- ๐๏ธ Alembic (Database Migrations)
- ๐งช pytest (Testing Framework)
๐ FastBook Insights
- ๐ Python Backend : View Code
๐ Getting Started
Follow these steps to get FastBook up and running on your local machine.
Prerequisites
- Python (version 3.12 or higher)
- PostgreSQL
- Redis (for token blacklisting and Celery)
- A tool to interact with your database (e.g., TablePlus, DBeaver, or pgAdmin)
Installation & Setup
-
Clone the repository:
git clone https://github.com/LouisFernando1204/fastbook-backend.git cd fastbook-backend -
Create and activate virtual environment:
python -m venv env source env/bin/activate # On Windows: env\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt
-
Set up environment variables:
- Create a
.envfile in the root directory. - Add the following configuration variables:
# Database Configuration DATABASE_URL="postgresql+asyncpg://username@localhost:5432/fastblog_db" # JWT Configuration JWT_SECRET="your_super_secret_jwt_key_here" JWT_ALGORITHM="HS256" # Redis Configuration REDIS_HORT="localhost" REDIS_PORT=6379 REDIS_URL="redis://localhost:6379/0" # Email Configuration MAIL_USERNAME=your_email@gmail.com MAIL_PASSWORD=your_app_password MAIL_SERVER=smtp.gmail.com MAIL_PORT=587 MAIL_FROM=your_email@gmail.com MAIL_FROM_NAME=FastBook Backend # Application Configuration DOMAIN=localhost:8000 # PostgreSQL Configuration (Optional) POSTGRES_USER= POSTGRES_PASSWORD= POSTGRES_DB=
- Create a
-
Set up the database:
- Start your PostgreSQL server.
- Create a new database named
fastbook_db(or as specified in your DATABASE_URL). - Run database migrations:
alembic upgrade head
-
Start Redis server:
redis-server
-
Start Celery worker (in a separate terminal):
celery -A src.celery_tasks worker --loglevel=info
-
Run the application:
fastapi dev src/
The server should now be running on
http://localhost:8000. -
Access API Documentation:
- Swagger UI:
http://localhost:8000/api/v1/docs - ReDoc:
http://localhost:8000/api/v1/redoc
- Swagger UI:
๐ API Endpoints
Authentication
POST /api/v1/auth/signup- Register new userPOST /api/v1/auth/login- User loginGET /api/v1/auth/verify/{token}- Verify emailPOST /api/v1/auth/refresh-token- Refresh access tokenPOST /api/v1/auth/logout- User logoutGET /api/v1/auth/me- Get current user profilePOST /api/v1/auth/password-reset-request- Request password resetPOST /api/v1/auth/password-reset-confirm/{token}- Confirm password reset
Books Management
GET /api/v1/books/- Get all booksPOST /api/v1/books/- Create new bookGET /api/v1/books/{book_uid}- Get book by IDPATCH /api/v1/books/{book_uid}- Update bookDELETE /api/v1/books/{book_uid}- Delete book
Reviews
POST /api/v1/books/{book_uid}/reviews- Add review to bookDELETE /api/v1/books/{book_uid}/reviews/{review_uid}- Delete review
Tags
GET /api/v1/tags/- Get all tagsPOST /api/v1/tags/- Create new tagPOST /api/v1/books/{book_uid}/tags- Add tags to bookDELETE /api/v1/books/{book_uid}/tags/{tag_uid}- Remove tag from book
๐งช Running Tests
pytest src/tests/ -v๐ค Contributor
- ๐งโ๐ป Louis Fernando : @LouisFernando1204