Kotchasan Framework Documentation
API & Middleware Management
API & Middleware Management
This section covers guidelines for developing RESTful APIs with the Kotchasan Framework, including the use of the Middleware system for handling Authentication and Security.
Core Components
1. ApiController
Base Controller for creating API Endpoints. Supports Request handling, Validation, and Standard Response generation.
2. Middleware System
Layered system for managing HTTP Request/Response flow. Used for Authentication, Logging, CORS, etc.
3. ApiException
Standardized Error Handling and HTTP Status Code management.
Integration Guide
Integrating components (Controller, Middleware, Routing) to build a complete API system.
Basic REST API Structure
// api/v1/user.php
use Kotchasan\ApiController;
use Kotchasan\Http\Request;
class UserController extends ApiController
{
/**
* GET /users
* List users
*/
public function index(Request $request)
{
// 1. Validate Method
if (!self::validateMethod($request, 'GET')) {
throw new \Kotchasan\ApiException('Method Not Allowed', 405);
}
// 2. Auth Check (Example)
$token = $this->getAccessToken($request);
if (!$token) {
throw new \Kotchasan\ApiException('Unauthorized', 401);
}
// 3. Logic
$users = ['User A', 'User B'];
// 4. Response
return $this->successResponse($users);
}
}Using Middleware Pipeline
Chaining multiple middleware to filter requests before reaching the Controller.
use Kotchasan\Http\Request;
use Kotchasan\Http\Middleware\CorsMiddleware;
use Kotchasan\Http\Middleware\JwtMiddleware;
use App\Api\UserController;
// Setup Middleware
$pipeline = new \Kotchasan\Http\Middleware\Pipeline();
$pipeline->pipe(new CorsMiddleware(['*'])); // 1. CORS
$pipeline->pipe(new JwtMiddleware('secret')); // 2. Auth
// Handle Request
$response = $pipeline->process($request, function($req) {
// Controller Dispatcher
$controller = new UserController();
return $controller->index($req);
});
$response->send();Best Practices
- Versioning: Always include version in URL (e.g.
/api/v1/...) - Stateless: API should be Stateless (no Session), use Token instead.
- HTTP Verbs: Use proper HTTP methods (GET, POST, PUT, DELETE).
- Error Codes: use standard HTTP Status Codes (200, 201, 400, 401, 403, 404, 500).
- Security: Validate Input, sanitize Output, and use HTTPS.