A comprehensive REST API for restaurant deal booking and management system built with Node.js, Express, and MongoDB.
- Features
- Tech Stack
- Quick Start
- API Endpoints
- Authentication
- Core Features
- ML Integration
- Database Schema
- Environment Setup
- Testing
- Deployment
- Contributing
- Restaurant Deal Creation - POST /deals
- Nearby Deals Search - GET /deals/nearby?lat=x&lng=y (geolocation-based)
- Deal Booking - POST /book/:dealId
- ML Discount Suggestions - Hardcoded logic with future ML integration plan
- User Authentication & Authorization - JWT-based with role management
- Admin Dashboard - User management and analytics
- Real-time Deal Availability - Automatic capacity management
- Booking Lifecycle Management - Status tracking (pending → confirmed → completed)
- Geolocation Services - Radius-based deal discovery
- Advanced Analytics - Business insights and user statistics
- Rate Limiting - API abuse prevention
- Data Validation - Comprehensive input validation
- Backend: Node.js, Express.js
- Database: MongoDB with Mongoose ODM
- Authentication: JWT (JSON Web Tokens)
- Security: Helmet, CORS, Rate Limiting, Data Sanitization
- Validation: Custom middleware with comprehensive error handling
- Documentation: Swagger/OpenAPI (planned)
- Testing: Jest (planned)
- Node.js (v16+)
- MongoDB (v4.4+)
- npm or yarn
# Clone the repository
git clone <repository-url>
cd restaurant-booking-api
# Install dependencies
npm install
# Setup environment variables
cp .env.example .env
# Edit .env with your configuration
# Start MongoDB (if local)
mongod
# Seed the database with sample data
npm run seed
# Start the development server
npm run dev# Server Configuration
NODE_ENV=development
PORT=5000
# Database
MONGODB_URI=mongodb://localhost:27017/restaurant-booking
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=7d
# Security
BCRYPT_SALT_ROUNDS=12
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW_MS=900000
# CORS
CORS_ORIGIN=*The API uses JWT (JSON Web Tokens) for authentication with role-based access control.
- User - Regular customers (can book deals, manage own bookings)
- Admin - System administrators (user management, analytics, all operations)
Admin Account:
Email: admin@restaurant.com
Password: Admin@123
Regular Users:
Email: john.doe@example.com
Password: Test@123
Email: jane.smith@example.com
Password: Test@123
POST /api/v1/auth/register # Register new user
POST /api/v1/auth/login # User login
POST /api/v1/auth/logout # User logout
GET /api/v1/auth/me # Get current user
PUT /api/v1/auth/me # Update profile
PUT /api/v1/auth/change-password # Change password
GET /api/v1/deals # Get all deals
GET /api/v1/deals/nearby # Get nearby deals ⭐ CORE
POST /api/v1/deals # Create deal ⭐ CORE
GET /api/v1/deals/:id # Get single deal
PUT /api/v1/deals/:id # Update deal
DELETE /api/v1/deals/:id # Delete deal
GET /api/v1/deals/:id/ml-suggestion # ML discount suggestion ⭐ CORE
GET /api/v1/deals/stats/overview # Deal statistics
POST /api/v1/bookings/:dealId # Book a deal ⭐ CORE
GET /api/v1/bookings/my-bookings # User's bookings
GET /api/v1/bookings # All bookings (admin)
GET /api/v1/bookings/:id # Get booking details
PUT /api/v1/bookings/:id # Update booking
DELETE /api/v1/bookings/:id # Cancel booking
PUT /api/v1/bookings/:id/confirm # Confirm booking
PUT /api/v1/bookings/:id/complete # Complete booking
GET /api/v1/bookings/stats # Booking statistics
GET /api/v1/users/profile # Own profile
PUT /api/v1/users/profile # Update own profile
GET /api/v1/users/booking-history # Own booking history
GET /api/v1/users/booking-stats # Own statistics
GET /api/v1/users/preferences # User preferences
PUT /api/v1/users/preferences # Update preferences
# Admin Only Routes
GET /api/v1/users # All users (admin)
GET /api/v1/users/:id # User details (admin)
PUT /api/v1/users/:id # Update user (admin)
DELETE /api/v1/users/:id # Delete user (admin)
PUT /api/v1/users/:id/activate # Activate user (admin)
PUT /api/v1/users/:id/deactivate # Deactivate user (admin)
GET /api/v1/users/analytics # User analytics (admin)
Endpoint: GET /api/v1/deals/nearby?lat=31.5204&lng=74.3587&radius=10
// Example Response
{
"status": "success",
"message": "Nearby deals retrieved successfully",
"data": [
{
"_id": "...",
"restaurantName": "Pizza Palace",
"description": "20% off on all pizzas",
"discountPercentage": 20,
"originalPrice": 25,
"discountedPrice": 20,
"location": {
"type": "Point",
"coordinates": [74.3587, 31.5204]
},
"address": "123 Main Street, Lahore",
"validFrom": "2025-06-13T00:00:00.000Z",
"validUntil": "2025-06-20T23:59:59.000Z",
"maxBookings": 50,
"currentBookings": 15,
"isActive": true
}
],
"meta": {
"total": 5,
"page": 1,
"limit": 10,
"pages": 1
}
}Endpoint: POST /api/v1/deals
// Example Request
{
"restaurantName": "Burger House",
"description": "Buy 1 Get 1 Free on all burgers",
"discountPercentage": 50,
"originalPrice": 15,
"location": {
"type": "Point",
"coordinates": [74.3587, 31.5204]
},
"address": "456 Food Street, Lahore",
"validFrom": "2025-06-13T00:00:00.000Z",
"validUntil": "2025-06-20T23:59:59.000Z",
"maxBookings": 100
}Endpoint: POST /api/v1/bookings/:dealId
// Example Request
{
"bookingDate": "2025-06-15T19:00:00.000Z",
"numberOfPeople": 4,
"specialRequests": "Window seat preferred"
}
// Example Response
{
"status": "success",
"message": "Booking created successfully",
"data": {
"booking": {
"_id": "...",
"userId": "...",
"dealId": {
"restaurantName": "Burger House",
"discountPercentage": 50,
"address": "456 Food Street, Lahore"
},
"bookingDate": "2025-06-15T19:00:00.000Z",
"numberOfPeople": 4,
"priceAtBooking": 15,
"discountApplied": 50,
"finalAmount": 30,
"status": "pending",
"specialRequests": "Window seat preferred"
}
}
}The API includes hardcoded ML logic that analyzes:
- Time of day (off-peak vs peak hours)
- Day of week (weekend vs weekday)
- Current booking count (demand level)
- Utilization rate (capacity percentage)
- Off-peak hours (2-4pm) + low bookings → 20% discount
- Weekend evenings + high demand → 5% discount
- Weekday lunch + moderate bookings → 15% discount
- Low utilization (<30%) → 25% discount
- Near capacity (>80%) → No additional discount
// Planned External ML Service Integration
POST /ml-service/predict
{
"features": {
"time": "14:30",
"day_of_week": "Tuesday",
"current_bookings": 8,
"max_bookings": 50,
"weather": "sunny",
"local_events": ["concert_nearby"]
}
}
// Response
{
"suggested_discount": 22,
"confidence": 0.87,
"reasoning": "Low afternoon demand with good weather"
}Endpoint: GET /api/v1/deals/:id/ml-suggestion
{
name: String,
email: String (unique),
phone: String,
password: String (hashed),
role: ['user', 'admin'],
status: ['active', 'inactive'],
timestamps: true
}{
restaurantName: String,
description: String,
discountPercentage: Number,
originalPrice: Number,
location: GeoJSON Point,
address: String,
validFrom: Date,
validUntil: Date,
maxBookings: Number,
currentBookings: Number,
isActive: Boolean,
suggestedDiscount: Number,
lastMLUpdate: Date,
timestamps: true
}{
userId: ObjectId (ref: User),
dealId: ObjectId (ref: Deal),
bookingDate: Date,
numberOfPeople: Number,
priceAtBooking: Number,
discountApplied: Number,
finalAmount: Number,
status: ['pending', 'confirmed', 'completed', 'cancelled'],
specialRequests: String,
cancellationReason: String,
timestamps: true
}# Pagination
?page=1&limit=10
# Filtering
?status=active&discountPercentage[gte]=20
# Searching
?search=pizza
# Sorting
?sort=-createdAt,discountPercentage
# Field Selection
?fields=restaurantName,discountPercentage,address
# Geolocation
?lat=31.5204&lng=74.3587&radius=15
- General API: 100 requests per 15 minutes
- Auth Operations: 20 requests per hour
- Booking Operations: 50 requests per hour
- JWT Authentication with secure token handling
- Password Hashing using bcrypt
- Data Sanitization against NoSQL injection
- XSS Protection using xss-clean
- Helmet for security headers
- CORS configuration
- Rate Limiting per IP and per user
{
"status": "success",
"message": "Operation completed successfully",
"data": { /* response data */ },
"meta": { /* pagination info */ }
}{
"status": "error",
"message": "Error description",
"error": {
"statusCode": 400,
"details": "Detailed error information"
}
}Use the provided test credentials to test different user roles:
# Test user registration
curl -X POST http://localhost:5000/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{"name":"Test User","email":"test@example.com","password":"Test@123"}'
# Test nearby deals
curl "http://localhost:5000/api/v1/deals/nearby?lat=31.5204&lng=74.3587&radius=10"
# Test booking creation (requires authentication)
curl -X POST http://localhost:5000/api/v1/bookings/DEAL_ID \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"bookingDate":"2025-06-15T19:00:00.000Z","numberOfPeople":2}'# Seed database with sample data
npm run seed
# Clear database
npm run seed:clear- Set
NODE_ENV=production - Configure production MongoDB URI
- Set secure JWT secret
- Configure CORS for your frontend domain
- Set up SSL/TLS certificates
- Configure reverse proxy (nginx)
- Environment variables configured
- Database indexes created
- SSL certificates installed
- Rate limiting configured
- Monitoring setup
- Backup strategy implemented
- Error logging configured
- Fork the repository
- Create a feature branch (
git checkout -b feature/new-feature) - Commit your changes (
git commit -am 'Add new feature') - Push to the branch (
git push origin feature/new-feature) - Create a Pull Request
Interactive API documentation will be available at:
- Development:
http://localhost:5000/api/docs - Production:
https://your-domain.com/api/docs
For technical support or questions:
- Create an issue in the repository
- Email: support@restaurant-api.com
- Documentation: API Docs
This project is licensed under the MIT License - see the LICENSE file for details.
✅ Core Requirements Completed
- Restaurant deal creation
- Nearby deals with geolocation
- Deal booking system
- ML discount suggestions (hardcoded)
✅ Additional Features
- User authentication & authorization
- Admin dashboard
- Real-time availability
- Comprehensive analytics
- Rate limiting & security
🔄 Future Enhancements
- External ML service integration
- Real-time notifications
- Payment gateway integration
- Mobile app API extensions
- Advanced analytics dashboard
Built with ❤️ for the restaurant industry