This document provides comprehensive API documentation for the College Library Management System, including Firestore database schema, REST API endpoints, Telegram bot commands, and data models.
library-management/
├── users/ # User profiles and authentication
├── books/ # Book catalog and metadata
├── requests/ # Book borrowing requests
├── notifications/ # System notifications
├── settings/ # System configuration
├── analytics/ # Usage analytics and reports
└── sessions/ # Active user sessions
Collection Path: /users/{userId}
interface User {
id: string; // Firebase Auth UID
email?: string; // Email (for staff)
telegramId?: string; // Telegram user ID (for students)
profile: {
firstName: string;
lastName: string;
studentId?: string; // Student ID number
employeeId?: string; // Staff employee ID
department: string;
phone?: string;
avatar?: string; // Profile picture URL
};
role: 'student' | 'librarian' | 'admin';
status: 'active' | 'suspended' | 'inactive';
preferences: {
notifications: {
dueDateReminders: boolean;
requestUpdates: boolean;
announcements: boolean;
};
language: string; // Default: 'en'
};
statistics: {
totalRequests: number;
approvedRequests: number;
currentLoans: number;
overdueBooks: number;
totalFines: number;
};
createdAt: Timestamp;
updatedAt: Timestamp;
lastLoginAt?: Timestamp;
}Collection Path: /books/{bookId}
interface Book {
id: string; // Auto-generated book ID
isbn: string; // ISBN-10 or ISBN-13
title: string;
subtitle?: string;
authors: string[]; // Array of author names
publisher: string;
publishedDate: string; // ISO date string
edition?: string;
language: string; // Default: 'en'
pages?: number;
categories: string[]; // Subject categories
description?: string;
coverImage?: string; // Cover image URL
availability: {
totalCopies: number;
availableCopies: number;
reservedCopies: number;
status: 'available' | 'limited' | 'unavailable';
};
location: {
section: string; // Library section
shelf: string; // Shelf identifier
callNumber: string; // Library call number
};
metadata: {
addedBy: string; // User ID who added the book
addedAt: Timestamp;
updatedBy?: string;
updatedAt?: Timestamp;
};
statistics: {
totalRequests: number;
currentLoans: number;
averageRating?: number;
reviewCount: number;
};
}Collection Path: /requests/{requestId}
interface BookRequest {
id: string; // Auto-generated request ID
userId: string; // Requesting user ID
bookId: string; // Requested book ID
status: 'pending' | 'approved' | 'rejected' | 'borrowed' | 'returned' | 'overdue';
type: 'borrow' | 'reserve';
requestDate: Timestamp;
approvedDate?: Timestamp;
borrowDate?: Timestamp;
dueDate?: Timestamp;
returnDate?: Timestamp;
approvedBy?: string; // Librarian user ID
notes?: string; // Additional notes
qrCode?: string; // QR code for validation
fine?: {
amount: number;
reason: string;
paidAt?: Timestamp;
paidAmount?: number;
};
timeline: RequestTimelineEntry[]; // Status change history
}
interface RequestTimelineEntry {
status: string;
timestamp: Timestamp;
userId: string; // User who made the change
notes?: string;
}Collection Path: /notifications/{notificationId}
interface Notification {
id: string;
userId: string; // Target user ID
type: 'due_reminder' | 'request_update' | 'announcement' | 'fine_notice';
title: string;
message: string;
data?: Record<string, any>; // Additional notification data
status: 'pending' | 'sent' | 'failed';
channels: ('telegram' | 'email' | 'web')[];
scheduledAt?: Timestamp; // For scheduled notifications
sentAt?: Timestamp;
readAt?: Timestamp;
createdAt: Timestamp;
}- Development:
https://us-central1-library-dev.cloudfunctions.net/api - Production:
https://us-central1-library-prod.cloudfunctions.net/api
Login with email and password (staff only)
Request Body:
{
"email": "librarian@college.edu",
"password": "securePassword123"
}Response:
{
"success": true,
"data": {
"user": {
"id": "user123",
"email": "librarian@college.edu",
"role": "librarian",
"profile": { ... }
},
"token": "eyJhbGciOiJIUzI1NiIs...",
"expiresIn": 3600
}
}Authenticate Telegram user
Request Body:
{
"telegramId": "123456789",
"firstName": "John",
"lastName": "Doe",
"username": "johndoe"
}Get all users (admin/librarian only)
Query Parameters:
role: Filter by user rolestatus: Filter by user statuslimit: Number of results (default: 50)offset: Pagination offset
Response:
{
"success": true,
"data": {
"users": [...],
"total": 150,
"hasMore": true
}
}Get user by ID
Update user profile
Deactivate user (admin only)
Search and list books
Query Parameters:
q: Search query (title, author, ISBN)category: Filter by categoryavailability: Filter by availability statuslimit: Number of results (default: 20)offset: Pagination offset
Response:
{
"success": true,
"data": {
"books": [
{
"id": "book123",
"title": "Introduction to Computer Science",
"authors": ["John Smith", "Jane Doe"],
"isbn": "978-0123456789",
"availability": {
"totalCopies": 5,
"availableCopies": 3,
"status": "available"
}
}
],
"total": 1250,
"hasMore": true
}
}Add new book (librarian/admin only)
Request Body:
{
"isbn": "978-0123456789",
"title": "Introduction to Computer Science",
"authors": ["John Smith", "Jane Doe"],
"publisher": "Tech Publications",
"publishedDate": "2023-01-15",
"categories": ["Computer Science", "Programming"],
"totalCopies": 5,
"location": {
"section": "CS",
"shelf": "A1",
"callNumber": "004.1 SMI"
}
}Update book information
Remove book from catalog
Get book requests
Query Parameters:
userId: Filter by user IDstatus: Filter by request statusbookId: Filter by book IDlimit: Number of resultsoffset: Pagination offset
Submit book request
Request Body:
{
"bookId": "book123",
"type": "borrow",
"notes": "Needed for research project"
}Approve book request (librarian/admin only)
Request Body:
{
"dueDate": "2024-02-15T00:00:00Z",
"notes": "Approved for 2 weeks"
}Reject book request
Mark book as returned
Get dashboard analytics (librarian/admin only)
Response:
{
"success": true,
"data": {
"summary": {
"totalBooks": 5000,
"totalUsers": 1200,
"activeRequests": 45,
"overdueBooks": 12
},
"trends": {
"dailyRequests": [...],
"popularBooks": [...],
"userActivity": [...]
}
}
}Initialize bot and register user
- Usage:
/start - Response: Welcome message and registration prompt
Search for books
- Usage:
/search <query> - Example:
/search python programming - Response: List of matching books with availability
Request a book
- Usage:
/request <book_id> - Example:
/request book123 - Response: Confirmation of request submission
Check request status
- Usage:
/status - Response: List of current requests with status
View borrowing history
- Usage:
/history - Response: Past borrowing records
View/edit user profile
- Usage:
/profile - Response: Current profile information with edit options
Show available commands
- Usage:
/help - Response: List of all available commands
View system statistics (admin only)
- Usage:
/admin_stats - Response: System usage statistics
Send announcement to all users (admin only)
- Usage:
/admin_broadcast <message> - Response: Confirmation of broadcast
All API responses follow this standard format:
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: {
code: string;
message: string;
details?: any;
};
meta?: {
timestamp: string;
requestId: string;
version: string;
};
}interface PaginatedResponse<T> {
items: T[];
total: number;
limit: number;
offset: number;
hasMore: boolean;
}interface SearchResult<T> {
items: T[];
total: number;
query: string;
filters: Record<string, any>;
suggestions?: string[];
}interface JWTPayload {
sub: string; // User ID
email?: string; // User email
role: string; // User role
iat: number; // Issued at
exp: number; // Expires at
aud: string; // Audience
iss: string; // Issuer
}All authenticated requests must include:
Authorization: Bearer <jwt_token>
- Student: Can view books, submit requests, view own data
- Librarian: Student permissions + manage requests, view all users
- Admin: All permissions + system configuration, user management
200- Success201- Created400- Bad Request401- Unauthorized403- Forbidden404- Not Found409- Conflict422- Validation Error429- Rate Limited500- Internal Server Error
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": {
"field": "email",
"reason": "Invalid email format"
}
}
}INVALID_TOKEN- Authentication token is invalidINSUFFICIENT_PERMISSIONS- User lacks required permissionsRESOURCE_NOT_FOUND- Requested resource doesn't existVALIDATION_ERROR- Input validation failedRATE_LIMITED- Too many requestsBOOK_UNAVAILABLE- Book is not available for borrowingREQUEST_ALREADY_EXISTS- User already has pending request for book
- General: 100 requests per minute per user
- Search: 30 requests per minute per user
- Authentication: 10 requests per minute per IP
- Commands: 20 commands per minute per user
- Messages: 50 messages per minute per user
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200
Endpoint: https://your-domain.com/webhook/telegram
Method: POST
Content-Type: application/json
All webhook requests are validated using:
- HMAC-SHA256 signature verification
- Timestamp validation (within 5 minutes)
- IP whitelist verification
import { LibraryAPI } from '@library/sdk';
const api = new LibraryAPI({
baseURL: 'https://api.library.edu',
apiKey: 'your-api-key'
});
// Search books
const books = await api.books.search({
query: 'javascript',
limit: 10
});
// Submit request
const request = await api.requests.create({
bookId: 'book123',
type: 'borrow'
});from library_sdk import LibraryClient
client = LibraryClient(
base_url='https://api.library.edu',
api_key='your-api-key'
)
# Search books
books = client.books.search(
query='python',
limit=10
)
# Submit request
request = client.requests.create(
book_id='book123',
type='borrow'
)Document Version: 1.0 Last Updated: [Current Date] Prepared By: API Development Team Reviewed By: [To be filled]