PHPackages                             mhasnainjafri/restapikit - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. mhasnainjafri/restapikit

ActiveLibrary[API Development](/categories/api)

mhasnainjafri/restapikit
========================

Unlock the full potential of your REST API development with RestApiKit. This powerful toolkit offers a variety of utilities to simplify the process of creating, testing, and managing REST APIs. From automatic documentation generation to built-in validation, RestApiKit provides a seamless workflow for developers looking to build reliable and scalable APIs with ease. Focus more on the logic, and let RestApiKit handle the heavy lifting.

v1.0.4(1y ago)0681MITPHPPHP ^8.0|^8.2|^8.3CI failing

Since Jan 22Pushed 1y ago1 watchersCompare

[ Source](https://github.com/MHasnainJafri/RestApiKit)[ Packagist](https://packagist.org/packages/mhasnainjafri/restapikit)[ Docs](https://github.com/mhasnainjafri/restapikit)[ RSS](/packages/mhasnainjafri-restapikit/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (4)Versions (8)Used By (0)

Introduction
------------

[](#introduction)

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.

---

Features
--------

[](#features)

- **Uniform API Responses**: Standardized success, error, and paginated responses.
- **Exception Handling**: Beautifully formatted error responses for various exception types.
- **File Management**: Easy file upload, deletion, and URL generation.
- **Built-in Authentication**: Includes login, registration, password reset (via email or OTP), and email verification.
- **Caching**: Simplified caching for API responses.
- **Customizable HTTP Status Codes**: Predefined constants for common HTTP status codes.

---

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require mhasnainjafri/restapikit
```

---

Usage
-----

[](#usage)

### Extending the `RestController`

[](#extending-the-restcontroller)

To 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);
    }

}
```

---

Functionalities
---------------

[](#functionalities)

### 1. **Uniform API Responses**

[](#1-uniform-api-responses)

The package provides a consistent structure for API responses. For example:

#### Success Response

[](#success-response)

```
return $this->response($data, 'Data retrieved successfully.', API::SUCCESS);
```

#### Paginated Response

[](#paginated-response)

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();
```

---

### 2. **Exception Handling**

[](#2-exception-handling)

The package simplifies exception handling by providing pre-defined methods for common scenarios:

#### General Exception

[](#general-exception)

```
catch (Exception $exception) {
return $this->exception($exception, "Something went wrong", API::INTERNAL_SERVER_ERROR);
}
```

#### Validation Exception

[](#validation-exception)

```
if ($exception instanceof ValidationException) {
return $this->response()
->errors($exception->errors())
->status(API::UNPROCESSABLE_ENTITY);
}
```

#### Unauthorized Access

[](#unauthorized-access)

```
if ($exception instanceof UnauthorizedException) {
return $this->response()
->message('Unauthorized access')
->status(API::FORBIDDEN);
}
```

#### Server Error

[](#server-error)

```
return $this->response()
->message('Server error')
->status(API::INTERNAL_SERVER_ERROR);
```

---

### 3. **File Management**

[](#3-file-management)

The package includes utilities for file uploads, deletions, and URL generation.

#### Upload a File

[](#upload-a-file)

```
$filePath = $this->upload($file, 'uploads/documents', 'local');
```

#### Delete a File

[](#delete-a-file)

```
$this->deleteFile($filePath, 'local');
```

#### Generate File URL

[](#generate-file-url)

```
$url = $this->fileUrl($filePath, 'local');
```

---

### 4. **Caching API Responses**

[](#4-caching-api-responses)

The `cacheResponse` method allows you to cache API responses for a specified duration.

#### Example:

[](#example)

```
public function index()
{
return $this->cacheResponse('users.index', function () {
return User::all();
}, 30); // Cache for 30 minutes
}
```

### 1. **Response Handling Without Controller Extension**

[](#1-response-handling-without-controller-extension)

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);
```

#### **Success Response**

[](#success-response-1)

```
return API::response($data, 'Data retrieved successfully.', API::SUCCESS);
```

#### **Paginated Response**

[](#paginated-response-1)

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();
```

### 2. **Exception Handling**

[](#2-exception-handling-1)

Simplified exception handling with pre-defined methods for common scenarios:

#### **General Exception**

[](#general-exception-1)

```
catch (Exception $exception) {
return API::exception($exception, "Something went wrong", API::INTERNAL_SERVER_ERROR);
}
```

#### **Validation Exception**

[](#validation-exception-1)

```
if ($exception instanceof ValidationException) {
return API::validationError($exception->errors());
}
```

#### **Unauthorized Access**

[](#unauthorized-access-1)

```
if ($exception instanceof UnauthorizedException) {
return API::error('Unauthorized access', API::FORBIDDEN);
}
```

#### **Server Error**

[](#server-error-1)

```
return API::error('Server error', API::INTERNAL_SERVER_ERROR);
```

### 3. **File Management**

[](#3-file-management-1)

Built-in utilities for managing file uploads, deletions, and generating file URLs.

#### **Upload a File**

[](#upload-a-file-1)

```
$filePath = API::upload($file, 'uploads/documents', 'local');
```

#### **Delete a File**

[](#delete-a-file-1)

```
API::deleteFile($filePath, 'local');
```

#### **Generate File URL**

[](#generate-file-url-1)

```
$url = API::fileUrl($filePath, 'local');
```

### 4. **Caching API Responses**

[](#4-caching-api-responses-1)

Effortlessly cache API responses using the `cacheResponse` method or the `API` facade.

#### Example with `$this`:

[](#example-with-this)

```
public function index()
{
return API::cacheResponse('users.index', function () {
return User::all();
}, 30); // Cache for 30 minutes
}
```

#### Example with `API` Facade:

[](#example-with-api-facade)

```
return API::cachedResponse(User::all(), 'users.index');
```

#### Clear Cache:

[](#clear-cache)

```
API::clearCacheKey('users.index');
```

---

### Notes

[](#notes)

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.

---

### **5. Built-in Authentication**

[](#5-built-in-authentication)

The package includes pre-defined routes and methods to simplify common authentication tasks, ensuring seamless integration into your application.

#### **Available Routes**

[](#available-routes)

To enable authentication routes, include the following line in your `api.php`:

```
Route::restifyAuth();
```

##### **Customizing Routes**

[](#customizing-routes)

You can specify only the required routes:

```
Route::restifyAuth(['login', 'register']);
```

##### **Supported Authentication Routes**

[](#supported-authentication-routes)

The following routes are available by default:

- **`login`**
- **`register`**
- **`forgotPassword`**
- **`resetPassword`**
- **`verifyEmail`**
- **`sendOtp`**
- **`verifyOtp`**
- **`changePassword`**

---

#### **Postman Collection**

[](#postman-collection)

A Postman collection is available to test the authentication endpoints. [Download the Postman Collection here](#).

---

#### **Authentication Methods**

[](#authentication-methods)

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
```

---

#### **Publishing Authentication Controllers**

[](#publishing-authentication-controllers)

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.

---

### 6. **HTTP Status Codes**

[](#6-http-status-codes)

The package includes a predefined `API` class with constants for common HTTP status codes:

Constants
---------

[](#constants)

APITOOLKIT provides various HTTP status codes as constants for convenience:

- `API::SUCCESS`: 200
- `API::CREATED`: 201
- `API::NO_CONTENT`: 204
- `API::BAD_REQUEST`: 400
- `API::UNAUTHORIZED`: 401
- `API::FORBIDDEN`: 403
- `API::NOT_FOUND`: 404
- `API::METHOD_NOT_ALLOWED`: 405
- `API::UNPROCESSABLE_ENTITY`: 422
- `API::INTERNAL_SERVER_ERROR`: 500
- `API::NOT_IMPLEMENTED`: 501
- `API::BAD_GATEWAY`: 502
- `API::SERVICE_UNAVAILABLE`: 503

---

### 7. **Custom Macros**

[](#7-custom-macros)

You can define custom macros for reusable functionality. For example:

#### Example Macro:

[](#example-macro)

```
app(ActionMacroManager::class)->macro('greetUser', function ($name) {
return "Hello, {$name}!";
});
```

---

**Todo list**
-------------

[](#todo-list)

1. Logger

Testing
-------

[](#testing)

To run the package's tests, use the following command:

```
composer test
```

---

Contributing
------------

[](#contributing)

Contributions are welcome! Please see the [CONTRIBUTING](CONTRIBUTING.md) file for details.

---

Security
--------

[](#security)

If you discover any security-related issues, please email `mhasnainjafri51214@gmail.com` instead of using the issue tracker.

---

License
-------

[](#license)

This package is open-sourced software licensed under the **MIT License**. See the [LICENSE](LICENSE.md) file for more details.

---

Credits
-------

[](#credits)

- **Author**: [Muhammad Hasnain](https://github.com/mhasnainjafri)
- **Contributors**: [All Contributors](../../contributors)

---

This package boilerplate was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com).

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance49

Moderate activity, may be stable

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~23 days

Total

5

Last Release

381d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0ac8f0e9f8ab4ade84cb363584a9d19051b1b0c412818d111ed1141795a02aca?d=identicon)[MHasnainJafri](/maintainers/MHasnainJafri)

---

Top Contributors

[![MHasnainJafri](https://avatars.githubusercontent.com/u/118059753?v=4)](https://github.com/MHasnainJafri "MHasnainJafri (21 commits)")

---

Tags

spatielaravel-query-builderlaravel-json-api-paginateapitoolkitmhasnainjafrirestapikit

### Embed Badge

![Health badge](/badges/mhasnainjafri-restapikit/health.svg)

```
[![Health](https://phpackages.com/badges/mhasnainjafri-restapikit/health.svg)](https://phpackages.com/packages/mhasnainjafri-restapikit)
```

###  Alternatives

[spatie/laravel-query-builder

Easily build Eloquent queries from API requests

4.4k26.9M220](/packages/spatie-laravel-query-builder)[spatie/laravel-json-api-paginate

A paginator that plays nice with the JSON API spec

6314.7M46](/packages/spatie-laravel-json-api-paginate)[spatie/laravel-enum

Laravel Enum support

3655.4M31](/packages/spatie-laravel-enum)[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[spatie/laravel-route-discovery

Auto register routes using PHP attributes

23645.0k2](/packages/spatie-laravel-route-discovery)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
