| Install | |
|---|---|
composer require mhasnainjafri/restapikit |
|
| Latest Version: | v1.0.4 |
| PHP: | ^8.0|^8.2|^8.3 |
The mhasnainjafri/restapikit package is a Laravel-based toolkit designed to simplify the development of RESTful APIs.
It provides a uniform structure for handling responses, exceptions, file uploads, authentication, and more. This package
is ideal for developers looking to streamline API development while adhering to best practices.
You can install the package via Composer:
composer require mhasnainjafri/restapikit
RestControllerTo use the package, extend your controller from Mhasnainjafri\RestApiKit\Http\Controllers\RestController. This
provides access to the package's built-in methods for handling responses, exceptions, and more.
use Mhasnainjafri\RestApiKit\Http\Controllers\RestController;
class BusinessController extends RestController
{
public function store(Request $request)
{
$data = $this->service->create($validated);
return $this->response($data,"Record has been saved successfully", API::CREATED);
}
}
The package provides a consistent structure for API responses. For example:
return $this->response($data, 'Data retrieved successfully.', API::SUCCESS);
If $data is paginated, the response will automatically include pagination metadata:
{
"success": true,
"data": {
"items": [
{
"id": 1,
"name": "API Toolkit"
}
],
"meta": {
"current_page": 1,
"total_pages": 1,
"per_page": 10,
"total": 2
}
},
"message": "Data retrieved successfully."
}
Alternatively, you can explicitly return a paginated response:
return $this->response()
->paginate($users, 'users')
->message('Users retrieved successfully.')
->toResponse();
The package simplifies exception handling by providing pre-defined methods for common scenarios:
catch (Exception $exception) {
return $this->exception($exception, "Something went wrong", API::INTERNAL_SERVER_ERROR);
}
if ($exception instanceof ValidationException) {
return $this->response()
->errors($exception->errors())
->status(API::UNPROCESSABLE_ENTITY);
}
if ($exception instanceof UnauthorizedException) {
return $this->response()
->message('Unauthorized access')
->status(API::FORBIDDEN);
}
return $this->response()
->message('Server error')
->status(API::INTERNAL_SERVER_ERROR);
The package includes utilities for file uploads, deletions, and URL generation.
$filePath = $this->upload($file, 'uploads/documents', 'local');
$this->deleteFile($filePath, 'local');
$url = $this->fileUrl($filePath, 'local');
The cacheResponse method allows you to cache API responses for a specified duration.
public function index()
{
return $this->cacheResponse('users.index', function () {
return User::all();
}, 30); // Cache for 30 minutes
}
The package provides a standalone API response helper for developers who prefer not to extend the RestController:
API::success($data, 'Data retrieved successfully');
API::error('An error occurred', API::INTERNAL_SERVER_ERROR);
// Additional response helpers:
API::validationError($errors);
API::notFound('User not found');
API::cachedResponse($resource, $cacheKey);
API::paginatedCachedResponse($resource, $pageNumber);
API::clearCacheKey($cacheKey);
return API::response($data, 'Data retrieved successfully.', API::SUCCESS);
If $data is paginated, the response will automatically include pagination metadata:
{
"success": true,
"data": {
"items": [
{
"id": 1,
"name": "API Toolkit"
}
],
"meta": {
"current_page": 1,
"total_pages": 1,
"per_page": 10,
"total": 2
}
},
"message": "Data retrieved successfully."
}
Alternatively, explicitly return a paginated response:
return API::response()
->paginate($users, 'users')
->message('Users retrieved successfully.')
->toResponse();
Simplified exception handling with pre-defined methods for common scenarios:
catch (Exception $exception) {
return API::exception($exception, "Something went wrong", API::INTERNAL_SERVER_ERROR);
}
if ($exception instanceof ValidationException) {
return API::validationError($exception->errors());
}
if ($exception instanceof UnauthorizedException) {
return API::error('Unauthorized access', API::FORBIDDEN);
}
return API::error('Server error', API::INTERNAL_SERVER_ERROR);
Built-in utilities for managing file uploads, deletions, and generating file URLs.
$filePath = API::upload($file, 'uploads/documents', 'local');
API::deleteFile($filePath, 'local');
$url = API::fileUrl($filePath, 'local');
Effortlessly cache API responses using the cacheResponse method or the API facade.
$this:public function index()
{
return API::cacheResponse('users.index', function () {
return User::all();
}, 30); // Cache for 30 minutes
}
API Facade:return API::cachedResponse(User::all(), 'users.index');
API::clearCacheKey('users.index');
By offering both RestController methods and the API facade, this package empowers developers with flexible options
to build robust APIs. Whether you prefer extending the controller or using standalone helpers, the toolkit adapts to
your workflow.
The package includes pre-defined routes and methods to simplify common authentication tasks, ensuring seamless integration into your application.
To enable authentication routes, include the following line in your api.php:
Route::restifyAuth();
You can specify only the required routes:
Route::restifyAuth(['login', 'register']);
The following routes are available by default:
loginregisterforgotPasswordresetPasswordverifyEmailsendOtpverifyOtpchangePasswordA Postman collection is available to test the authentication endpoints. Download the Postman Collection here.
The package supports both Laravel Passport and Laravel Sanctum for authentication. To set up the desired method, run the following command:
php artisan RestApiKit:setup-auth
You can customize authentication controllers by publishing them to your project. Run the command below:
php artisan vendor:publish --tag=restify-AuthControllers
This will generate authentication controllers in the following directory:
app/Http/Controllers/RestApi/Auth
After publishing the controllers, update the config/restify.php file to define the correct namespace for your
authentication controllers.
The package includes a predefined API class with constants for common HTTP status codes:
APITOOLKIT provides various HTTP status codes as constants for convenience:
API::SUCCESS: 200API::CREATED: 201API::NO_CONTENT: 204API::BAD_REQUEST: 400API::UNAUTHORIZED: 401API::FORBIDDEN: 403API::NOT_FOUND: 404API::METHOD_NOT_ALLOWED: 405API::UNPROCESSABLE_ENTITY: 422API::INTERNAL_SERVER_ERROR: 500API::NOT_IMPLEMENTED: 501API::BAD_GATEWAY: 502API::SERVICE_UNAVAILABLE: 503You can define custom macros for reusable functionality. For example:
app(ActionMacroManager::class)->macro('greetUser', function ($name) {
return "Hello, {$name}!";
});
To run the package's tests, use the following command:
composer test
Contributions are welcome! Please see the CONTRIBUTING file for details.
If you discover any security-related issues, please email mhasnainjafri51214@gmail.com instead of using the issue
tracker.
This package is open-sourced software licensed under the MIT License. See the LICENSE file for more details.
This package boilerplate was generated using the Laravel Package Boilerplate.