Looking to hire Laravel developers? Try LaraJobs

laravel-api-response-provider maintained by holocronit

Description
Laravel Provider library for implementing structured responses to API calls
Author
Last update
2023/04/07 09:49 (dev-master)
License
Downloads
22

Comments
comments powered by Disqus

larevel-api-response-provider

Laravel Provider library for implementing structured responses to API calls

This library helps in the standardized generation of responses of any API layer. It also provides utilities for multi-language support of error responses

The library takes care to always guarantee a "status" key containing the logical result of the operation. In the case of "status" to false, the "error" object containing "code" and "description" will always be present. Here are some examples

// Success operation message
{
    "status" : true,
    "foo" : "bar"
}

// Error operation message
{
    "status" : false,
    "error" : {
        "code" : 10,
        "desc" : "Error description message"
    }
}

Installation

composer require laravel-api-response-provider

php artisan vendor:publish --tag=errors-config

Configuration

Add new service provider to the providers’ array as shown below.

'providers' => [
     ...,
     App\Providers\RouteServiceProvider::class,
     // Our new package class
     Holocronit\LaravelApiResponseProvider\responseProvider::class,
 ],

How to use

//Remember to import the library
use Holocronit\LaravelApiResponseProvider\responseProvider;


$responseProvider = new responseProvider();

//First parameter is the DATA, the second parameter is the KEY
$responseProvider->addData('foo',"bar");
return response()->json($responseProvider->getResponseData());

// With error

$responseProvider = new responseProvider();


$responseProvider->inError(10, "My custom error message");
// OR
$responseProvider->inError(1); // If not specified, the message will be taken from the preloaded catalog for the current locale. This is useful if you have errors common to multiple methods

return response()->json($responseProvider->getResponseData());


// With custom locale
$responseProvider = new responseProvider();
$responseProvider->loadErrorListForLocale('it');
// Default locale is "en".

$responseProvider->inError(1);
return response()->json($responseProvider->getResponseData());
    

Update error list

Update and add your own custom errors in the published file errors_list.json in Config Path with your custom locale.


{
	"en": {
		"1": "Generic error",
		"2": "Empty token"
	},
	"it": {
		"1": "Errore generico"
	}
}