harrisonratcliffe/laravel-api-responses

A Laravel package to easily handle API responses and exceptions

2.2.2 2025-04-07 15:35 UTC

This package is auto-updated.

Last update: 2025-04-07 15:35:57 UTC


README

LARAVEL API RESPONSES

composer require harrisonratcliffe/laravel-api-responses

license last-commit repo-top-language repo-language-count


๐Ÿ”— Table of Contents

๐Ÿ“ Overview

A Laravel package to easily handle API responses and exceptions.

๐Ÿ‘พ Features

  • ๐ŸŒŸ Return clean, consistent API responses
  • ๐Ÿ›ก๏ธ Handle API exceptions with standardized error responses
  • ๐Ÿš€ Easy integration with Laravel 7 to 12

๐Ÿš€ Getting Started

โ˜‘๏ธ Prerequisites

Before getting started with Laravel API Responses, ensure your runtime environment meets the following requirements:

  • Programming Language: PHP
  • Package Manager: Composer
  • Laravel Version: 7 or later

โš™๏ธ Installation

Install laravel-api-responses using the following method:

  1. Install the package via Composer:
composer require harrisonratcliffe/laravel-api-responses
  1. Publish the config with:
php artisan vendor:publish --tag="apiresponses-config"

API Exception Handler

Note: if you use a different API route path than /api you should adjust the below if statement.

Laravel 11-12

To configure the API Exception Handler on Laravel 11-12, add the following configuration to your boostrap/app.php file:

use Harrisonratcliffe\LaravelApiResponses\ApiExceptionHandler;

->withExceptions(function (Exceptions $exceptions) {
        // your other code here
       $exceptions->render(function (Throwable $exception, $request) {
            if ($request->expectsJson() || $request->is('api/*')) {
                return app(ApiExceptionHandler::class)->renderApiException($exception);
            }
        });
        // your other code here
    })

Laravel 7-10

To configure the API Exception Handler on Laravel 7-10, add the following configuration inside your render method of your app/Exceptions/Handler.php file:

use Harrisonratcliffe\LaravelApiResponses\ApiExceptionHandler;

public function render($request, Throwable $exception)
    {
    // your other code here
        if ($request->expectsJson() || $request->is('api/*')) {
            return app(ApiExceptionHandler::class)->renderApiException($exception);
        }
    // your other code here
    }

Here's the modified README to reflect the new option for handling internal server error messages:

๐Ÿ”ง Configuration Options

The Laravel API Handler package provides a flexible configuration file that allows you to customize default response messages and behaviors. Let's break down each configuration option:

๐Ÿž Debug Mode

'debug_mode' => end('APP_ENV', false),
  • Purpose: Controls whether detailed error information is exposed
  • Default: Inherits from Laravel's APP_ENV environment variable
  • Security Warning: ๐Ÿšจ Only enable in development environments
  • Behavior:
    • When true: Potentially exposes sensitive error details
    • When false: Provides generic, safe error messages

๐Ÿ“ก Default Success Response

'success_response' => 'API request processed successfully.',
'success_status_code' => 200,
  • Success Message: Customizable default message for successful API requests
  • Status Code: Standard HTTP 200 OK response
  • Customization: Easily modify the default success message to match your application's tone

๐Ÿšง Default Error Messages

'http_not_found' => 'The requested resource or endpoint could not be located.',
'unauthenticated' => 'You must be logged in to access this resource. Please provide valid credentials.',
'model_not_found' => 'The requested resource could not be found. This resource doesn\'t exist.',
'unknown_error' => 'An unexpected error has occurred. Please try again later or contact support if the issue persists.',

Error Message Breakdown

  • http_not_found: Used when a requested endpoint doesn't exist
  • unauthenticated: Triggered for unauthorized access attempts
  • model_not_found: Dynamic message for missing database records
    • Provides clarity on what was not found
  • unknown_error: Fallback message for unexpected errors

โš ๏ธ Internal Server Error Message

'show_500_error_message' => true,
  • Purpose: Controls whether the actual error message from a 500/internal server error is returned.
  • Default: true (actual error message will be shown)
  • Behavior:
    • When true: The detailed error message is returned, which can aid in debugging.
    • When false: The unknown_error response will be used instead, maintaining user-friendliness.

๐Ÿ› ๏ธ Customization Tips

  • Modify the config file located at config/api-responses.php
  • Tailor messages to match your application's voice
  • Keep error messages informative but not overly technical
  • Ensure messages are user-friendly and provide clear guidance

๐Ÿค– Usage

Success Responses

// In your controller
use Harrisonratcliffe\LaravelApiResponses\Facades\ApiResponses;

public function index()
{
    $data = User::all();
    return ApiResponses::success(
        'Users retrieved successfully', 
        $data
    );
}

Example Success Response

{
    "status": "success",
    "message": "Users retrieved successfully",
    "data": [
        {"id": 1, "name": "John Doe"},
        {"id": 2, "name": "Jane Smith"}
    ]
}

Error Responses

use Harrisonratcliffe\LaravelApiResponses\Facades\ApiResponses;

public function store()
{
    return ApiResponses::error(
        'This virtual machine does not exist',
        404,
        [
            'vm_id' => 12345
        ],
        'https://docs.yourapi.com/errors/some-error'
    );
}

Example Error Response

{
    "status": "error",
    "message": "This virtual machine does not exist",
    "details": {
        "vm_id": 12345
    },
    "documentation": "https://docs.yourapi.com/errors/some-error"
}

Method Signatures

successResponse()

  • $message (optional): Custom success message
  • $data (optional): Response data
  • $statusCode (optional): HTTP status code (default: 200)

errorResponse()

  • $message (required): Error description
  • $statusCode (optional): HTTP error code (default: 400)
  • $details (optional) Error details
  • $documentation (optional): Error documentation link
  • $debug (optional): Additional debug information

๐Ÿงช Testing

Run the test suite using the following command: Using composer ย 

vendor/bin/pest

๐Ÿ”ฐ Contributing

Contributions are welcome!

  • ๐Ÿ› Report Issues: Submit bugs found or log feature requests for the laravel-api-responses project.
  • ๐Ÿ’ก Submit Pull Requests: Review open PRs, and submit your own PRs.
Contributing Guidelines
  1. Fork the Repository: Start by forking the project repository to your github account.
  2. Clone Locally: Clone the forked repository to your local machine using a git client.
    git clone https://github.com/harrisonratcliffe/laravel-api-responses
  3. Create a New Branch: Always work on a new branch, giving it a descriptive name.
    git checkout -b new-feature-x
  4. Make Your Changes: Develop and test your changes locally.
  5. Commit Your Changes: Commit with a clear message describing your updates.
    git commit -m 'Implemented new feature x.'
  6. Push to github: Push the changes to your forked repository.
    git push origin new-feature-x
  7. Submit a Pull Request: Create a PR against the original project repository. Clearly describe the changes and their motivations.
  8. Review: Once your PR is reviewed and approved, it will be merged into the main branch. Congratulations on your contribution!
Contributor Graph

๐ŸŽ— License

This project is protected under the MIT License. For more details, refer to the LICENSE file.