### Install Specific Release Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/installation.md Example of installing a specific release (e.g., 9.3) and its bug fixes (9.3.*). Composer will not automatically update to 9.4 or newer. ```bash composer require marcin-orlowski/laravel-api-response-builder:9.3 ``` -------------------------------- ### Install Latest Version Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/installation.md Use this command to install the latest stable version of the package. ```bash composer require marcin-orlowski/laravel-api-response-builder ``` -------------------------------- ### Install Specific Version Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/installation.md Install a specific major and minor version of the package. This ensures stability by not automatically updating to newer minor versions. ```bash composer require marcin-orlowski/laravel-api-response-builder: ``` -------------------------------- ### Example Success Response with Custom Builder Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/response.md Demonstrates how to use the custom response builder to generate a success response. The output includes the custom timestamp and timezone, and omits the locale field. ```php MyRB::success(); ``` -------------------------------- ### Example JSON Success Response Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/response.md The expected JSON structure for a success response when using the custom response builder, including timestamp and timezone. ```json { "success": true, "code": 0, "message": "OK", "timestamp": 1272509157, "timezone": "UTC", "data": null } ``` -------------------------------- ### Example Error Response with Data using Custom Builder Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/response.md Shows how to generate an error response with data using the custom response builder. The response will include the custom timestamp and timezone. ```php $data = [ 'foo' => 'bar' ]; return MyRB::errorWithData(ApiCode::SOMETHING_WENT_WRONG, $data); ``` -------------------------------- ### Custom Response Builder Implementation Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/response.md Extend the ResponseBuilder class and override the buildResponse method to customize the response structure. This example adds a timestamp and timezone, and removes the locale field. ```php getTimestamp(); $response['timezone'] = $date->getTimezone(); unset($response['locale']); // finally, return what $response holds return $response; } } ``` -------------------------------- ### Recursive Conversion Example Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md Illustrates how recursive conversion works when an object's converted data contains other objects. The 'key' parameter determines how the converted data is represented in the JSON response. ```json ... "data": { "given-key": { [converted object data] } } ... ``` -------------------------------- ### Example JSON Error Response Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/examples.md Illustrates the JSON structure of an error response when ApiCode::SOMETHING_WENT_WRONG has a value of 250 and no custom message is mapped. ```json { "success": false, "code": 250, "locale": "en", "message": "Error #250", "data": null } ``` -------------------------------- ### Example JSON Error Response Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/response.md The expected JSON structure for an error response with data when using the custom response builder, including timestamp and timezone. ```json { "success": false, "code": 250, "message": "Error #250", "timestamp": 1272509157, "timezone": "UTC", "data": { "foo": "bar" } } ``` -------------------------------- ### Publish Configuration File Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/installation.md Run this Artisan command to publish the default configuration file to your application's config directory for customization. ```bash php artisan vendor:publish ``` -------------------------------- ### Create a Simple Success Response Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/methods.md A shortcut to return a basic success response without any additional data or custom HTTP codes. This is equivalent to the previous success() method. ```php return RB::success(); ``` -------------------------------- ### Helper Method - Success Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/methods.md A shortcut method to quickly return a success response without extensive configuration. ```APIDOC ## Helper Method - Success ### Description Provides a simple way to return a success response, optionally with data. ### Method `success($data = null, $api_code = null, $placeholders = null, $http_code = null, $json_opts = null)` ### Parameters * `$data` (**mixed**, optional): Data to include in the response. * `$api_code` (**int**, optional): The API response code. Defaults to `ApiCodes::OK()`. * `$placeholders` (**array**, optional): Placeholders for localization. * `$http_code` (**int**, optional): The HTTP status code. * `$json_opts` (**int**, optional): JSON encoding options. ### Request Example ```php return RB::success(); return RB::success(['user_id' => 123], ApiCodes::OK, null, HttpResponse::HTTP_OK); ``` ### Response #### Success Response (2xx) * `data` (mixed) - The data payload. * `message` (string) - A success message. * `code` (int) - The API response code. ``` -------------------------------- ### Configure Data Converters Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md Define custom converters for Eloquent Models and Paginators. The 'handler' specifies the converter class, 'key' is used for JSON output, and 'pri' sets the matching priority. ```php 'converter' => [ \Illuminate\Database\Eloquent\Model::class => [ 'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class, 'key' => 'items', 'pri' => 0, ], \Illuminate\Pagination\Paginator::class => [ 'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ArrayableConverter::class, 'key' => null, // SPECIAL CASE. READ BELOW! 'pri' => 0, ], ], ``` -------------------------------- ### Builder Pattern - Success Response Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/methods.md Demonstrates creating a success response using the Builder pattern, including custom data and HTTP status code. ```APIDOC ## Builder Pattern - Success Response ### Description Creates a success response with optional data and custom HTTP status code. ### Method `asSuccess($api_code)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Builder Methods * `withData($data)`: (**mixed**) Adds data to the response. * `withHttpCode($code)`: (**int**) Sets the HTTP status code. * `withJsonOptions($opts)`: (**int**) Sets JSON encoding options. * `withHttpHeaders($headers)`: (**array**) Adds custom HTTP headers. ### Build Method * `build()`: Returns the final `HttpResponse` object. ### Request Example ```php return RB::asSuccess() ->withData($data) ->withHttpCode(HttpResponse::HTTP_CREATED) ->build(); ``` ### Response #### Success Response (2xx) * `data` (mixed) - The data payload. * `message` (string) - A success message. * `code` (int) - The API response code. ``` -------------------------------- ### Selective HTTP Code and Code Configuration Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/exceptions.md Optionally configure only the 'http_code' or 'code' for exceptions. The helper falls back to defaults if keys are missing. For 'uncaught_exception', the default HTTP code is HttpResponse::HTTP_INTERNAL_SERVER_ERROR. ```php 'http_not_found' => [ 'http_code' => HttpResponse::HTTP_BAD_REQUEST, ], 'http_service_unavailable' => [ 'code' => BaseApiCodes::EX_HTTP_SERVICE_UNAVAILABLE(), ], 'uncaught_exception' => [ ], ``` -------------------------------- ### Debug Configuration Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md The debug configuration section allows enabling various debugging features, including exception tracing and converter debugging. Use with caution in production environments. ```php 'debug' => [ 'debug_key' => 'debug', 'exception_handler' => [ 'trace_key' => 'trace', 'trace_enabled' => env('APP_DEBUG', false), ], // Controls debugging features of payload converter class. 'converter' => [ // Set to true to figure out what converter is used for given data payload and why. 'debug_enabled' => env('RB_CONVERTER_DEBUG', false), ], ] ``` -------------------------------- ### Builder Pattern - Error Response Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/methods.md Demonstrates creating an error response using the Builder pattern, including custom error messages and placeholders. ```APIDOC ## Builder Pattern - Error Response ### Description Creates an error response with a specific API code, optional message, and placeholders. ### Method `asError($api_code)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Builder Methods * `withHttpCode($code)`: (**int**) Sets the HTTP status code (400-599). * `withMessage($message)`: (**string**) Sets a custom error message. * `withPlaceholders($placeholders)`: (**array**) Provides placeholders for the message. * `withHttpHeaders($headers)`: (**array**) Adds custom HTTP headers. ### Build Method * `build()`: Returns the final `HttpResponse` object. ### Request Example ```php return RB::asError(ApiCodes::INVALID_INPUT) ->withMessage('Invalid input provided') ->withPlaceholders(['field' => 'email']) ->build(); ``` ### Response #### Error Response (4xx or 5xx) * `data` (mixed) - The error data payload (if any). * `message` (string) - The error message. * `code` (int) - The API error code. ``` -------------------------------- ### Unit Test ApiCodes with Traits Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/testing.md Create a testable ApiCodes class extending your original and using ApiCodesHelpers. Then, create a PHPUnit test class that uses the ApiCodesTests trait and specifies the testable ApiCodes class name. ```php $login]); ``` -------------------------------- ### Create a Success Response with Data and Custom HTTP Code Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/methods.md Use this snippet to create a success response with custom data and a specific HTTP status code. It utilizes the Builder pattern for a flexible API. ```php return RB::asSuccess() ->withData($data) ->withHttpCode(HttpResponse::HTTP_CREATED) ->build(); ``` -------------------------------- ### Basic Error Response Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/examples.md Return a basic error response using a placeholder for the error code. ```php return RB::error(); ``` -------------------------------- ### Success Response with Numeric Array Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/examples.md When a numeric array is passed to `success()`, it is treated specially and wrapped in an 'items' key. ```php $returned_array = [1,2,3]; return RB::success($returned_array); ``` -------------------------------- ### Success Response with Data Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/examples.md Return a success response with a payload. Pass your data as an argument to the `success()` method. Arrays with keys are mapped to JSON objects. ```php $data = [ 'foo' => 'bar' ]; return RB::success($data); ``` -------------------------------- ### Minimum API Code Configuration Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md Define the lowest inclusive API code that can be used. The ResponseBuilder reserves the first 19 codes for its own use. ```php 'min_code' => 100, ``` -------------------------------- ### Recursive Data Conversion with Array Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md Shows how the response builder handles an array containing objects, converting each object recursively and preserving the original array keys in the JSON output. ```php $data = [ 'flight' = App\Flight::where(...)->first(), 'planes' = App\Plane::where(...)->get(), ]; ``` -------------------------------- ### Custom Exception Handler Configuration Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md Configure specific handlers for different exception types, including priority and custom configurations. The default handler is mandatory and must define both 'api_code' and 'http_code'. ```php 'exception_handler' => [ \Symfony\Component\HttpKernel\Exception\HttpException::class => [ 'handler' => \MarcinOrlowski\ResponseBuilder\ExceptionHandlers\HttpExceptionHandler::class, 'pri' => -100, 'config' => [ HttpException::class => [ // used by unauthenticated() to obtain api and http code for the exception HttpResponse::HTTP_UNAUTHORIZED => [ 'api_code' => ApiCodes::YOUR_API_CODE_FOR_UNATHORIZED_EXCEPTION, ], // default handler is mandatory and MUST have both `api_code` and `http_code` set. 'default' => [ 'api_code' => ApiCodes::YOUR_API_CODE_FOR_GENERIC_HTTP_EXCEPTION, 'http_code' => HttpResponse::HTTP_BAD_REQUEST, ], ], ], ], ], ``` -------------------------------- ### Map Exceptions to API Codes Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/exceptions.md Configure the `config/response_builder.php` file to map specific exception types to your custom API codes. This ensures consistent error reporting. ```php 'exception_handler' => [ 'exception' => [ 'http_not_found' => ['code' => ApiCode::HTTP_NOT_FOUND], 'http_service_unavailable' => ['code' => ApiCode::HTTP_SERVICE_UNAVAILABLE], 'http_exception' => ['code' => ApiCode::HTTP_EXCEPTION], 'uncaught_exception' => ['code' => ApiCode::UNCAUGHT_EXCEPTION], 'authentication_exception' => ['code' => ApiCode::AUTHENTICATION_EXCEPTION], 'validation_exception' => ['code' => ApiCode::VALIDATION_EXCEPTION], ], ], ``` -------------------------------- ### Helper Method - Error Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/methods.md A shortcut method to quickly return an error response. ```APIDOC ## Helper Method - Error ### Description Provides a simple way to return an error response with a specific API code. ### Method `error(int $api_code, array $placeholders = null, $data = null, int $http_code = null, int $json_opts = null)` ### Parameters * `$api_code` (**int**) - Required. The API error code. Must not equal `ApiCodes::OK()`. * `$placeholders` (**array**, optional): Placeholders for localization. * `$data` (**mixed**, optional): Data to include in the error response. * `$http_code` (**int**, optional): The HTTP status code (400-599). * `$json_opts` (**int**, optional): JSON encoding options. ### Request Example ```php return RB::error(ApiCodes::SOMETHING_FAILED); return RB::error(ApiCodes::RESOURCE_NOT_FOUND, null, ['id' => 5], HttpResponse::HTTP_NOT_FOUND); ``` ### Response #### Error Response (4xx or 5xx) * `data` (mixed) - The error data payload (if any). * `message` (string) - The error message. * `code` (int) - The API error code. ``` -------------------------------- ### Register Exception Handler Helper Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/exceptions.md Add the ExceptionHandlerHelper to your application's exception handler to enable standardized JSON error responses. This involves importing the helper and registering a renderable callback. ```php use MarcinOrlowski\ResponseBuilder\ExceptionHandlerHelper; ``` ```php public function register() { $this->renderable(function (Throwable $ex, $request) { return ExceptionHandlerHelper::render($request ,$ex ); }); } ``` -------------------------------- ### Maximum API Code Configuration Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md Define the highest inclusive API code allowed for this module. ```php 'max_code' => 1024, ``` -------------------------------- ### Create a Simple Error Response Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/methods.md Use this helper method to quickly generate an error response with a specified API code. All other parameters are optional. ```php return RB::error(ApiCodes::SOMETHING_FAILED); ``` -------------------------------- ### Override Default Success Message Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/docs.md Map the `OK()` code to your custom message key to override the default success message. ```php MarcinOrlowski\ResponseBuilder\BaseApiCodes::OK() => 'my_messages.ok', ``` -------------------------------- ### Configure HTTP Code for Exception Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/exceptions.md Set a custom HTTP status code for a specific exception like 'http_not_found'. Ensure the code is within the valid range (400-599). ```php 'http_not_found' => [ 'code' => BaseApiCodes::EX_HTTP_NOT_FOUND(), 'http_code' => HttpResponse::HTTP_BAD_REQUEST, ], ``` -------------------------------- ### Error Response with API Code Constant Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/examples.md Use a constant from an ApiCode class for a more readable and testable error code. Assumes ApiCode::SOMETHING_WENT_WRONG is defined. ```php return RB::error(ApiCode::SOMETHING_WENT_WRONG); ``` -------------------------------- ### Success Response with Eloquent Models Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/examples.md Pass Eloquent models or collections directly to `success()`. The Response Builder will automatically convert them into the appropriate JSON structure within the 'data' node. ```php $flight = App\Flight::where(...)->get(); return RB::success($flight); ``` -------------------------------- ### Error Response with Custom Message Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/examples.md Return an error response with a custom string message, bypassing the default error code mapping. Placeholders must be manually resolved using Lang::get() if needed. ```php $msg = Lang::get('message.something_wrong', ['login' => $login]); return RB::errorWithMessage(ApiCodeBase::SOMETHING_WENT_WRONG, $msg); ``` -------------------------------- ### Map Exceptions to Custom Error Messages Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/exceptions.md Override default exception messages by mapping exception codes to localization string keys. Supports placeholders like :api_code and :message. ```php 'map' => [ BaseApiCodes::EX_HTTP_NOT_FOUND() => 'api.http_not_found', BaseApiCodes::EX_HTTP_SERVICE_UNAVAILABLE() => 'api.http_service_unavailable', BaseApiCodes::EX_HTTP_EXCEPTION() => 'api.http_exception', BaseApiCodes::EX_UNCAUGHT_EXCEPTION() => 'api.uncaught_exception', BaseApiCodes::EX_AUTHENTICATION_EXCEPTION() => 'api.authentication_exception', BaseApiCodes::EX_VALIDATION_EXCEPTION() => 'api.validation_exception', ... ], ``` -------------------------------- ### Simplified Primitive Payload (v9+) Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md In versions 9 and above, primitives can be passed directly as the payload, simplifying the response structure. This removes the need to wrap primitives in an array or object. ```php RB::success(12.25); ``` -------------------------------- ### Debug Exception Trace Output Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md When the exception handler is enabled in debug mode, the JSON response will include a 'debug' node containing trace information about the exception. ```json { "success": false, "code": 0, "locale": "en", "message": "Uncaught Exception", "data": null, "debug": { "trace": { "class": "", "file": "", "line": "" } } } ``` -------------------------------- ### Test API Endpoint Response Structure Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/testing.md Use the TestingHelpers trait in your Laravel TestCase to make calls to your API endpoints and validate the ApiResponse structure. The ApiResponse::fromJson method helps in parsing and validating the response content. ```php call('POST', '/v1/session/foo'); // Get the response validated and processed. $api = ApiResponse::fromJson($response->getContent()); // Add some tests of your choice. $this->assertTrue($api->success()); } } ``` -------------------------------- ### API Error Code to Language String Mapping Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md Map custom API error codes to language strings for user-friendly error messages. An empty map is valid but the 'map' key must be present. ```php 'map' => [ ApiCode::SOMETHING => 'api.something', ... ], ``` ```php 'map' => [], ``` -------------------------------- ### Primitive Payload (Pre-v9) Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md Prior to version 9, primitive data types needed to be wrapped in an array or object to be passed as a payload. ```php RB::success(['value' => 12.25]); ``` -------------------------------- ### Define API Error Codes Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/exceptions.md Define custom API error codes in your `ApiCodes` class to represent different exception types handled by the ExceptionHandlerHelper. Ensure these codes fall within your allowed range. ```php public const HTTP_NOT_FOUND = ...; public const HTTP_SERVICE_UNAVAILABLE = ...; public const HTTP_EXCEPTION = ...; public const UNCAUGHT_EXCEPTION = ...; public const AUTHENTICATION_EXCEPTION = ...; public const VALIDATION_EXCEPTION = ...; ``` -------------------------------- ### Laravel Default JSON Encoding Options Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md This shows the default JSON encoding options used by Laravel, which typically do not include JSON_UNESCAPED_UNICODE. ```php JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT ``` -------------------------------- ### Recursive Data Conversion Output Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md The resulting JSON structure after recursively converting an array of objects, demonstrating how nested objects and collections are represented. ```json { "flight": { "airline": "lot", "flight_number": "lo123", ... }, "planes": [ { "make": "airbus", "registration": "F-GUGJ", ... }, { "make": "boeing", "registration": "VT-ANG", ... } ] } ``` -------------------------------- ### Default JSON Response Structure Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/docs.md The standard JSON structure guaranteed by the ResponseBuilder, including success status, return code, locale, message, and data. ```json { "success": true, "code": 0, "locale": "en", "message": "OK", "data": null } ``` -------------------------------- ### Convert Single Eloquent Model to JSON Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/conversion.md Pass a single Eloquent model instance to RB::success() to have it automatically converted to a JSON object within the response. This is useful for returning single records. ```php $flight = App\Flight::where(...)->first(); return RB::success($flight); ``` -------------------------------- ### Override API Code to Message Conversion Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/docs.md Extend the ResponseBuilder class to provide custom logic for converting API codes into human-readable messages. This allows for tailored error messages based on your application's needs. ```php get(); return RB::success($flights); ``` -------------------------------- ### Override Default Error Message Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/docs.md Map the `NO_ERROR_MESSAGE()` code to your custom error message key to override the default fallback error message. The `:api_code` placeholder can be used for dynamic substitution. ```php MarcinOrlowski\ResponseBuilder\BaseApiCodes::NO_ERROR_MESSAGE() => 'my_messages.default_error_message', ``` -------------------------------- ### JSON Encoding with Unescaped Unicode Source: https://github.com/marcinorlowski/laravel-api-response-builder/blob/master/docs/config.md To prevent characters like accents from being escaped in JSON output, include the JSON_UNESCAPED_UNICODE option in the encoding configuration. ```php JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.