A production-ready Raw PHP REST API Starter Kit with JWT authentication, user management, file uploads, caching, rate limiting, and Docker support.
- β JWT Authentication - Secure token-based authentication
- β User Management - Complete CRUD operations
- β File Upload/Download - Secure file handling
- β Rate Limiting - API request throttling
- β Input Validation - Request data validation
- β Caching System - File-based caching
- β Error Handling - Centralized error management
- β Logging - Request/error logging
- β Health Checks - System monitoring
- β Docker Support - Containerized deployment
- β PHPUnit Testing - Comprehensive test suite
- β API Documentation - Complete endpoint docs
- β Debug Bar - Development debugging toolbar with performance monitoring
- β CLI Support - Command-line interface for development tasks
- β API Versioning - Multiple API versions with backward compatibility
- β Queue System - Background job processing with Redis/Database drivers
βββ app/
β βββ api/ # API versioning system
β βββ cli/ # CLI commands and console
β βββ config/ # Configuration files
β βββ controllers/ # Request handlers
β β βββ v1/ # Version 1 controllers
β β βββ v2/ # Version 2 controllers
β βββ core/ # Core framework classes
β βββ database/ # Migrations and seeders
β βββ debugbar/ # Debug bar system
β βββ exceptions/ # Exception handlers
β βββ helpers/ # Utility classes
β βββ middleware/ # Request middleware
β βββ models/ # Data models
β βββ queue/ # Queue system
β β βββ Drivers/ # Queue drivers (Database, Redis)
β β βββ Jobs/ # Job classes
β β βββ Processors/ # Queue workers
β βββ routes/ # Route definitions
β β βββ api.php # Legacy API routes (backward compatibility)
β β βββ api_v1.php # Version 1 API routes
β β βββ api_v2.php # Version 2 API routes
β β βββ web.php # Web routes
β βββ services/ # Business logic
β βββ tests/ # Test files
βββ console # CLI entry point
βββ bootstrap/ # Application bootstrap
βββ docs/ # API documentation
βββ public/ # Web server document root
βββ storage/ # Logs, cache, uploads
βββ vendor/ # Composer dependencies
git clone https://github.com/jmrashed/php-rest-api-pro-kit.git
cd php-rest-api-pro-kit
composer install
cp .env.example .env
# Edit .env with your database credentials
Debug Bar Configuration (Optional)
# Enable debug bar for development
DEBUGBAR_ENABLED=true
DEBUGBAR_ALLOWED_IPS=127.0.0.1,::1
Queue System Configuration (Optional)
# Queue driver (database or redis)
QUEUE_DRIVER=database
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
# Option 1: Import the complete database schema
mysql -u root -p < app/database/Database.sql
# Option 2: Use migration system (recommended)
php migrate.php fresh # Creates database, runs migrations and seeders
# Using CLI (recommended)
php console migrate
php console migrate seed
php console migrate rollback
php console migrate fresh
# Or legacy commands
php migrate.php migrate
php migrate.php seed
php migrate.php rollback
php migrate.php fresh
# Using CLI command (recommended)
php console serve
# Or PHP Built-in Server
php -S localhost:8000 -t public
# Or with Docker
docker-compose up -d
curl http://localhost:8000/api/health
After running migrations and seeders, use these credentials to test the API:
# Admin User
Email: admin@hrms.com
Password: admin123
# HR Manager
Email: hr@hrms.com
Password: admin123
# Employees
Email: john@hrms.com, jane@hrms.com, mike@hrms.com
Password: admin123
GET /api/v1/health
- Health checkPOST /api/v1/auth/register
- Register new userPOST /api/v1/auth/login
- Login userGET /api/v1/users
- Get all users (paginated)GET /api/v1/users/{id}
- Get user by IDPOST /api/v1/users
- Create userPUT /api/v1/users/{id}
- Update userDELETE /api/v1/users/{id}
- Delete user
GET /api/v2/health
- Health check with metadataPOST /api/v2/auth/register
- Register with enhanced responsePOST /api/v2/auth/login
- Login with structured responseGET /api/v2/users
- Get users with enhanced paginationGET /api/v2/users/{id}
- Get user with metadataPOST /api/v2/users
- Create user with structured responsePUT /api/v2/users/{id}
- Update user with action trackingDELETE /api/v2/users/{id}
- Delete user with confirmation
Note: These endpoints default to V1 behavior for backward compatibility
POST /api/auth/register
- Register new userPOST /api/auth/login
- Login userPOST /api/auth/logout
- Logout userGET /api/users
- Get all users (paginated)GET /api/users/{id}
- Get user by IDPOST /api/users
- Create userPUT /api/users/{id}
- Update userDELETE /api/users/{id}
- Delete userPOST /api/files/upload
- Upload fileDELETE /api/files/{id}
- Delete fileGET /api/health
- Health checkGET /api/health/info
- System info
# V1 API (Explicit versioning - Recommended)
curl -X POST http://localhost:8000/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"john@example.com","password":"password123"}'
# V2 API (Enhanced responses)
curl -X POST http://localhost:8000/api/v2/auth/register \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"john@example.com","password":"password123"}'
# Legacy API (Backward compatibility)
curl -X POST http://localhost:8000/api/auth/register \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"john@example.com","password":"password123"}'
# Version via header
curl -X GET http://localhost:8000/api/users \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "X-API-Version: v2"
The HRMS includes the following tables:
- users - Employee accounts with roles (admin, hr, employee)
- departments - Company departments
- employee_profiles - Extended employee information
- attendance - Daily attendance tracking
- leave_types - Leave categories (Annual, Sick, etc.)
- leave_requests - Leave applications with approval workflow
- payroll - Monthly salary processing
- performance_reviews - Employee performance evaluations
- tokens - JWT authentication tokens
- Application: Main app bootstrap and container
- Router: URL routing and middleware pipeline
- Request/Response: HTTP abstraction layer
- Database: PDO wrapper with query builder
- Authentication: JWT-based auth system
- Cache: File-based caching system
- Validation: Input validation and sanitization
- Password hashing (bcrypt)
- JWT token authentication
- Rate limiting (60 requests/hour per IP)
- Input sanitization and validation
- CORS middleware
- SQL injection protection (prepared statements)
The built-in debug bar provides real-time development insights with minimal performance impact.
- Performance Monitoring - Execution time and memory usage tracking
- Database Queries - All SQL queries with timing information
- Debug Messages - Categorized logging (info, warning, error)
- Request Data - HTTP method, URI, headers, and parameters
- Custom Timers - Measure specific code execution times
Add to your .env
file:
# Enable debug bar (disabled by default)
DEBUGBAR_ENABLED=true
# Optional: Restrict access by IP (comma-separated)
DEBUGBAR_ALLOWED_IPS=127.0.0.1,::1,192.168.1.100
// Log debug messages with different levels
debug('User login attempt', 'info');
debug('Invalid credentials', 'warning');
debug('Database connection failed', 'error');
// Measure execution time
timer_start('api_call');
// ... your code ...
timer_stop('api_call');
- Database Queries: All PDO queries are automatically tracked
- Memory Usage: Current and peak memory consumption
- Request Info: HTTP method, URI, headers automatically captured
HTML Pages: Debug toolbar appears at the bottom of the page
JSON APIs: Debug data included in X-Debugbar-Data
response header (Base64 encoded JSON)
- Automatically disabled when
DEBUGBAR_ENABLED=false
- IP whitelist support for production-like environments
- No sensitive data exposure (credentials are filtered)
- Zero performance impact when disabled
Visit http://localhost:8000/welcome
to see the debug bar in action.
The framework supports multiple API versions with backward compatibility and flexible version detection.
- URI Path (Recommended)
GET /api/v1/users
GET /api/v2/users
- X-API-Version Header
curl -H "X-API-Version: v2" http://localhost:8000/api/users
- Accept Header
curl -H "Accept: application/vnd.api+json;version=2" http://localhost:8000/api/users
- Standard JSON responses
- Basic error handling
- Simple data structure
{
"status": "success",
"data": {...},
"version": "v1"
}
- Enhanced response format
- Structured error codes
- Metadata inclusion
- Timestamp tracking
{
"success": true,
"data": {...},
"meta": {
"version": "v2",
"timestamp": "2024-10-21T10:30:00+00:00",
"action": "created"
}
}
V1 Features:
- Basic CRUD operations
- Simple response format
- Standard HTTP status codes
V2 Features:
- Enhanced error handling with error codes
- Metadata in responses
- Improved pagination info
- Structured error responses
- Create version directory:
app/controllers/v3/
- Create versioned controllers
- Add route file:
app/routes/api_v3.php
- Update Application.php to load new routes
For New Projects:
- Use explicit versioning from the start:
/api/v1/
- Avoid legacy endpoints
For Existing Projects:
- Legacy endpoints (
/api/
) remain unchanged - Gradually migrate clients to versioned endpoints
- Deprecate legacy endpoints in future versions
Best Practices:
- Always specify version in new integrations
- Use semantic versioning for major changes
- Maintain at least 2 versions simultaneously
- Provide migration guides for version changes
The framework includes a powerful queue system for background job processing with support for multiple drivers.
- Background Job Processing - Asynchronous task execution
- Multiple Drivers - Database and Redis support
- Email Queues - Reliable email delivery
- File Processing - Image resize, file conversion, compression
- Job Retry Logic - Automatic retry with exponential backoff
- Failed Job Handling - Dead letter queue for failed jobs
- CLI Workers - Command-line queue processors
Add to your .env
file:
# Queue driver (database or redis)
QUEUE_DRIVER=database
# Redis configuration (if using Redis driver)
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
// Email jobs
queue_email('user@example.com', 'Welcome!', 'Welcome message');
// File processing jobs
queue_file_processing('/path/to/image.jpg', 'resize', ['width' => 800, 'height' => 600]);
// Custom jobs
use App\Queue\Jobs\SendEmailJob;
$job = new SendEmailJob('user@example.com', 'Subject', 'Message');
dispatch($job, 'emails');
# Start queue worker
php console queue work default
# Process specific queue
php console queue work emails
# Process limited number of jobs
php console queue work files 10
# Check queue status
php console queue status emails
SendEmailJob - Email delivery
- Automatic retry on failure
- SMTP configuration support
- HTML/text email support
ProcessFileJob - File processing
- Image resizing
- File compression
- Format conversion
- Batch processing support
use App\Queue\Jobs\BaseJob;
class CustomJob extends BaseJob
{
private $data;
public function __construct($data)
{
$this->data = $data;
$this->maxRetries = 3;
$this->delay = 30; // seconds
}
public function handle(): bool
{
// Your job logic here
return true;
}
public function failed(\Exception $exception): void
{
// Handle job failure
}
}
Database Driver
- Uses MySQL/PostgreSQL for job storage
- Automatic table creation
- Transaction support
- No external dependencies
Redis Driver
- High performance
- Atomic operations
- Delayed job support
- Requires Redis extension
The framework includes a powerful command-line interface for development tasks.
# Start development server
php console serve [host] [port]
# Database migrations
php console migrate [fresh|rollback|seed]
# Run tests
php console test [specific-test-file]
# Cache management
php console cache clear
# Generate files
php console make controller ControllerName
php console make model ModelName
# Queue management
php console queue work [queue] [max-jobs]
php console queue status [queue]
php console queue clear [queue]
# Show help
php console help
# Start server on custom host/port
php console serve localhost 8080
# Fresh migration with seeders
php console migrate fresh
# Generate a new controller
php console make controller ProductController
# Generate a new model
php console make model Product
# Run specific test
php console test app/tests/Unit/UserTest.php
# Clear application cache
php console cache clear
# Start queue worker
php console queue work emails
# Check queue status
php console queue status default
# Run all tests
vendor/bin/phpunit
# Run specific test
vendor/bin/phpunit app/tests/Unit/UserTest.php
# Build and run
docker-compose up -d
# View logs
docker-compose logs -f app
# Stop services
docker-compose down
- PHP 8.0+
- MySQL 5.7+
- Composer
- Docker (optional)
- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature
) - Commit changes (
git commit -m 'Add amazing feature'
) - Push to branch (
git push origin feature/amazing-feature
) - Open Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Md Rasheduzzaman
Full-Stack Software Engineer & Technical Project Manager
Building scalable, secure & AI-powered SaaS platforms across ERP, HRMS, CRM, LMS, and E-commerce domains.
Over 10 years of experience leading full-stack teams, cloud infrastructure, and enterprise-grade software delivery.
π Portfolio: jmrashed.github.io
βοΈ Email: jmrashed@gmail.com
πΌ LinkedIn: linkedin.com/in/jmrashed
π Blog: medium.com/@jmrashed
π» GitHub: github.com/jmrashed
βNeed a Reliable Software Partner? I build scalable, secure & modern solutions for startups and enterprises.β