Β Simplify Your API Responses with Laravel API Response Builder! This package helps you create structured and formatted API responses in both JSON and XML formats effortlessly. It provides customizable status codes, messages, and data handling, making it a versatile tool for managing API responses, including error handling, logging, and extensive configuration options.
π How to Use
Overview of the most commonly used methods and their brief descriptions.
- Features
- Requirements
- Installation
- Translations
- Technologies
- Concepts & Patterns
- Documentation
- Links
- Contributing
- License
- Contact
- Structured Responses: Create consistent JSON and XML responses effortlessly.
- Customizable Status Codes & Messages: Adapt responses to fit your requirements.
- Error Handling & Logging: Detailed logging for both responses and requests.
- Flexible Configuration: Adjust settings for data wrapping, response languages, and more.
Ensure your project meets the following requirements before using this package:
- Laravel Framework: Version 8.12 or higher.
- PHP: Version 7.3 or higher.
- Composer: PHP dependency manager.
With these features in place, letβs dive into the installation process!
To integrate the Laravel API Response Builder into your Laravel project, follow these steps:
- Install via Composer:
Run the following command in your terminal:
composer require danilowa/laravel-api-response-builder
- Publish the Configuration (Optional):
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.
- Configuration:
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:
- Publish the Translation Files (Optional):
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
).
- Use Existing Translation Files:
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:
- Laravel Framework: A PHP framework for web applications.
- PHP: The server-side scripting language.
- JSON: Data format for API responses.
- XML: Data format for API responses (currently under development).
- Log: Laravel's logging facilities for recording response details.
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 Laravelβs 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 codes500
will be logged as errors, helping you track and debug critical issues. -
Flexible Configuration Management: Leveraging Laravelβs 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 packageβs 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 applicationβs 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.
- Success - Returns a standard success response with optional data and a default message.
- SuccessWithMeta - Returns a success response with data and additional metadata.
- SuccessWithHeaders - Returns a success response with data and custom headers included.
- SuccessWithPagination - Returns a success response with data and pagination details.
- Error - Returns an error response with a specified status code and message.
- ErrorWithTrace - Returns an error response with an additional trace for debugging purposes.
- ErrorWithSuggestions - Returns an error response with suggestions for resolving the issue.
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
:- Optional
- Type:
array
orobject
- Description: The data to include in the response. This can be any data structure that you want to return to the client.
- Example:
['user' => $user]
ornew User($userId)
.
-
string|null $message
:- Optional
- Type:
string
ornull
- Description: The success message to include in the response. If not provided, a default message will be used. This parameter is optional.
- Example:
'User fetched successfully.'
ornull
.
-
bool|null $wrap
:- Optional
- Type:
bool
ornull
- Description: Determines whether to wrap the data in a wrapper object. If
true
, the data will be wrapped according to the configuration. Iffalse
, no wrapping will be applied. Ifnull
, the wrapping behavior will follow the default configuration setting. This parameter is optional. - Example:
true
|false
ornull
.
-
string|null $wrapKey
:- Optional
- Type:
string
ornull
- Description: The key for wrapping the data. If specified, the data will be wrapped under this key. If not provided, the default key from the configuration will be used. This parameter is optional.
- Example:
'items'
ornull
.
-
int $statusCode
:- Optional
- Type:
int
- Description: The HTTP status code for the response. Default is
200
, but can be changed if needed. - Example:
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();
- Description: Returns a JSON response with the user data and a default success message.
- Example Output:
{ "status": "success", "message": "Operation completed successfully.", "data": null }
-
Basic Success Response:
$response = JsonResponse::success(['user' => $user]);
- Description: Returns a JSON response with the user data and a default success message.
- Example Output:
{ "status": "success", "message": "Operation successful.", "data": { "user": { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } } }
-
Success Response with Custom Message:
$response = JsonResponse::success(['user' => $user], 'User fetched successfully.');
- Description: Returns a JSON response with the user data and a custom success message.
- Example Output:
{ "status": "success", "message": "User fetched successfully.", "data": { "user": { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } } }
-
Success Response with Wrapping:
$response = JsonResponse::success(['user' => $user], 'User fetched successfully.', true);
- Description: Returns a JSON response with the user data wrapped under the key
'items'
by default and a custom success message. - Example Output:
{ "status": "success", "message": "User fetched successfully.", "data": { "items": { "user": { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } } } }
- Description: Returns a JSON response with the user data wrapped under the key
-
Success Response with Custom Wrap key:
$response = JsonResponse::success(['user' => $user], 'User fetched successfully.', true, 'customWrap');
- Description: Returns a JSON response with the user data wrapped under the custom key
'customWrap'
and a custom success message. - Example Output:
{ "status": "success", "message": "User fetched successfully.", "data": { "customWrap": { "user": { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } } } }
- Description: Returns a JSON response with the user data wrapped under the custom key
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
:- Required
- Type:
int
- Description: The HTTP status code to indicate the type of error (e.g., 400 for Bad Request, 404 for Not Found, 500 for Internal Server Error).
- Example:
404
.
-
string|null $message
:- Optional
- Type:
string
ornull
- Description: The error message to include in the response. If not provided, a default error message will be used. This parameter is optional.
- Example:
'Resource not found.'
ornull
.
-
mixed $data
:- Optional
- Type:
array
orobject
ornull
- Description: The data to include in the response. This can be used to provide additional information about the error (e.g., validation errors). If not provided, no additional data will be included. This parameter is optional.
- Example:
['field' => 'username', 'error' => 'Username is required.']
ornull
.
-
bool|null $wrap
:- Optional
- Type:
bool
ornull
- Description: Determines whether to wrap the error data in a wrapper object. If
true
, the data will be wrapped according to the configuration. Iffalse
, no wrapping will be applied. Ifnull
, the wrapping behavior will follow the default configuration setting. This parameter is optional. - Example:
true
|false
ornull
.
-
string|null $wrapKey
:- Optional
- Type:
string
ornull
- Description: The key for wrapping the error data. If specified, the data will be wrapped under this key. If not provided, the default key from the configuration will be used. This parameter is optional.
- Example:
'error'
ornull
.
Returns:
IlluminateJsonResponse
: A JSON response object with the provided status code, message, and data.
Usage Examples:
-
Default Error Response
$response = JsonResponse::error(404);
- Description: Returns a JSON response with a
404
status code and a default error message. - Example Output:
{ "status": "error", "message": "The requested resource could not be found.", "data": null }
- Description: Returns a JSON response with a
-
Basic Error Response:
$response = JsonResponse::error(404, 'Resource not found.');
- Description: Returns a JSON response with a
404
status code and a default error message. - Example Output:
{ "status": "error", "message": "Resource not found.", "data": null }
- Description: Returns a JSON response with a
-
Error Response with Custom Message and Data:
$response = JsonResponse::error(400, 'Bad request', ['field' => 'username', 'error' => 'Username is required.']);
- Description: Returns a JSON response with a
400
status code, a custom error message, and additional data describing the validation error. - Example Output:
{ "status": "error", "message": "Bad request", "data": { "field": "username", "error": "Username is required." } }
- Description: Returns a JSON response with a
-
Error Response with Wrapping:
$response = JsonResponse::error(500, 'Internal server error', null, true);
- Description: Returns a JSON response with a
500
status code and the error wrapped under the key'items'
by default. - Example Output:
{ "status": "error", "message": "Internal server error", "data": { "items": null } }
- Description: Returns a JSON response with a
-
Error Response with custom Wrap key:
$response = JsonResponse::error(500, 'Internal server error', null, true, 'error');
- Description: Returns a JSON response with a
500
status code and the error wrapped under the custom key'error'
. - Example Output:
{ "status": "error", "message": "Internal server error", "data": { "error": null } }
- Description: Returns a JSON response with a
- Success - Description | Examples
- SuccessWithMeta - Description | Examples
- SuccessWithHeaders - Description | Examples
- SuccessWithPagination - Description | Examples
- Error - Description | Examples
- ErrorWithTrace - Description | Examples
- ErrorWithSuggestions - Description | Examples
- Custom Response Structure - Details Β - Data Wrapper Β - API Key Header Β - Response Language Β - Default Status Code Β - JSON Options
- Logs - Details Β - Log Responses Β - Request Logging Β - Response Time Logging Β - Logging Level Β - Log Files Path
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:
- Danilo Oliveira: daniloworkdev@gmail.com
- Website: daniloo.dev
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.