A comprehensive RESTful API for managing university library operations including books, users, borrowings, reservations, and analytics. Built with Node.js, Express, and MongoDB.
- Features
- Technology Stack
- Project Structure
- Installation
- Configuration
- API Endpoints
- Security Features
- Rate Limiting
- Authentication
- Testing
- API Documentation
- Book Management: CRUD operations for library books with categories, search, and filtering
- User Management: User registration, authentication, profile management
- Borrowing System: Borrow and return books with automatic due date tracking
- Reservation System: Reserve books that are currently unavailable
- Fine Management: Automatic fine calculation for overdue books
- Analytics Dashboard: Library statistics and usage reports (admin only)
- JWT-based authentication
- Password hashing with bcrypt
- Request rate limiting
- Input sanitization (NoSQL injection prevention)
- XSS protection
- HTTP Parameter Pollution prevention
- Security headers (Helmet)
- CORS configuration
| Technology | Purpose |
|---|---|
| Node.js | Runtime environment |
| Express.js | Web framework |
| MongoDB | Database |
| Mongoose | ODM for MongoDB |
| JWT | Authentication tokens |
| bcryptjs | Password hashing |
| Helmet | Security headers |
| express-rate-limit | Rate limiting |
| express-mongo-sanitize | NoSQL injection prevention |
| xss-clean | XSS attack prevention |
| hpp | HTTP Parameter Pollution prevention |
| Swagger UI | API documentation |
| Jest | Testing framework |
university-library-restful-api/
βββ app.js # Express app configuration
βββ server.js # Server entry point
βββ package.json # Dependencies and scripts
βββ swagger.json # API documentation
βββ .env # Environment variables
βββ config/
β βββ config.js # Configuration loader
β βββ config.json # Environment-specific configs
βββ middleware/
β βββ auth.js # Authentication middleware
β βββ rateLimiter.js # Rate limiting configurations
β βββ security.js # Security middleware
βββ models/
β βββ book.js # Book model
β βββ user.js # User model
β βββ borrowing.js # Borrowing model
β βββ reservation.js # Reservation model
βββ routes/
β βββ bookRoutes.js # Book endpoints
β βββ userRoutes.js # User endpoints
β βββ borrowingRoutes.js # Borrowing endpoints
β βββ reservationRoutes.js # Reservation endpoints
β βββ analyticRoutes.js # Analytics endpoints
βββ emails/
β βββ account.js # Email templates
βββ tests/
βββ app.test.js # Test suite
- Node.js (v14 or higher)
- MongoDB (v4.4 or higher)
- npm or yarn
-
Clone the repository
git clone <repository-url> cd university-library-restful-api
-
Install dependencies
npm install
-
Configure environment variables
cp .env.example .env # Edit .env with your configuration -
Start MongoDB
# Using MongoDB locally mongod # Or using Docker docker run -d -p 27017:27017 --name mongodb mongo
-
Start the server
# Development mode (with hot reload) npm run dev # Production mode npm start
-
Access the API
- API: http://localhost:3000
- Documentation: http://localhost:3000/api-docs
Create a .env file in the root directory:
# Server Configuration
PORT=3000
NODE_ENV=development
# Database
MONGODB_URL=mongodb://localhost:27017/library
# JWT Configuration
JWT_SECRET=your_secure_jwt_secret_change_in_production
JWT_EXPIRY=7d
# Fine Configuration
FINE_RATE_PER_DAY=1
# CORS
CORS_ORIGIN=*
# Email Configuration (optional)
EMAIL_SERVICE=gmail
EMAIL_USER=your-email@example.com
EMAIL_PASSWORD=your-app-password| Method | Endpoint | Description | Auth |
|---|---|---|---|
| GET | /api/books |
Get all books | Public |
| GET | /api/books/:id |
Get book by ID | Public |
| POST | /api/books |
Create a new book | Admin |
| PATCH | /api/books/:id |
Update a book | Admin |
| DELETE | /api/books/:id |
Delete a book | Admin |
Query Parameters for GET /api/books:
category- Filter by categorystatus- Filter by status (Available, Borrowed, etc.)search- Full-text searchsortBy- Sort by field (e.g.,title:asc,author:desc)limit- Number of results (default: 10)skip- Pagination offset
| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /api/users |
Register new user | Public |
| POST | /api/users/login |
User login | Public |
| POST | /api/users/logout |
Logout current session | Required |
| POST | /api/users/logoutAll |
Logout all sessions | Required |
| GET | /api/users/me |
Get current user profile | Required |
| PATCH | /api/users/me |
Update user profile | Required |
| POST | /api/users/password-reset |
Request password reset | Public |
| POST | /api/users/pay-fines |
Pay outstanding fines | Required |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /api/borrowings |
Borrow a book | Required |
| GET | /api/borrowings/me |
Get user's borrowings | Required |
| GET | /api/borrowings/:id |
Get borrowing details | Required |
| PATCH | /api/borrowings/:id/return |
Return a book | Required |
| PATCH | /api/borrowings/:id/renew |
Renew a borrowing | Required |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
| POST | /api/reservations |
Create a reservation | Required |
| GET | /api/reservations/me |
Get user's reservations | Required |
| GET | /api/reservations/:id |
Get reservation details | Required |
| PATCH | /api/reservations/:id/cancel |
Cancel a reservation | Required |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
| GET | /api/analytics/stats |
Get library statistics | Admin |
| GET | /api/analytics/popular-books |
Get most borrowed books | Admin |
| GET | /api/analytics/borrowing-trends |
Get borrowing trends | Admin |
| GET | /api/analytics/category-distribution |
Get category distribution | Admin |
| GET | /api/analytics/top-fines |
Get users with highest fines | Admin |
- JWT Tokens: Secure token-based authentication
- Password Hashing: bcrypt with salt rounds for secure password storage
- Session Management: Support for multiple device sessions with logout functionality
- Helmet: Sets various HTTP headers for security
- CORS: Configurable Cross-Origin Resource Sharing
- Input Sanitization: Prevents NoSQL injection attacks
- XSS Protection: Sanitizes user input to prevent cross-site scripting
- HPP Protection: Prevents HTTP Parameter Pollution attacks
- Request body size limits (10KB)
- Content-Type validation
- Input validation on all models
- Whitelist-based update operations
The API implements multiple rate limiters to prevent abuse:
| Limiter | Window | Max Requests | Applied To |
|---|---|---|---|
| API General | 15 min | 100 | All /api routes |
| Authentication | 1 hour | 10 | Login endpoint |
| Password Reset | 1 hour | 3 | Password reset endpoint |
| Resource Creation | 1 hour | 50 | POST endpoints |
When rate limited, the API returns:
{
"error": "Too many requests from this IP, please try again after 15 minutes"
}curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "john@example.com",
"password": "password123",
"role": "student",
"department": "Computer Science"
}'curl -X POST http://localhost:3000/api/users/login \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "password123"
}'Include the JWT token in the Authorization header:
curl -X GET http://localhost:3000/api/users/me \
-H "Authorization: Bearer <your-jwt-token>"- student: Basic user, can borrow and reserve books
- faculty: Same as student with extended borrowing periods
- librarian: Can manage books and view user borrowings
- admin: Full access including analytics and user management
Run the test suite:
npm testRun tests with coverage:
npm test -- --coverageInteractive API documentation is available at:
http://localhost:3000/api-docs
The documentation uses Swagger UI and provides:
- Complete endpoint listing
- Request/response schemas
- Try-it-out functionality
- Authentication testing
The API uses standard HTTP status codes:
| Code | Description |
|---|---|
| 200 | Success |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 409 | Conflict (duplicate) |
| 415 | Unsupported Media Type |
| 429 | Too Many Requests |
| 500 | Internal Server Error |
Error response format:
{
"error": "Error message description"
}The API provides a health check endpoint:
curl http://localhost:3000/healthResponse:
{
"status": "healthy",
"timestamp": "2024-01-01T00:00:00.000Z",
"uptime": 3600
}- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the ISC License.
For support, please open an issue in the repository or contact the maintainers.