API Development
Yabasi provides a robust set of tools for building RESTful APIs, including versioning, rate limiting, CORS support, and standardized response formatting. The framework makes it easy to create secure and scalable APIs while following REST best practices.
API Routes
Define API routes using the ApiRouter with automatic prefix and versioning:
use Yabasi\Routing\ApiRouter;
$apiRouter = new ApiRouter($router);
$apiRouter->setVersion('v1')->group([], function($router) {
$router->resource('users', 'UserApiController');
$router->get('posts', 'PostApiController@index');
$router->post('posts', 'PostApiController@store');
});
API Controllers
Extend the ApiController base class to get standardized response methods:
namespace App\Controllers;
use Yabasi\Http\Controllers\ApiController;
use Yabasi\Http\Request;
class UserApiController extends ApiController
{
public function index()
{
$users = User::all();
return $this->respondWithData($users);
}
public function store(Request $request)
{
// Validation and creation logic
return $this->respondWithSuccess('User created successfully', 201);
}
}
Rate Limiting
Protect your API endpoints with built-in rate limiting:
$apiRouter->group([
'middleware' => [
RateLimitMiddleware::class
]
], function($router) {
// Your rate-limited routes here
});
API Versioning
API versioning is handled automatically through the URL or Accept header:
- URL-based:
/api/v1/users
- Header-based:
Accept-Version: v1
CORS Configuration
Configure CORS for your API in the config/config.php file:
'cors' => [
'allowed_origins' => ['*'],
'allowed_methods' => ['*'],
'allowed_headers' => ['*'],
'allow_credentials' => false,
'max_age' => 0,
],
Standardized API Responses
ApiController provides methods for consistent response formatting:
respondWithData($data, $statusCode = 200)
respondWithError($message, $statusCode)
respondWithSuccess($message, $statusCode = 200)
respondWithValidationError($errors)
respondWithPaginatedData($data, $page, $perPage, $total)
Response Examples
Example of standardized JSON responses:
{
"data": {
"id": 1,
"name": "John Doe",
"email": "john@example.com"
},
"meta": {
"version": "v1"
}
}
Best Practices
- Always version your APIs
- Implement rate limiting for public endpoints
- Use appropriate HTTP status codes
- Include proper error messages in responses
- Document your API endpoints