PHPackages                             surazdott/api-response - 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. surazdott/api-response

ActivePackage

surazdott/api-response
======================

Laravel package for HTTP JSON response for API.

v1.2.3(1y ago)954↓100%1MITPHPPHP ^8.1

Since Sep 19Pushed 1y ago1 watchersCompare

[ Source](https://github.com/surazdott/api-response)[ Packagist](https://packagist.org/packages/surazdott/api-response)[ RSS](/packages/surazdott-api-response/feed)WikiDiscussions main Synced today

READMEChangelog (9)Dependencies (4)Versions (10)Used By (0)

 [![Laravel API Response](https://raw.githubusercontent.com/surazdott/api-response/main/art/example.png)](https://raw.githubusercontent.com/surazdott/api-response/main/art/example.png)

[![GitHub Workflow Status (main)](https://camo.githubusercontent.com/9f9db8fe11f4af54a272a92c80bf0206e160ecb5abee517085e3d518880de7b7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f737572617a646f74742f6170692d726573706f6e73652f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d726f756e642d737175617265)](https://github.com/surazdott/api-response/actions) [![Latest Version](https://camo.githubusercontent.com/d24c232c3747afc7999e6092b72d5822c1bcf2893ba1b077a77e0f9b9e8aacbc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f737572617a646f74742f6170692d726573706f6e7365)](https://packagist.org/packages/surazdott/api-response) [![License](https://camo.githubusercontent.com/acfe3682dcefe133c02a136b5701bcdb48c60190c3aeddb1ba149c5d25cb757b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f737572617a646f74742f6170692d726573706f6e7365)](https://packagist.org/packages/surazdott/api-response)

Laravel API Response
====================

[](#laravel-api-response)

Laravel API Response package simplifies the process of generating standardized JSON responses in Laravel applications. It provides a consistent and intuitive API through the package, offering a variety of methods to manage different types of HTTP responses effectively.

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

[](#installation)

> **Requires [PHP 8.1+](https://php.net/releases/)**

To install the package, you can use Composer:

```
composer require surazdott/api-response
```

You can publish the config, languages and resources from with the help of command.

```
php artisan vendor:publish --tag=api-response

```

Basic usage
-----------

[](#basic-usage)

After installing the package, you can use the Api facade or helper function to generate JSON responses in your controllers or anywhere within your application. The following methods are available:

#### Facade

[](#facade)

Generates a generic JSON response with facade.

```
use Api;

....

public function index()
{
    $posts = Post::take(10)->get();

    return Api::response('Data fetched successfully', $posts);
}
```

#### Helper function

[](#helper-function)

Generates a generic JSON response with helper function.

```
public function index()
{
    $posts = Post::take(10)->get();

    return api()->response('Data fetched successfully', $posts);
}
```

This is the result.

```
{
    "success": true,
    "message": "Data fetched successfully",
    "data": [
        {"title": "Post Title", ...}
    ]
}
```

### Methods

[](#methods)

#### `response`

[](#response)

Generates a generic JSON response with a customizable status code.

`response(string $message, mixed $data = [], int $status = 200)`

```
return api()->response('Operation completed successfully', $data = [], $status = 200);

// Result
{
    "success": true,
    "message": "Operation completed successfully",
    "data": []
}
```

#### `success`

[](#success)

Method for a successful operation with HTTP status code 200.

`success(string $message, mixed $data = [])`

```
public function index()
{
    $users = User::take(2)->get();

    return api()->success('Request processed successfully.', $users);
}

// Result
{
    "success": true,
    "message": "Request processed successfully.",
    "data": [
        {
            "id": 1",
            "name": "Suraj....",
        },
        {
            "id": 2",
            "name": "Rabin....",
        }
    ]
}
```

#### `paginate`

[](#paginate)

Return for a successful operation with HTTP paginated data.

`paginate(string $message, mixed $data = [])`

```
public function index()
{
    $users = UserResource::collection(User::active()->paginate(10));

    return api()->paginate('Data fetched successfully.', $users);
}

// Result
{
    "success": true,
    "message": "Data fetched successfully.",
    "data": [
        {
            "id": 1",
            "name": "Suraj....",
        },
        {
            "id": 2",
            "name": "Rabin....",
        }
    ],
    "links": {
        "first": "http://example.com/api/v1/users?page=1",
        "last": "http://example.com/api/v1/users?page=1",
        "prev": null,
        "next": null
    },
    "meta": {
        "total": 0,
        "current_page": 1,
        "total_pages": 1,
        "per_page": 10
    }
}
```

#### `created`

[](#created)

Returns a response indicating that a resource has been successfully created with HTTP status code 201.

`created(string $message, mixed $data = [])`

```
public function store()
{
    $user = User::create(['name' => 'Suraj']);

    return api()->created('Resource created successfully', $user);
}

// Result
{
    "success": true,
    "message": "Resource created successfully",
    "data": [
        {
            "id": 1,
            "name": "Suraj Datheputhe",
        }
    ]
}
```

#### `error`

[](#error)

Returns an error response with HTTP status code 4xx.

`error(string $message, int $status = 400)`

```
public function foo()
{
    return api()->error('Bad request');
}

// Result
{
    "success": false,
    "message": "Bad request"
}
```

#### `unauthorized`

[](#unauthorized)

Returns an unauthorized response with HTTP status code 401.

`unauthorized(string $message)`

```
public function edit()
{
    if ($user->isNotAdmin()) {
        return api()->unauthorized('Authentication is required to access this resource.');
    }
}

// Result
{
    "success": false,
    "message": "Authentication is required to access this resource"
}
```

#### `forbidden`

[](#forbidden)

Returns an unauthorized response with HTTP status code 401.

`forbidden(string $message)`

```
public function edit()
{
    if ($user->isNotAdmin()) {
        return api()->unauthorized('You do not have permission to access this resource.');
    }
}

// Result
{
    "success": false,
    "message": "You do not have permission to access this resource"
}
```

#### `notFound`

[](#notfound)

Returns a not found response with HTTP status code 404.

`notFound(string $message)`

```
public function edit()
{
    $post = Post::find(1);

    if (! $post) {
        return api()->notFound('Requested resource could not be found');
    }
}

// Result
{
    "success": false,
    "message": "Requested resource could not be found"
}
```

#### `notAllowed`

[](#notallowed)

Returns a method not allowed response with HTTP status code 405.

`notAllowed(string $message)`

```
Route::fallback(function() {
    return api()->notAllowed('Method type is not currently supported');
});

// Result
{
    "success": false,
    "message": "Method type is not currently supporte."
}
```

#### `validation`

[](#validation)

Generates a response indicating validation errors with HTTP status code 400.

`validation(string $message, mixed $errors = [])`

```
public function login()
{
    $validator = Validator::make($request->all(), [
        'email' => 'required',
        'password' => 'required',
    ]);

    if ($validator->fails()) {
        return api()->validation('Validation failed for the request.', $validator->errors());
    }
}

// Result
{
    "success": false,
    "message": "Validation failed for the request",
    "errors": {
        "password": [
            "The password field is required."
        ]
    }
}
```

#### `serverError`

[](#servererror)

Returns an error response with HTTP status code 4xx.

`serverError(string $message, int $status = 500)`

```
public function index()
{
    try {
        $users = \App\Models\User::find($id); // Undefined $id
    } catch (\Exception $e) {
        return api()->error('Invalid syntax for this request was provided');
    }
}

// Result
{
    "success": false,
    "message": "Invalid syntax for this request was provided"
}
```

Note: API response messages are predefined and can be changed from parameters or from the language file.

Request Validation
------------------

[](#request-validation)

Laravel's request validation can be used for both web and API. You can call the trait

`SurazDott\ApiResposne\Concerns\HasApiResponse;`

```
