A Laravel package designed to simplify the creation of structured and formatted API responses (JSON, XML) with custom status codes, messages, and data. XML support is currently under construction.
How to Use Overview of the most commonly used methods and their brief descriptions.
Ensure your project meets the following requirements before using this package:
With these features in place, lets dive into the installation process!
To integrate the Laravel API Response Builder into your Laravel project, follow these steps:
Run the following command in your terminal:
composer require danilowa/laravel-api-response-builder
After installation, publish the configuration file:
php artisan vendor:publish --provider="Danilowa\LaravelResponseBuilder\Providers\ResponseBuilderServiceProvider"
This will create a configuration file at config/responsebuilder.php
, where you can customize the package settings.
Open the config/responsebuilder.php
file and adjust the settings as needed for your project. Configure options such as data wrappers, API key headers, and logging preferences.
With the configuration in place, your package is ready to go!
The Laravel API Response Builder supports multiple languages for API responses. By default, it includes English (en
) and Brazilian Portuguese (pt_BR
). To use translations in your project, follow these steps:
If you wish to customize or add new languages, you can publish the translation files to your project by running:
php artisan vendor:publish --tag=lang
This will create a resources/lang/vendor/responsebuilder
directory where you can modify or add new translation files (e.g., es
, fr
).
If you do not need custom translations, the package will automatically use the default language files from the vendor/danilowa/laravel-api-response-builder/resources/lang
directory.
The Laravel API Response Builder utilizes the following technologies:
The Laravel API Response Builder package integrates several advanced concepts and patterns designed to enhance API response management:
Response Wrapping: This pattern wraps your response data in a unified format, ensuring consistency across all API responses. It includes customizable data wrappers that can be adjusted through the config/responsebuilder.php
configuration file. This approach simplifies response handling and provides a clear structure for both successful and error responses.
Detailed Logging: The package offers comprehensive logging capabilities for both responses and requests. Using Laravels built-in logging facilities, it captures key details such as response status, headers, and content. This feature supports various logging levels and allows you to specify log file paths, enabling efficient debugging and monitoring of your API interactions.
Example: You can view response logs in your designated log file, set in the configuration file under logging.channels
. For instance, responses with status codes 500
will be logged as errors, helping you track and debug critical issues.
Flexible Configuration Management: Leveraging Laravels configuration system, the package provides extensive options for customizing the response structure. You can easily configure data wrappers, API key headers, default status codes, and response languages. This flexibility allows you to tailor the packages behavior to fit the specific needs of your project.
Standardized Error Handling: The package standardizes the way error messages and statuses are generated. It provides a consistent approach to error responses, allowing for easier troubleshooting and improved user experience. Configuration options are available to adjust error message formats and response codes, ensuring that error handling aligns with your applications requirements.
In this section, we highlight the two most frequently used methods (Success and Error ) in the package for quick reference. For a comprehensive overview and detailed explanations of all available methods, including additional functionalities and usage scenarios, please consult the full documentation.
You can customize the response structure and behavior in the package configuration file. Here are some key options:
Custom Response Structure: Modify the default response keys (status
, message
, data
) to fit your API needs.
/*
|--------------------------------------------------------------------------
| Custom Response Structure
|--------------------------------------------------------------------------
| Define a custom structure for responses. The example below includes
| 'status', 'message', and 'data', but you can modify these as needed.
|
*/
'custom_response_structure' => [
'status' => 'status',
'message' => 'message',
'data' => 'data',
],
Response Data Wrapper: Enable or disable wrapping the response data in an additional data
key. This helps maintain a consistent response structure.
/*
|--------------------------------------------------------------------------
| Response Data Wrapper
|--------------------------------------------------------------------------
| If enabled, the response data will be wrapped in an additional 'data'
| key. This is useful if you want a consistent structure for all responses.
|
*/
'wrap_data' => true,
Response Data Wrapper Key: Customize the key used to wrap the response data. The default key is data
, but you can change it according to your API structure.
/*
|--------------------------------------------------------------------------
| Response Data Wrapper Key
|--------------------------------------------------------------------------
| This value sets the key used to wrap the response data. By default, it is
| 'data', but you can customize it according to your API structure.
|
*/
'wrap_data_key' => 'items',
These configuration options allow you to tailor the response structure to fit the needs of your application and ensure consistency across your API responses.
Description:
The success()
method returns a JSON response with a successful status code (200) and a success message. This is useful for standardizing success responses in your API.
Parameters:
mixed $data
:
array
or object
['user' => $user]
or new User($userId)
.string|null $message
:
string
or null
'User fetched successfully.'
or null
.bool|null $wrap
:
bool
or null
true
, the data will be wrapped according to the configuration. If false
, no wrapping will be applied. If null
, the wrapping behavior will follow the default configuration setting. This parameter is optional.true
| false
or null
.string|null $wrapKey
:
string
or null
'items'
or null
.int $statusCode
:
int
200
, but can be changed if needed.200
(for a successful request).Returns:
IlluminateJsonResponse
: A JSON response object with the provided data and message.Usage Examples:
Default Success Response:
$response = JsonResponse::success();
{
"status": "success",
"message": "Operation completed successfully.",
"data": null
}
Basic Success Response:
$response = JsonResponse::success(['user' => $user]);
{
"status": "success",
"message": "Operation successful.",
"data": {
"user": {
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}
}
}
Success Response with Custom Message:
$response = JsonResponse::success(['user' => $user], 'User fetched successfully.');
{
"status": "success",
"message": "User fetched successfully.",
"data": {
"user": {
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}
}
}
Success Response with Wrapping:
$response = JsonResponse::success(['user' => $user], 'User fetched successfully.', true);
'items'
by default and a custom success message.{
"status": "success",
"message": "User fetched successfully.",
"data": {
"items": {
"user": {
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}
}
}
}
Success Response with Custom Wrap key:
$response = JsonResponse::success(['user' => $user], 'User fetched successfully.', true, 'customWrap');
'customWrap'
and a custom success message.{
"status": "success",
"message": "User fetched successfully.",
"data": {
"customWrap": {
"user": {
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}
}
}
}
error()
Description:
The error()
method returns a JSON response with an error status code and an error message. This is useful for standardizing error responses in your API.
Parameters:
int $statusCode
:
int
404
.string|null $message
:
string
or null
'Resource not found.'
or null
.mixed $data
:
array
or object
or null
['field' => 'username', 'error' => 'Username is required.']
or null
.bool|null $wrap
:
bool
or null
true
, the data will be wrapped according to the configuration. If false
, no wrapping will be applied. If null
, the wrapping behavior will follow the default configuration setting. This parameter is optional.true
| false
or null
.string|null $wrapKey
:
string
or null
'error'
or null
.Returns:
IlluminateJsonResponse
: A JSON response object with the provided status code, message, and data.Usage Examples:
Default Error Response
$response = JsonResponse::error(404);
404
status code and a default error message.{
"status": "error",
"message": "The requested resource could not be found.",
"data": null
}
Basic Error Response:
$response = JsonResponse::error(404, 'Resource not found.');
404
status code and a default error message.{
"status": "error",
"message": "Resource not found.",
"data": null
}
Error Response with Custom Message and Data:
$response = JsonResponse::error(400, 'Bad request', ['field' => 'username', 'error' => 'Username is required.']);
400
status code, a custom error message, and additional data describing the validation error.{
"status": "error",
"message": "Bad request",
"data": {
"field": "username",
"error": "Username is required."
}
}
Error Response with Wrapping:
$response = JsonResponse::error(500, 'Internal server error', null, true);
500
status code and the error wrapped under the key 'items'
by default.{
"status": "error",
"message": "Internal server error",
"data": {
"items": null
}
}
Error Response with custom Wrap key:
$response = JsonResponse::error(500, 'Internal server error', null, true, 'error');
500
status code and the error wrapped under the custom key 'error'
.{
"status": "error",
"message": "Internal server error",
"data": {
"error": null
}
}
You can contribute by forking the repository and submitting a pull request.
This package is licensed under the MIT License.
For any questions or feedback, please reach out to:
Note: This package is currently under development, and XML support is still in progress. As an early release, there might be bugs or incomplete features. We appreciate your patience and feedback.