API Switcher is a Laravel-based tool that allows seamless switching between real API endpoints and mock responses based on defined criteria. It provides a flexible way to develop and test applications without relying on external API services.
Note: API Switcher is designed primarily for development and testing environments to facilitate API mocking and testing.
- API Request Routing: Automatically routes API requests to either real API endpoints or mock responses
- Custom Criteria Management: Define custom criteria for different API paths and HTTP methods
- Mock Response Builder: Create mock responses with custom status codes, headers, and bodies
- Real-time API Testing: Test API endpoints directly from the dashboard
- Extensive Logging: Comprehensive logging of API requests, responses, and errors
- Response Caching: Cache API responses to improve performance
- Interactive Dashboard: Web interface to manage all aspects of API switching
- Permission-based Access: Role-based access control for API Switcher functionality
- PHP 8.2 or higher
- Laravel 12.0 or higher
- MySQL or compatible database
- Docker (optional, for containerized setup)
- Clone the repository or integrate the API Switcher files into your existing Laravel project
- Install dependencies:
composer install
- Run migrations to create the required tables:
php artisan migrate
- Set up environment variables in your
.env
file:REAL_API_BASE_URL=https://api.example.com API_SWITCHER_ENABLED=true API_SWITCHER_DEFAULT=pass API_SWITCHER_LOGGING=true
- Clone the repository
- Build and run the Docker container:
make run
- Access the application at the configured URL
- To access the container shell:
make shell
The configuration file is located at config/api_switcher.php
. Here are the key configuration options:
return [
// Base URL for the real API
'real_api_base_url' => env('REAL_API_BASE_URL', 'https://api.example.com'),
// Enable or disable the API switcher
'enabled' => env('API_SWITCHER_ENABLED', true),
// Default behavior when no matching criteria is found
// Options: 'real', 'mock', 'pass'
'default_behavior' => env('API_SWITCHER_DEFAULT', 'pass'),
// Log API requests and responses
'logging' => [
'enabled' => env('API_SWITCHER_LOGGING', true),
'include_request_body' => env('API_SWITCHER_LOG_REQUEST_BODY', false),
'include_response_body' => env('API_SWITCHER_LOG_RESPONSE_BODY', false),
],
// Cache settings for API responses
'cache' => [
'enabled' => env('API_SWITCHER_CACHE', false),
'ttl' => env('API_SWITCHER_CACHE_TTL', 3600), // time in seconds
],
// HTTP client settings for real API requests
'http_client' => [
'timeout' => env('API_SWITCHER_TIMEOUT', 30),
'connect_timeout' => env('API_SWITCHER_CONNECT_TIMEOUT', 10),
'retry' => env('API_SWITCHER_RETRY', 1),
'retry_delay' => env('API_SWITCHER_RETRY_DELAY', 100),
],
// Headers to be forwarded to real API
'forward_headers' => [
'Authorization',
'Content-Type',
'Accept',
'X-Requested-With',
],
];
- Access the API Switcher dashboard at
/cms-api/api-switcher
- Click on "Create New Criteria" to create a new API criterion
- Fill in the required fields:
- Name: A descriptive name for the criterion
- Path: The API path to match (e.g.,
/users
or/products/123
) - Method: HTTP method (GET, POST, PUT, PATCH, DELETE, etc.)
- Type:
real
to forward to real API ormock
for a mock response - Status Code: HTTP status code for mock responses
- Content Type: Response content type (e.g.,
application/json
) - Headers: Custom response headers (as JSON)
- Body: Response body content (as JSON)
- Is Active: Enable/disable the criterion
- Description: Optional description of the criterion
- Real API URL (optional): Override the base URL for this specific endpoint
Example of creating a mock response for a user profile endpoint:
- Create a new API criterion
- Set Path to
/users/profile
- Set Method to
GET
- Set Type to
mock
- Set Status Code to
200
- Set Content Type to
application/json
- Set Body to:
{ "id": 1, "name": "John Doe", "email": "john@example.com", "role": "admin" }
- Set Is Active to
true
- Save the criterion
The API Switcher middleware automatically intercepts API requests based on the configured criteria. No code changes are necessary in your application.
To make requests to endpoints managed by API Switcher, use your regular Laravel HTTP client or any HTTP client of your choice. For example:
// This request will be intercepted by API Switcher if criteria match
$response = Http::get('/api/users/profile');
The API Switcher dashboard includes a testing tool to test API endpoints and see how they behave with the configured criteria:
- Navigate to the "Test API Endpoint" section
- Enter the API path and method
- Add any required headers or request body
- Click "Test Endpoint" to see the response
The API Switcher logs all requests and responses for debugging and auditing:
- Navigate to the "View Logs" section to see all API activity
- Filter logs by path, method, status code, etc.
- View detailed information including request headers, body, and response data
The ApiCriteria
model is the core component of the API Switcher:
ApiCriteria::findMatchingCriteria(string $path, string $method);
$criteria->isMock();
$criteria->getRealEndpoint();
To integrate the API Switcher middleware in additional routes:
Route::prefix('api')->middleware(ApiSwitcherMiddleware::class)->group(function() {
// Your API routes here
});
- An API request is received by the Laravel application
- The
ApiSwitcherMiddleware
intercepts the request - The middleware looks for matching criteria in the database
- Based on the criteria type:
- If
mock
, returns a mock response with the defined status, headers, and body - If
real
, forwards the request to the actual API endpoint
- If
- If no matching criteria is found, follows the default behavior (pass, mock, or real)
- Logs the request and response details if logging is enabled
The API Switcher consists of several key components:
- ApiCriteria Model: Defines the criteria for matching API requests and determines their handling
- ApiSwitcherMiddleware: Intercepts API requests and processes them according to criteria
- ApiLog Model: Records all API activities for debugging and monitoring
- Dashboard Controllers: Provide a user interface for managing criteria and viewing logs
- Configuration System: Allows customization through environment variables and configuration files
The Docker setup consists of:
- Web container running PHP with Laravel
- MySQL database container
- Optional additional services as defined in
config/docker/compose.yml
- API request not being intercepted: Ensure the API Switcher is enabled in your configuration and that your routes are properly set up with the middleware.
- Mock responses not working: Verify the criteria match exactly (path and method) and that the criteria is marked as active.
- Performance issues: Consider enabling response caching for frequently accessed endpoints.
- Headers not forwarded: Check the
forward_headers
configuration to ensure all required headers are included.
- API Switcher should only be enabled in development and testing environments
- Be cautious about storing sensitive data in mock responses
- Use proper authentication for accessing the API Switcher dashboard
- Regular review of API logs to detect potential security issues
The project includes several Docker-related commands in the Makefile:
make build-app
: Build the Docker imagemake network
: Create the Docker network if it doesn't existmake run
: Build and run the Docker containersmake logs
: View the container logsmake stop
: Stop all containersmake shell
: Open a shell in the API containermake import-db
: Import database from SQL dump filesmake build-prod
: Build production Docker image
The API Switcher includes custom Artisan commands for management:
php artisan api:list-criteria
: List all defined API criteriaphp artisan api:check-endpoint {path} {method}
: Check how a specific endpoint would be handledphp artisan api:clear-logs
: Clear all API logsphp artisan config:set
: Update configuration values
Contributions to the API Switcher are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin feature/my-feature
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.