Skip to content

hotel search API that aggregates results from multiple suppliers with parallel execution, deduplication, and comprehensive filtering. Built with Laravel 12 following enterprise-grade architecture principles.

Notifications You must be signed in to change notification settings

hassangomaa/ctx-multi-supplier-hotels

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

CTX Multi-Supplier Hotel Search API

A production-ready hotel search API that aggregates results from multiple suppliers with parallel execution, deduplication, and comprehensive filtering. Built with Laravel 12 following enterprise-grade architecture principles.

🎯 Project Overview

This API solves the problem of searching hotels across multiple suppliers by:

  • Fetching data from 4+ suppliers simultaneously
  • Normalizing different data formats into a unified structure
  • Removing duplicates and selecting the best price
  • Providing advanced filtering and sorting capabilities
  • Handling failures gracefully without breaking the user experience

πŸ—οΈ Architecture & Design Principles

SOLID Compliance

  • Single Responsibility: Each service handles one specific concern
  • Open/Closed: Easy to add new suppliers without modifying existing code
  • Liskov Substitution: All suppliers implement the same contract
  • Interface Segregation: Clean, focused interfaces
  • Dependency Inversion: Services depend on abstractions via DI container

Code Quality

  • DRY: Shared logic centralized in abstract classes
  • KISS: Simple, straightforward implementation
  • Testable: Proper dependency injection and mocking support

πŸš€ Quick Start

Prerequisites

  • PHP 8.2+
  • Composer
  • Laravel 12
  • SQLite (for development) or MySQL/PostgreSQL (for production)

Installation Steps

  1. Clone and Install Dependencies
git clone https://github.com/hassangomaa/ctx-multi-supplier-hotels
cd ctx-multi-supplier-hotels
composer install
  1. Environment Setup
cp .env.example .env
php artisan key:generate
  1. Database Setup
# For MySQL/PostgreSQL (production)
# Update .env with your database credentials
php artisan migrate
  1. Start Development Server
php artisan serve
  1. Verify Installation
# Test the API endpoint
curl "http://localhost:8000/api/hotels/search?location=Dubai&check_in=2025-01-15&check_out=2025-01-20"

βš™οΈ Configuration

Environment Variables

Create your .env file with these key variables:

# Application
APP_NAME="CTX Hotel Search API"
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost:8000

# Database
DB_CONNECTION=sqlite
DB_DATABASE=database/database.sqlite

# Supplier Configuration
SUPPLIER_TIMEOUT=3
SUPPLIER_CONCURRENCY=4

# Development Mock Suppliers
SUPPLIER_A_BASE_URL=/mock/supplier-a
SUPPLIER_B_BASE_URL=/mock/supplier-b
SUPPLIER_C_BASE_URL=/mock/supplier-c
SUPPLIER_D_BASE_URL=/mock/supplier-d

# Production External Suppliers (uncomment when ready)
# SUPPLIER_A_BASE_URL=https://api.supplier-a.com/hotels
# SUPPLIER_B_BASE_URL=https://api.supplier-b.com/search
# SUPPLIER_C_BASE_URL=https://api.supplier-c.com/availability
# SUPPLIER_D_BASE_URL=https://api.supplier-d.com/rooms

Supplier Configuration

Edit config/suppliers.php to:

  • Enable/disable specific suppliers
  • Set request timeouts
  • Configure concurrency limits
  • Define base URLs for each supplier

πŸ”Œ API Endpoints

Hotel Search

Endpoint: GET /api/hotels/search

Required Parameters

Parameter Type Description Example
location string City or country Dubai, UAE
check_in date Arrival date 2025-01-15
check_out date Departure date 2025-01-20

Optional Parameters

Parameter Type Description Default
guests integer Number of guests 1
min_price numeric Minimum price per night null
max_price numeric Maximum price per night null
sort_by string Sort order: price or rating null
lat numeric Latitude for location filtering null
lng numeric Longitude for location filtering null
radius_km numeric Search radius in kilometers null

Example Requests

Basic Search:

curl "http://localhost:8000/api/hotels/search?location=Dubai&check_in=2025-01-15&check_out=2025-01-20"

Advanced Search with Filters:

curl "http://localhost:8000/api/hotels/search?location=Dubai&check_in=2025-01-15&check_out=2025-01-20&guests=2&min_price=100&max_price=500&sort_by=price&lat=25.2048&lng=55.2708&radius_km=10"

Language-Specific Search:

# English
curl "http://localhost:8000/api/hotels/search?location=Dubai&check_in=2025-01-15&check_out=2025-01-20&lang=en"

# Arabic
curl "http://localhost:8000/api/hotels/search?location=Dubai&check_in=2025-01-15&check_out=2025-01-20&lang=ar"

Response Format

{
    "success": true,
    "msg": "Hotels retrieved successfully",
    "data": [
        {
            "name": "Grand City Hotel",
            "location": "Dubai, UAE",
            "price_per_night": 240.0,
            "available_rooms": 3,
            "rating": 4.5,
            "source": "supplier_b"
        }
    ]
}

πŸ§ͺ Testing & Development

Mock Suppliers

For development and testing, these endpoints provide sample data:

  • GET /mock/supplier-a - Sample hotel data from Supplier A
  • GET /mock/supplier-b - Sample hotel data from Supplier B
  • GET /mock/supplier-c - Sample hotel data from Supplier C
  • GET /mock/supplier-d - Sample hotel data from Supplier D

πŸ”§ Core Components

Services

Service Purpose Key Features
HotelSearchService Main orchestrator Parallel execution, deduplication, coordination
AbstractSupplierService Base supplier class HTTP handling, error management, parameter building
HotelNormalizer Data standardization Format conversion, field mapping
HotelFilter Business logic filtering Price, location, availability, coordinates

Suppliers

Supplier Extends Configuration Key
SupplierAService AbstractSupplierService supplier_a
SupplierBService AbstractSupplierService supplier_b
SupplierCService AbstractSupplierService supplier_c
SupplierDService AbstractSupplierService supplier_d

Middleware

Middleware Purpose Applied To
XssMiddleware XSS protection All API routes
SetLocale Language detection All routes

πŸš€ Key Features

1. Parallel Execution

  • Technology: Laravel's Http::pool() for concurrent requests
  • Benefits: Reduced total response time, configurable timeouts
  • Configuration: Adjustable concurrency limits via environment variables

2. Smart Deduplication

  • Algorithm: Groups hotels by name + location (case-insensitive)
  • Selection: Keeps the lowest price option when duplicates exist
  • Benefits: Better user experience, no redundant results

3. Advanced Filtering

  • Price Range: Min/max price filtering
  • Location: Coordinate-based filtering with optional radius
  • Availability: Guest count validation
  • Performance: Efficient collection operations

4. Data Normalization

  • Input: Handles different supplier data formats
  • Output: Consistent structure across all suppliers
  • Flexibility: Easy to add new supplier formats

5. Error Handling

  • Graceful Degradation: Supplier failures don't break the response
  • Comprehensive Logging: Detailed error tracking for debugging
  • User Experience: Partial results when some suppliers fail

6. Internationalization

  • Languages: English (en) and Arabic (ar) support
  • Detection: Query parameter or Accept-Language header
  • Fallback: Graceful language fallback handling

πŸ“Š Performance Characteristics

Response Times

  • Mock Suppliers: ~50-100ms (local processing)
  • External Suppliers: ~200-500ms (network + processing)
  • Parallel Execution: Total time = slowest supplier response

Scalability

  • Concurrency: Configurable supplier limits
  • Memory: Efficient collection operations
  • Caching: Ready for Redis/Memcached integration

Monitoring

  • Logging: Comprehensive supplier interaction logging
  • Metrics: Response time tracking ready
  • Alerts: Error threshold monitoring ready

πŸ”’ Security Features

Input Validation

  • Request Validation: Comprehensive parameter validation
  • Type Safety: Strict type checking for all inputs
  • Sanitization: XSS protection middleware

Data Protection

  • No Sensitive Data: No API keys or credentials exposed
  • Rate Limiting: Ready for implementation
  • CORS: Configurable cross-origin policies

πŸš€ Deployment

Production Checklist

  1. Environment Configuration

    • Set APP_ENV=production
    • Disable APP_DEBUG
    • Configure production database
    • Set external supplier URLs
  2. Performance Optimization

    • Enable caching (Redis/Memcached)
    • Configure queue workers
    • Set appropriate timeouts
  3. Monitoring Setup

    • Application logging
    • Performance metrics
    • Error alerting

Deployment Options

  • Traditional: VPS/Cloud server with Nginx/Apache
  • Container: Docker with Docker Compose
  • Cloud: AWS, Google Cloud, Azure
  • Platform: Laravel Forge, Vercel, Heroku

πŸ”§ Adding New Suppliers

Step-by-Step Process

  1. Create Service Class
<?php
namespace App\Services\Suppliers;

class NewSupplierService extends AbstractSupplierService
{
    protected function configKey(): string
    {
        return 'new_supplier';
    }

    protected function name(): string
    {
        return 'new_supplier';
    }
}
  1. Add Configuration
// config/suppliers.php
'new_supplier' => [
    'enabled' => true,
    'base_url' => env('NEW_SUPPLIER_BASE_URL', '/mock/new-supplier'),
],
  1. Register Service
// app/Providers/AppServiceProvider.php
$this->app->bind('supplier.new', NewSupplierService::class);
  1. Add Tests
// tests/Feature/NewSupplierTest.php
// Test the new supplier integration

πŸ› Troubleshooting

Common Issues

Issue Cause Solution
Supplier timeout errors Network issues or slow responses Increase SUPPLIER_TIMEOUT value
Empty results All suppliers failing Check supplier URLs and network connectivity
Validation errors Invalid parameter format Verify date formats and parameter types
Memory issues Large result sets Implement pagination or result limiting

Debug Mode

Enable debug mode in .env:

APP_DEBUG=true
LOG_LEVEL=debug

Check logs in storage/logs/laravel.log for detailed error information.

πŸ“š API Documentation

OpenAPI/Swagger

The API is ready for OpenAPI documentation generation. Use tools like:

  • Laravel Scribe
  • L5-Swagger
  • OpenAPI Generator

Postman Collection

Create a Postman collection with the provided examples for easy testing and development.

🀝 Contributing

Development Workflow

  1. Fork the repository
  2. Create a feature branch
  3. Implement changes following SOLID principles
  4. Add comprehensive tests
  5. Submit a pull request

Code Standards

  • Follow PSR-12 coding standards
  • Maintain SOLID principles
  • Write meaningful commit messages
  • Include tests for new features

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

For technical support or questions:

  • Create an issue in the repository
  • Check the troubleshooting section
  • Review the code examples and tests

Built with ❀️ using Laravel 12 and modern PHP practices

About

hotel search API that aggregates results from multiple suppliers with parallel execution, deduplication, and comprehensive filtering. Built with Laravel 12 following enterprise-grade architecture principles.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages