A comprehensive library management system built with Python and FastAPI, featuring role-based access control, book management, loan tracking, and advanced analytics. This project demonstrates modern software development practices including RESTful API design, database integration, containerization, and security best practices.
This library management system is a full-featured application that allows different user roles (Members, Librarians, and Admins) to interact with a library's book inventory and loan system. The project was developed as the final assignment for the Fundamentals of Computer and Basic Programming course, implementing all core requirements plus several bonus features.
- β Role-Based Access Control - Three distinct user roles with appropriate permissions
- β Book Management - Add, edit, delete, and search books
- β Loan System - Request, approve, renew, and return books with status tracking
- β User Management - Registration, authentication, and user administration
- β Analytics Dashboard - Insights into popular books, reliable users, and overdue items
- β Secure Authentication - JWT-based authentication with password encryption
- β RESTful API - Modern API design with FastAPI
- β Database Integration - MongoDB for persistent data storage
- β Containerization - Docker support for easy deployment
- Framework: FastAPI (Python web framework)
- Database: MongoDB (NoSQL database)
- Authentication: JWT (JSON Web Tokens)
- Password Hashing: bcrypt
- Containerization: Docker & Docker Compose
- API Documentation: Automatic OpenAPI/Swagger docs
This project follows Domain Driven Design (DDD) principles, organizing the codebase around business domains and bounded contexts. The architecture is structured to reflect the core business domains of the library management system:
- Domain Separation: Each domain (admin, librarian, member, analytics, auth) is organized as a separate module with its own router and service layer
- Bounded Contexts: Clear boundaries between different business contexts (user management, book management, loan management)
- Domain Models: Business logic encapsulated in domain-specific models and services
- Layered Architecture: Clear separation between presentation layer (routers), business logic layer (services), and data access layer (database)
This architectural approach ensures:
- Maintainability: Easy to understand and modify domain-specific features
- Scalability: New domains can be added without affecting existing ones
- Testability: Each domain can be tested independently
- Business Alignment: Code structure mirrors the business domain model
university-basic-programming-python/
βββ app/
β βββ core/ # Core configuration and utilities
β β βββ config.py # Application settings
β β βββ jwt.py # JWT token management
β β βββ mongo_base.py # MongoDB base model
β βββ db/ # Database configuration
β β βββ mongo.py # MongoDB connection
β β βββ seed.py # Database seeding script
β βββ models/ # Business logic and routes
β β βββ admin/ # Admin endpoints
β β β βββ router.py # Admin API routes
β β β βββ services.py # Admin business logic
β β βββ analytics/ # Analytics endpoints
β β β βββ router.py # Analytics API routes
β β β βββ services.py # Analytics business logic
β β βββ auth/ # Authentication endpoints
β β β βββ router.py # Auth API routes
β β β βββ services.py # Auth business logic
β β βββ librarian/ # Librarian endpoints
β β β βββ router.py # Librarian API routes
β β β βββ services.py # Librarian business logic
β β βββ member/ # Member endpoints
β β βββ router.py # Member API routes
β β βββ services.py # Member business logic
β βββ schema/ # Pydantic models
β β βββ book.py # Book schemas
β β βββ loan.py # Loan schemas
β β βββ user.py # User schemas
β βββ utils/ # Utility functions
β βββ days_left.py # Date calculations
β βββ hasher.py # Password hashing
β βββ object_id.py # Object ID utilities
βββ tests/ # Test suite
β βββ __init__.py # Package initialization
β βββ conftest.py # Pytest configuration and fixtures
β βββ test_admin.py # Admin functionality tests
β βββ test_analytics.py # Analytics endpoint tests
β βββ test_auth.py # Authentication tests
β βββ test_experimental.py # Experimental tests
β βββ test_librarian.py # Librarian functionality tests
β βββ test_member.py # Member functionality tests
βββ main.py # Application entry point
βββ requirements.txt # Python dependencies
βββ pytest.ini # Pytest configuration
βββ Dockerfile # Docker image configuration
βββ docker-compose.yml # Docker Compose configuration
βββ logo.png # University logo
βββ README.md # This file
- Search for books
- Request book loans
- View personal loan history
- Request loan renewal
- Request book return
- All Member permissions, plus:
- View and manage all loan requests
- Approve/reject loan requests
- Approve/reject return and renewal requests
- Add new books to the library
- Edit existing book information
- Delete books from the system
- All Librarian permissions, plus:
- Register new users
- Delete or disable user accounts
- Access analytics dashboard
- Python 3.9 or higher
- MongoDB (or use Docker Compose)
- Docker & Docker Compose (optional, for containerized setup)
-
Clone the repository
git clone <repository-url> cd university-basic-programming-python
-
Create a virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Set up environment variables
Create a
.envfile in the root directory:MONGO_HOST=localhost MONGO_PORT=27017 MONGO_DB=appdb MONGO_USER=admin MONGO_PASSWORD=adminpassword MONGO_AUTH_DB=admin JWT_SECRET=your-secret-key-change-in-production
-
Start MongoDB
Make sure MongoDB is running on your system, or use Docker Compose:
docker-compose up -d mongo
-
Seed the database (optional)
python -m app.db.seed
-
Run the application
uvicorn main:app --reload
The API will be available at
http://localhost:8000
-
Clone the repository
git clone <repository-url> cd university-basic-programming-python
-
Create
.envfile (same as above) -
Start services with Docker Compose
docker-compose up -d
This will start both MongoDB and the application.
Once the application is running, you can access:
- Interactive API Docs (Swagger UI):
http://localhost:8000/docs - Alternative API Docs (ReDoc):
http://localhost:8000/redoc - OpenAPI Schema:
http://localhost:8000/openapi.json
POST /auth/login- User loginPOST /auth/register- Register new user (Admin only)
GET /member/s/{query}- Search booksGET /member/loan- Get personal loan listPOST /member/loan- Request a book loanPOST /member/loan/{loan_id}/return- Request book return
GET /librarian/loan- View all loan requestsPUT /librarian/loan/{id}/accept- Approve loan requestPUT /librarian/loan/{id}/reject- Reject loan requestPUT /librarian/loan/{id}/returned- Confirm book returnPOST /librarian/book- Add new bookPUT /librarian/book/{id}- Update book informationDELETE /librarian/book/{id}- Delete book
POST /admin/user- Register new userDELETE /admin/user/{username}- Delete userPUT /admin/user/{username}/disable- Disable user accountPUT /admin/user/{username}/enable- Enable user account
GET /analytics/popular-books- Get most popular booksGET /analytics/reliable-users- Get most reliable usersGET /analytics/overdue-books- Get overdue books list
The API uses JWT (JSON Web Tokens) for authentication. To access protected endpoints:
-
Login to get an access token:
curl -X POST "http://localhost:8000/auth/login" \ -H "Content-Type: application/json" \ -d '{"username": "member", "password": "123"}'
-
Use the token in subsequent requests:
curl -X GET "http://localhost:8000/member/loan" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
After seeding the database, you can use these test accounts:
- Admin:
username: amir,password: 123 - Librarian:
username: librarian,password: 123 - Member:
username: member,password: 123
{
"username": "string",
"password": "string (hashed)",
"full_name": "string",
"role": "admin | librarian | member",
"score": "integer (default: 0)",
"disabled_at": "datetime | null"
}{
"title": "string",
"author": "string",
"category": "string",
"total_count": "integer",
"aviable_count": "integer"
}{
"username": "string",
"book_title": "string",
"date": "datetime",
"status": "pending | approved | returned_awaiting | returned | renew_pending | rejected",
"returned_date": "datetime | null"
}This project goes beyond the basic requirements and includes several advanced features:
- Modern document-based database instead of file-based storage
- Efficient querying and data relationships
- Scalable architecture
- bcrypt hashing for secure password storage
- Industry-standard security practices
- No plain-text passwords in database
- Complete Docker setup with Dockerfile and docker-compose.yml
- Easy deployment across different environments
- Isolated development and production environments
- Popular Books: Track most borrowed books
- Reliable Users: Identify users with good borrowing history
- Overdue Books: Monitor books that are past due date
- Modern API design instead of CLI interface
- Automatic API documentation
- Type validation with Pydantic
- Async/await support for better performance
- Proper Git repository structure
- Organized commit history
- Ready for GitHub deployment
Login as Member:
curl -X POST "http://localhost:8000/auth/login" \
-H "Content-Type: application/json" \
-d '{"username": "member", "password": "123"}'Search for Books:
curl -X GET "http://localhost:8000/member/s/clean" \
-H "Authorization: Bearer YOUR_TOKEN"Request a Loan:
curl -X POST "http://localhost:8000/member/loan" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"book_id": "BOOK_ID", "date": "2024-01-15T10:00:00Z"}'The easiest way to test the API is through the Swagger UI at http://localhost:8000/docs. You can:
- View all available endpoints
- See request/response schemas
- Test endpoints directly from the browser
- Authenticate using the "Authorize" button
The project follows Python best practices:
- Modular Design: Separated concerns with routers, services, and schemas
- Type Hints: Full type annotations for better code clarity
- Pydantic Models: Data validation and serialization
- Clean Architecture: Separation of business logic and API routes
- Domain Driven Design (DDD): Architecture organized around business domains with clear bounded contexts
- Dependency Injection: FastAPI's dependency system for authentication
- Repository Pattern: Database operations abstracted in service layer
- Schema Validation: Pydantic models for request/response validation
This project includes comprehensive test coverage using Pytest and GitHub Actions CI/CD.
-
Install test dependencies (if not already installed):
pip install -r requirements.txt
-
Ensure MongoDB is running:
docker-compose up -d mongo
-
Set environment variables for testing:
export MONGO_URI="mongodb://localhost:27017" export JWT_SECRET="test_secret_key"
-
Run all tests:
pytest tests/ -v
-
Run specific test file:
pytest tests/test_auth.py -v
-
Run with coverage:
pip install pytest-cov pytest tests/ --cov=app --cov-report=html
The test suite is organized by domain:
tests/test_auth.py- Authentication and authorization teststests/test_member.py- Member role functionality teststests/test_librarian.py- Librarian role functionality teststests/test_admin.py- Admin role functionality teststests/test_analytics.py- Analytics endpoint teststests/conftest.py- Shared fixtures and test configuration
The project uses GitHub Actions for automated testing:
- Workflow:
.github/workflows/ci.yml - Triggers: Runs on push and pull requests to main/master/develop branches
- Services: Automatically sets up MongoDB service container
- Test Execution: Runs full test suite with coverage reporting
- Status Badge: View test status directly in repository
The CI pipeline:
- Sets up Python 3.9 environment
- Installs dependencies
- Starts MongoDB service container
- Runs all tests with pytest
- Generates coverage reports
- Uploads coverage to Codecov (optional)
The test suite covers:
- β Authentication and JWT token validation
- β Role-based access control
- β Book management operations
- β Loan request and approval workflows
- β User management (admin functions)
- β Analytics endpoints
- β Error handling and edge cases
- User management with three roles (Admin, Librarian, Member)
- Book management (add, edit, delete, search)
- Loan system (request, approve, renew, return)
- Status tracking for loans
- Data persistence (MongoDB)
- Authentication and authorization
- NoSQL Database (MongoDB)
- Password Encryption (bcrypt)
- Docker Containerization
- Analytics System
- RESTful API (FastAPI)
- Version Control (Git)
- Testing with Pytest
- CI/CD with GitHub Actions
This project is developed as part of a university course assignment. All rights reserved.
- University of Tehran for the project
- FastAPI community for excellent documentation
- MongoDB for the robust database solution
Note: This project was developed as a learning exercise. For production use, additional security measures, error handling, and testing would be recommended.
