├── .github ├── FUNDING.yml └── workflows │ ├── php.yml │ ├── test.yml │ └── tests.yml ├── .gitignore ├── .travis.yml ├── LICENSE.md ├── README.md ├── composer.json ├── config └── api.php ├── lang ├── .gitkeep └── en │ └── messages.php ├── phpunit.xml ├── src ├── ApiResponse.php ├── ApiResponseServiceProvider.php ├── Contracts │ └── ApiInterface.php ├── Facades │ └── API.php └── helpers.php └── tests ├── ErrorResponseTest.php ├── ForbiddenResponseTest.php ├── NotFoundResponseTest.php ├── OkResponseTest.php ├── ResponseTest.php ├── TestCase.php └── ValidationResponseTest.php /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | ko_fi: obiefy 2 | -------------------------------------------------------------------------------- /.github/workflows/php.yml: -------------------------------------------------------------------------------- 1 | name: PHP Composer 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | 13 | - name: Validate composer.json and composer.lock 14 | run: composer validate 15 | 16 | - name: Install dependencies 17 | run: composer install --prefer-dist --no-progress --no-suggest 18 | 19 | # Add a test script to composer.json, for instance: "test": "vendor/bin/phpunit" 20 | # Docs: https://getcomposer.org/doc/articles/scripts.md 21 | 22 | - name: Run test suite 23 | run: vendor/bin/phpunit 24 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - name: Run a one-line script 13 | run: echo Hello, world! 14 | - name: Run a multi-line script 15 | run: | 16 | echo Add other actions to build, 17 | echo test, and deploy your project. 18 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: PHP Composer 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | 17 | - name: Validate composer.json and composer.lock 18 | run: composer validate 19 | 20 | - name: Install dependencies 21 | run: composer install --prefer-dist --no-progress --no-suggest 22 | 23 | # Add a test script to composer.json, for instance: "test": "vendor/bin/phpunit" 24 | # Docs: https://getcomposer.org/doc/articles/scripts.md 25 | 26 | - name: Run test suite 27 | run: composer run-script test 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | vendor 2 | .idea 3 | .composer.lock 4 | .phpunit.result.cache 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | 3 | php: 4 | - 7.2 5 | 6 | before_script: 7 | - composer self-update 8 | - composer install --no-interaction 9 | 10 | script: 11 | - vendor/bin/phpunit -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Obay Hamed Idris 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel API Response 2 | 3 | ![Build Status](https://travis-ci.org/obiefy/api-response.svg?branch=master) 4 | [![StyleCI](https://github.styleci.io/repos/206981157/shield?branch=master)](https://github.styleci.io/repos/206981157) 5 | ![Packagist](https://img.shields.io/packagist/l/obiefy/api-response) ![Packagist Version](https://img.shields.io/packagist/v/obiefy/api-response) 6 | 7 | Simple Laravel API response wrapper. 8 | 9 | --- 10 | ![API response code sample](https://i.ibb.co/S5bLwKc/carbon.png) 11 | --- 12 | 13 | ## Installation 14 | 1. Install the package through composer: 15 | 16 | `$ composer require obiefy/api-response` 17 | 18 | 2. Register the package service provider to the providers array in `app.php` file: 19 | 20 | `Obiefy\API\ApiResponseServiceProvider::class` 21 | 22 | 3. Register the package facade alias to the aliases array in `app.php` file: 23 | 24 | `'API' => Obiefy\API\Facades\API::class,` 25 | 26 | 5. And finally you can publish the config file: 27 | 28 | `php artisan vendor:publish --tag=api-response` 29 | 30 | Note: You could also include "`use Obiefy\API\Facades\API;`" at the top of the class, but we recommend not to. 31 | 32 | ## Basic usage 33 | There are to ways of utilizing the package: using the `facade`, or using the `helper` function. 34 | On either way you will get the same result, it is totally up to you. 35 | 36 | #### Facade: 37 | ```php 38 | use API; 39 | 40 | ... 41 | 42 | public function index() 43 | { 44 | $users = User::latest()->take(5)->get(); 45 | 46 | return API::response(200, 'Latest 5 Users', $users); 47 | } 48 | ``` 49 | Note: If you decide not to register the service provider and the facade, alias then you need to include `use Obiefy\API\Facades\API;` at the top of the class, but we recommend not to. 50 | 51 | #### Helper function: 52 | ```php 53 | public function index() 54 | { 55 | $users = User::latest()->take(5)->get(); 56 | 57 | return api()->response(200, 'Latest 5 Users', $users); 58 | } 59 | ``` 60 | 61 | ## Advanced usage 62 | The `response()` method accepts three mandatory parameters: 63 | - `int $status` 64 | - `string $message` 65 | - `string | array $data` 66 | 67 | For example, in the below example we are calling the `response()` method thru the facade and we are passing the following parameters: `200` as the status code, `User list` as the message and `$users` (a collection of users) as the data. 68 | 69 | ```php 70 | use API; 71 | 72 | ... 73 | 74 | public function index() 75 | { 76 | $users = User::latest()->take(5)->get(); 77 | 78 | return API::response(200, 'Latest 5 Users', $users); 79 | } 80 | ``` 81 | This is the result: 82 | ```json 83 | { 84 | "STATUS": 200, 85 | "MESSAGE": "Latest 5 Users", 86 | "DATA": [ 87 | {"name": "Obay Adam", ...} 88 | ] 89 | } 90 | ``` 91 | 92 | If you need more data other than the defaults `STATUS`, `MESSAGE`, and `DATA` attributes on your json response, you could pass as many parameters as you need after `$data`. However, we do recommend formating the extra parameters as a `$key => $value` array. 93 | 94 | As you can see in the below example, we are calling the `api()` helper and we are passing the following parameters: `200` as the status code, `User list` as the message, `$users` (a collection of users) as the data, `$code` as a key value array and `$error` as another key value array. 95 | 96 | ```php 97 | public function index() 98 | { 99 | $users = User::latest()->take(5)->get(); 100 | $code = ['code' => 30566]; 101 | $error = ['error' => 'ERROR-2019-09-14']; 102 | 103 | return api()->response(200, 'Latest 5 Users', $users, $code, $error); 104 | } 105 | ``` 106 | This is the result: 107 | ```json 108 | { 109 | "STATUS": 200, 110 | "MESSAGE": "Latest 5 Users", 111 | "DATA": [ 112 | {"name": "Obay Adam", ...} 113 | ], 114 | "code": 30566, 115 | "error": "ERROR-2019-09-14" 116 | } 117 | ``` 118 | 119 | Another way of creating a response is by calling `api()` method and passing the parameters directly to the helper function. Again, it is up to you how you better want to use it. 120 | 121 | Check the below code example. 122 | 123 | ```php 124 | public function index() 125 | { 126 | $users = User::latest()->take(5)->get(); 127 | 128 | return api(200, 'Latest 5 Users', $users); 129 | } 130 | ``` 131 | This is the result: 132 | ```json 133 | { 134 | "STATUS": 200, 135 | "MESSAGE": "Latest 5 Users", 136 | "DATA": [ 137 | {"name": "Obay Adam", ...} 138 | ] 139 | } 140 | ``` 141 | 142 | ## Helper functions 143 | The package ships with a group of functions that will help you to speed up your development process. For example, you could call directly `api()->ok()` if the response was successful, instead of building the response. 144 | 145 | #### `function ok()` 146 | The `ok()` function can be used without passing any parameters, it will defaulted the status code to `200` and use the default message from the configuration file. 147 | 148 | ```php 149 | return api()->ok(); 150 | ``` 151 | Result: 152 | ```json 153 | { 154 | "STATUS": 200, 155 | "MESSAGE": "Process is successfully completed", 156 | "DATA": {} 157 | } 158 | ``` 159 | 160 | Or you could pass to the function a custom message and the data you need. In this case, as mentioned before, the `ok()` status code will be defaulted to 200. 161 | 162 | ```php 163 | $users = User::latest()->take(5)->get(); 164 | 165 | return api()->ok("User list", $users); 166 | ``` 167 | Result: 168 | ```json 169 | { 170 | "STATUS": 200, 171 | "MESSAGE": "User list", 172 | "DATA": [ 173 | {"name": "Obay Adam", ...} 174 | ] 175 | } 176 | ``` 177 | 178 | #### `function notFound()` 179 | The `notFound()` function, as its name states, should be used for the case when the resource is not found and the status code will be defaulted to `404`. You could pass a custom message to this function otherwise it will use the default message from the configuration file. 180 | 181 | ```php 182 | return api()->notFound(); 183 | ``` 184 | 185 | #### `function validation()` 186 | The `validation()` function can be used on the case of a validation error exist, throwing a 422 status code by default. It accepts two mandatory parameters: a message and an array of errors, and as many extra parameters you need (we recommend a key value array format). If the message is empty, then the default message will be used instead. 187 | 188 | ```php 189 | return api()->validation('These fields are required.', ['name', 'lastName']); 190 | ``` 191 | 192 | #### `function error()` 193 | The `error()` function can be used when an internal server error occurs throwing a 500 status code by default. It accepts two mandatory parameters: a message and an array of errors, and as many extra parameters you need (we recommend a key value array format). If the message is empty, then the default message will be used instead. 194 | 195 | ## Configuration 196 | 197 | ### JSON Response Labels 198 | If you need to customize the default messages or the json response labels, you can do it directly on the `api.php` configuration file. 199 | 200 | |method| default status code | change code | message | 201 | |--|--| -- | --- | 202 | |`ok()`| 200 |`config('api.codes.success)` | `trans('api-response::messages.success)` 203 | |`notFound()`| 404 |`config('api.codes.notfound)` | `trans('api-response::messages.notfound)` 204 | |`validation()`| 422 |`config('api.codes.validation)` | `trans('api-response::messages.validation)` 205 | |`error()`| 500 |`config('api.codes.error)` | `trans('api-response::messages.error)` 206 | 207 | ### Matching Status Codes 208 | By default, all API responses return a 200 OK HTTP status header. If you'd like the status header to match the Response's status, set the `matchstatus` configuration to `true` 209 | 210 | ### Include The Count Of Data 211 | You can optionally include the count of the `DATA` portion of the response, by setting `includeDataCount` to `true` in the `api.php` configuration file. You can also override the label, if desired, by updating the label in the`keys` array of the configuration file. 212 | 213 | ```json 214 | { 215 | "STATUS": "200", 216 | "MESSAGE": "User Profile data", 217 | "DATA": [ 218 | ... 219 | ], 220 | "DATACOUNT": 6 221 | } 222 | ``` 223 | 224 | ## Contributing 225 | We will be happy if we see PR from you. 226 | 227 | ## License 228 | The API Response is a free package released under the MIT License. 229 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "obiefy/api-response", 3 | "type": "library", 4 | "description": "Simple Laravel package to return Json responses.", 5 | "keywords": [ 6 | "api", 7 | "response", 8 | "laravel", 9 | "json", 10 | "php", 11 | "restful", 12 | "RESTful API" 13 | ], 14 | "homepage": "https://github.com/obiefy/api-response", 15 | "license": "MIT", 16 | "minimum-stability": "stable", 17 | "authors": [ 18 | { 19 | "name": "Obiefy", 20 | "email": "obayhamed@gmail.com", 21 | "homepage": "http://obay-dev.com", 22 | "role": "Creator & Maintainer" 23 | } 24 | ], 25 | "require": { 26 | "php" : "^7.3|^8.0", 27 | "illuminate/support": "^10.0|^9.0|^8.0|^7.0|^6.0|^5.5" 28 | }, 29 | "require-dev": { 30 | "phpunit/phpunit": "^10.0", 31 | "orchestra/testbench": "^7.0" 32 | }, 33 | "autoload": { 34 | "psr-4": { 35 | "Obiefy\\API\\": "src/" 36 | } 37 | }, 38 | "autoload-dev": { 39 | "psr-4": { 40 | "Obiefy\\API\\Tests\\": "tests/" 41 | }, 42 | "files": [ 43 | "src/helpers.php" 44 | ] 45 | }, 46 | "scripts": { 47 | "test": "vendor/bin/phpunit" 48 | }, 49 | "extra": { 50 | "laravel": { 51 | "providers": [ 52 | "Obiefy\\API\\ApiResponseServiceProvider" 53 | ], 54 | "aliases": { 55 | "API": "Obiefy\\API\\Facades\\API" 56 | } 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /config/api.php: -------------------------------------------------------------------------------- 1 | true, 9 | 10 | /* 11 | * Set the status code from the json response to be the same as the status code 12 | * in the json response's body. 13 | */ 14 | 'match_status' => false, 15 | 16 | /* 17 | * Include the count of the "data" in the JSON response 18 | */ 19 | 'include_data_count' => false, 20 | 21 | /* 22 | * Json response's body labels. 23 | */ 24 | 'keys' => [ 25 | 'status' => 'STATUS', 26 | 'message' => 'MESSAGE', 27 | 'data' => 'DATA', 28 | 'data_count' => 'DATA_COUNT', 29 | ], 30 | 31 | ]; 32 | -------------------------------------------------------------------------------- /lang/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/obiefy/api-response/f952200782409a421b8fb8828c22eebc6d4f8e64/lang/.gitkeep -------------------------------------------------------------------------------- /lang/en/messages.php: -------------------------------------------------------------------------------- 1 | 'Process is successfully completed', 5 | 'notfound' => 'Sorry no results query for your request.', 6 | 'validation' => 'Validation Failed please check the request attributes and try again.', 7 | 'forbidden' => 'You don\'t have permission to access this content.', 8 | 'error' => 'Server error, please try again later', 9 | ]; 10 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | tests 15 | 16 | 17 | 18 | 19 | src/ 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/ApiResponse.php: -------------------------------------------------------------------------------- 1 | config('api.stringify') ? strval($status) : $status, 33 | config('api.keys.message') => $message, 34 | config('api.keys.data') => $data, 35 | ]; 36 | 37 | if (is_countable($data) && config('api.include_data_count', false) && !empty($data)) { 38 | $json = array_merge($json, [config('api.keys.data_count') => config('api.stringify') ? strval(count($data)) : count($data)]); 39 | } 40 | 41 | if ($extraData) { 42 | foreach ($extraData as $extra) { 43 | $json = array_merge($json, $extra); 44 | } 45 | } 46 | 47 | return (config('api.match_status')) ? response()->json($json, $status) : response()->json($json); 48 | } 49 | 50 | /** 51 | * Create successful (200) API response. 52 | * 53 | * @param string $message 54 | * @param array $data 55 | * @param array $extraData 56 | * 57 | * @return JsonResponse 58 | */ 59 | public function ok($message = null, $data = [], ...$extraData) 60 | { 61 | if (is_null($message)) { 62 | $message = trans('api-response::messages.success'); 63 | } 64 | 65 | return $this->response(static::HTTP_OK, $message, $data, ...$extraData); 66 | } 67 | 68 | /** 69 | * Create successful (200) API response. 70 | * 71 | * @param string $message 72 | * @param array $data 73 | * @param array $extraData 74 | * 75 | * @return JsonResponse 76 | */ 77 | public function success($message = null, $data = [], ...$extraData) 78 | { 79 | return $this->ok($message, $data, ...$extraData); 80 | } 81 | 82 | /** 83 | * Create Not found (404) API response. 84 | * 85 | * @param string $message 86 | * 87 | * @return JsonResponse 88 | */ 89 | public function notFound($message = null) 90 | { 91 | if (is_null($message)) { 92 | $message = trans('api-response::messages.notfound'); 93 | } 94 | 95 | return $this->response(static::HTTP_NOT_FOUND, $message, []); 96 | } 97 | 98 | /** 99 | * Create Validation (422) API response. 100 | * 101 | * @param string $message 102 | * @param array $errors 103 | * @param array $extraData 104 | * 105 | * @return JsonResponse 106 | */ 107 | public function validation($message = null, $errors = [], ...$extraData) 108 | { 109 | if (is_null($message)) { 110 | $message = trans('api-response::messages.validation'); 111 | } 112 | 113 | return $this->response(static::HTTP_UNPROCESSABLE_ENTITY, $message, $errors, ...$extraData); 114 | } 115 | 116 | /** 117 | * Create Validation (422) API response. 118 | * 119 | * @param string $message 120 | * @param array $data 121 | * @param array $extraData 122 | * 123 | * @return JsonResponse 124 | */ 125 | public function forbidden($message = null, $data = [], ...$extraData) 126 | { 127 | if (is_null($message)) { 128 | $message = trans('api-response::messages.forbidden'); 129 | } 130 | 131 | return $this->response(static::HTTP_FORBIDDEN, $message, $data, ...$extraData); 132 | } 133 | 134 | /** 135 | * Create Server error (500) API response. 136 | * 137 | * @param string $message 138 | * @param array $data 139 | * @param array $extraData 140 | * 141 | * @return JsonResponse 142 | */ 143 | public function error($message = null, $data = [], ...$extraData) 144 | { 145 | if (is_null($message)) { 146 | $message = trans('api-response::messages.error'); 147 | } 148 | 149 | return $this->response(static::HTTP_INTERNAL_SERVER_ERROR, $message, $data, ...$extraData); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/ApiResponseServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->bind(ApiInterface::class, function () { 18 | return new ApiResponse(); 19 | }); 20 | } 21 | 22 | /** 23 | * Bootstrap API resources. 24 | * 25 | * @return void 26 | */ 27 | public function boot() 28 | { 29 | $this->setupConfig(); 30 | 31 | $this->setupTranslations(); 32 | 33 | $this->registerHelpers(); 34 | 35 | $this->publishes([ 36 | __DIR__.'/../config/api.php' => config_path('api.php'), 37 | ], 'api-response'); 38 | } 39 | 40 | /** 41 | * Set Config files. 42 | */ 43 | protected function setupConfig() 44 | { 45 | $path = realpath($raw = __DIR__.'/../config/api.php') ?: $raw; 46 | $this->mergeConfigFrom($path, 'api'); 47 | } 48 | 49 | /** 50 | * Register helpers. 51 | */ 52 | protected function registerHelpers() 53 | { 54 | if (file_exists($helperFile = __DIR__.'/helpers.php')) { 55 | require_once $helperFile; 56 | } 57 | } 58 | 59 | private function setupTranslations() 60 | { 61 | $this->loadTranslationsFrom(__DIR__.'/../lang', 'api-response'); 62 | 63 | $this->publishes([ 64 | __DIR__.'/../lang' => $this->app->langPath('vendor/api-response'), 65 | ]); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/Contracts/ApiInterface.php: -------------------------------------------------------------------------------- 1 | response($status, $message, $data, ...$extraData); 26 | } 27 | } 28 | 29 | if (!function_exists('ok')) { 30 | 31 | /** 32 | * Return success response. 33 | * 34 | * @param string $message 35 | * @param array $data 36 | * @param array $extraData 37 | * 38 | * @return JsonResponse 39 | */ 40 | function ok($message = '', $data = [], ...$extraData) 41 | { 42 | return api()->ok($message, $data, ...$extraData); 43 | } 44 | } 45 | 46 | if (!function_exists('success')) { 47 | 48 | /** 49 | * Return success response. 50 | * 51 | * @param string $message 52 | * @param array $data 53 | * @param array $extraData 54 | * 55 | * @return JsonResponse 56 | */ 57 | function success($message = '', $data = [], ...$extraData) 58 | { 59 | return api()->success($message, $data, ...$extraData); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /tests/ErrorResponseTest.php: -------------------------------------------------------------------------------- 1 | error()->getContent(); 11 | $expectedResponse = [ 12 | 'STATUS' => 500, 13 | 'MESSAGE' => trans('api-response::messages.error'), 14 | 'DATA' => [], 15 | ]; 16 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 17 | } 18 | 19 | /** @test */ 20 | public function it_returns_error_with_passed_parameters() 21 | { 22 | $response = api() 23 | ->error('error Accord, try later.', ['reference_code' => 345]) 24 | ->getContent(); 25 | $expectedResponse = [ 26 | 'STATUS' => 500, 27 | 'MESSAGE' => 'error Accord, try later.', 28 | 'DATA' => ['reference_code' => 345], 29 | ]; 30 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/ForbiddenResponseTest.php: -------------------------------------------------------------------------------- 1 | forbidden()->getContent(); 11 | $expectedResponse = [ 12 | 'STATUS' => 403, 13 | 'MESSAGE' => trans('api-response::messages.forbidden'), 14 | 'DATA' => [], 15 | ]; 16 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 17 | } 18 | 19 | /** @test */ 20 | public function it_returns_forbidden_with_passed_parameters() 21 | { 22 | $response = api() 23 | ->forbidden('No access.', ['reference_code' => 345]) 24 | ->getContent(); 25 | $expectedResponse = [ 26 | 'STATUS' => 403, 27 | 'MESSAGE' => 'No access.', 28 | 'DATA' => ['reference_code' => 345], 29 | ]; 30 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/NotFoundResponseTest.php: -------------------------------------------------------------------------------- 1 | notFound('No results for your query')->getContent(); 13 | $expectedResponse = [ 14 | 'MESSAGE' => 'No results for your query', 15 | 'STATUS' => 404, 16 | 'DATA' => [], 17 | ]; 18 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 19 | } 20 | 21 | /** @test */ 22 | public function it_returns_404_response_with_default_config_message() 23 | { 24 | $response = api()->notFound()->getContent(); 25 | $expectedResponse = [ 26 | 'MESSAGE' => trans('api-response::messages.notfound'), 27 | 'STATUS' => 404, 28 | 'DATA' => [], 29 | ]; 30 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/OkResponseTest.php: -------------------------------------------------------------------------------- 1 | getContent(); 14 | $expectedResponse = [ 15 | 'MESSAGE' => 'this is message', 16 | 'STATUS' => 200, 17 | 'DATA' => [], 18 | ]; 19 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 20 | } 21 | 22 | /** @test */ 23 | public function it_returns_ok_response_from_helper_function() 24 | { 25 | $response = api()->ok('this is message', [])->getContent(); 26 | $expectedResponse = [ 27 | 'MESSAGE' => 'this is message', 28 | 'STATUS' => 200, 29 | 'DATA' => [], 30 | ]; 31 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 32 | } 33 | 34 | /** @test */ 35 | public function it_returns_ok_response_from_success_helper_function() 36 | { 37 | $response = api()->success('this is message', [])->getContent(); 38 | $expectedResponse = [ 39 | 'MESSAGE' => 'this is message', 40 | 'STATUS' => 200, 41 | 'DATA' => [], 42 | ]; 43 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 44 | } 45 | 46 | /** @test */ 47 | public function it_returns_ok_response_from_ok_helper_function() 48 | { 49 | $response = ok('this is message', [])->getContent(); 50 | $expectedResponse = [ 51 | 'MESSAGE' => 'this is message', 52 | 'STATUS' => 200, 53 | 'DATA' => [], 54 | ]; 55 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 56 | } 57 | 58 | /** @test */ 59 | public function it_returns_ok_response_from_success_alias_helper_function() 60 | { 61 | $response = success('this is message', [])->getContent(); 62 | $expectedResponse = [ 63 | 'MESSAGE' => 'this is message', 64 | 'STATUS' => 200, 65 | 'DATA' => [], 66 | ]; 67 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 68 | } 69 | 70 | /** @test */ 71 | public function it_returns_ok_response_with_default_message() 72 | { 73 | $response = api()->ok()->getContent(); 74 | $expectedResponse = [ 75 | 'MESSAGE' => trans('api-response::messages.success'), 76 | 'STATUS' => 200, 77 | 'DATA' => [], 78 | ]; 79 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 80 | } 81 | 82 | /** @test */ 83 | public function it_returns_count_if_enabled_and_countable() 84 | { 85 | config()->set('api.include_data_count', true); 86 | $response = api()->ok('User list', ['name1' => 'name1', 'name2' => 'name2'])->getContent(); 87 | $this->assertEquals(true, property_exists(json_decode($response), 'DATA_COUNT')); 88 | $this->assertEquals(2, json_decode($response, 1)['DATA_COUNT']); 89 | } 90 | 91 | /** @test */ 92 | public function it_does_not_return_count_if_enabled_and_not_countable() 93 | { 94 | config()->set('api.include_data_count', true); 95 | $response = api()->ok('User list', [])->getContent(); 96 | $this->assertEquals(false, property_exists(json_decode($response), 'DATA_COUNT')); 97 | } 98 | 99 | /** @test */ 100 | public function user_can_change_default_data_count_name() 101 | { 102 | config()->set('api.include_data_count', true); 103 | config()->set('api.keys.data_count', 'count_of_data'); 104 | $response = api()->ok('User list', ['name1' => 'name1', 'name2' => 'name2'])->getContent(); 105 | $this->assertEquals(true, property_exists(json_decode($response), 'count_of_data')); 106 | } 107 | 108 | /** @test */ 109 | public function it_returns_count_as_a_string_if_enabled() 110 | { 111 | config()->set('api.include_data_count', true); 112 | config()->set('api.stringify', true); 113 | 114 | $response = api()->ok('User list', ['name1' => 'name1', 'name2' => 'name2'])->getContent(); 115 | $this->assertIsString(json_decode($response, 1)['DATA_COUNT']); 116 | $this->assertEquals(true, 2, json_decode($response, 1)['DATA_COUNT']); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /tests/ResponseTest.php: -------------------------------------------------------------------------------- 1 | assertInstanceOf(JsonResponse::class, $response); 17 | } 18 | 19 | /** @test */ 20 | public function it_returns_response_object_with_object() 21 | { 22 | $data = new stdClass(); 23 | $data->foo = 'foo'; 24 | $data->bar = 'bar'; 25 | $data->baz = 'baz'; 26 | $response = API::response(200, 'New Response', $data); 27 | $this->assertInstanceOf(JsonResponse::class, $response); 28 | } 29 | 30 | /** @test */ 31 | public function user_can_edit_default_response_keys() 32 | { 33 | config()->set('api.keys', [ 34 | 'status' => 'newStatus', 35 | 'message' => 'newMessage', 36 | 'data' => 'newData', 37 | ]); 38 | 39 | $response = api()->ok()->getContent(); 40 | $expectedResponse = [ 41 | 'newStatus' => 200, 42 | 'newMessage' => trans('api-response::messages.success'), 43 | 'newData' => [], 44 | ]; 45 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 46 | } 47 | 48 | /** @test */ 49 | public function it_returns_string_api_status_code() 50 | { 51 | $response = api()->ok()->getContent(); 52 | 53 | $this->assertIsString(json_decode($response, 1)['STATUS']); 54 | } 55 | 56 | /** @test */ 57 | public function user_can_edit_default_stringify_setting() 58 | { 59 | config()->set('api.stringify', false); 60 | 61 | $response = api()->ok()->getContent(); 62 | 63 | $this->assertIsInt(json_decode($response, 1)['STATUS']); 64 | } 65 | 66 | /** @test */ 67 | public function it_returns_response_from_base_helper_function() 68 | { 69 | $response = api(403, 'Forbidden response message', [])->getContent(); 70 | $expectedResponse = [ 71 | 'STATUS' => 403, 72 | 'MESSAGE' => 'Forbidden response message', 73 | 'DATA' => [], 74 | ]; 75 | 76 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 77 | } 78 | 79 | /** @test */ 80 | public function it_returns_extra_parameters() 81 | { 82 | // using the api()->response() 83 | $response = api()->response( 84 | 200, 85 | 'New Response', 86 | ['name' => 'Joe Doe'], 87 | ['code' => 30566], 88 | ['reference' => 'ERROR-2019-09-14'] 89 | )->getContent(); 90 | $expectedResponse = [ 91 | 'STATUS' => 200, 92 | 'MESSAGE' => 'New Response', 93 | 'DATA' => ['name' => 'Joe Doe'], 94 | 'code' => 30566, 95 | 'reference' => 'ERROR-2019-09-14', 96 | ]; 97 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 98 | 99 | // using the facade 100 | $response = API::response( 101 | 200, 102 | 'New Response', 103 | ['name' => 'Joe Doe'], 104 | ['code' => 30566], 105 | ['reference' => 'ERROR-2019-09-14'] 106 | )->getContent(); 107 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 108 | 109 | // using api() directly 110 | $response = api( 111 | 200, 112 | 'New Response', 113 | ['name' => 'Joe Doe'], 114 | ['code' => 30566], 115 | ['reference' => 'ERROR-2019-09-14'] 116 | )->getContent(); 117 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 118 | 119 | // extra data as part of the same array 120 | $response = api()->response( 121 | 200, 122 | 'New Response', 123 | ['name' => 'Joe Doe'], 124 | ['code' => 30566, 'reference' => 'ERROR-2019-09-14'] 125 | )->getContent(); 126 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 127 | } 128 | 129 | // TODO (3 test): test validation errors, default message validation, serer error response 130 | } 131 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | app->register(ApiResponseServiceProvider::class); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tests/ValidationResponseTest.php: -------------------------------------------------------------------------------- 1 | validation()->getContent(); 11 | $expectedResponse = [ 12 | 'MESSAGE' => 'Validation Failed please check the request attributes and try again.', 13 | 'STATUS' => 422, 14 | 'DATA' => [], 15 | ]; 16 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 17 | } 18 | 19 | /** @test */ 20 | public function it_returns_validation_failed_response_with_passed_data() 21 | { 22 | $response = api()->validation('Name field is required, please check and try again.', ['name' => 'name field is required'])->getContent(); 23 | $expectedResponse = [ 24 | 'MESSAGE' => 'Name field is required, please check and try again.', 25 | 'STATUS' => 422, 26 | 'DATA' => ['name' => 'name field is required'], 27 | ]; 28 | 29 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 30 | } 31 | 32 | /** @test */ 33 | public function it_returns_validation_response_with_default_data() 34 | { 35 | $response = api()->validation()->getContent(); 36 | $expectedResponse = [ 37 | 'STATUS' => 422, 38 | 'MESSAGE' => trans('api-response::messages.validation'), 39 | 'DATA' => [], 40 | ]; 41 | 42 | $this->assertEquals($expectedResponse, json_decode($response, 1)); 43 | } 44 | } 45 | --------------------------------------------------------------------------------