creativecrafts/laravel-api-response

A simple package to have a consistent api response.

2.0.2 2025-01-07 15:38 UTC

This package is auto-updated.

Last update: 2025-01-07 16:19:28 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Laravel API Response is a powerful and flexible package that provides a standardized way to structure API responses in Laravel applications. It offers a range of features to enhance your API development experience, including consistent response formatting, conditional responses, pagination support, rate limiting, and more.

Table of Contents

1. [Installation](#installation)
2. [Configuration](#configuration)
3. [Basic Usage](#basic-usage)
4. [Feature](#feature)
    - [Success Response](#success-response)
    - [Error Response](#error-response)
    - [Conditional Response](#conditional-response)
    - [Pagination](#pagination)
    - [Rate Limiting](#rate-limiting)
    - [Response Compression](#response-compression)
    - [Localization](#localization)
    - [HATEOAS Links](#hateoas-links)
    - [Logging](#logging)
5. [Advanced Usage](#advanced-usage)
6. [Testing](#testing)
7. [Changelog](#changelog)
8. [Contributing](#contributing)
9. [Security Vulnerabilities](#security-vulnerabilities)
10. [Credits](#credits)
11. [License](#license)

1. Installation

You can install the package via composer:

composer require creativecrafts/laravel-api-response

2. Configuration

The package comes with a default configuration file that you can publish to your application using the following command:

php artisan vendor:publish --tag=api-response-config

This will create a laravel-api-response.php file in your config directory. You can customize various aspects of the package behavior in this file.

3. Basic Usage

To use the Laravel API Response in your controllers, you can inject the LaravelApi class:

use CreativeCrafts\LaravelApiResponse\LaravelApi;

class UserController extends Controller
{
    protected $api;

    public function __construct(LaravelApi $api)
    {
        $this->api = $api;
    }

    public function index()
    {
        $users = User::all();
        return $this->api->successResponse('Users retrieved successfully', $users);
    }
}

4. Feature

The Laravel API Response package provides a range of features to help you build robust and reliable APIs. Here are some of the key features:

Success Responses

To return a success response:

return $this->api->successResponse('Operation successful', $data);

Error Responses

To return an error response:

return $this->api->errorResponse('An error occurred', $errorCode, $statusCode);

Conditional Responses

For responses that support caching and conditional requests:

return $this->api->conditionalResponse($data, 'Data retrieved successfully');

This method automatically handles ETag and Last-Modified headers for efficient caching.

Pagination

The package supports Laravel's pagination:

$users = User::paginate(15);
return $this->api->paginatedResponse('Users retrieved successfully', $users);

Rate Limiting

Rate limiting is automatically applied to API routes. You can configure the rate limit in the laravel-api-response.php config file:

'rate_limit_max_attempts' => env('API_RATE_LIMIT_MAX_ATTEMPTS', 60),
'rate_limit_decay_minutes' => env('API_RATE_LIMIT_DECAY_MINUTES', 1),

Response Compression

Response compression can be enabled or disabled in the config:

'enable_compression' => env('API_RESPONSE_COMPRESSION', true),

Localization

The package supports message localization. Use the localize method to translate messages:

$message = $this->api->localize('messages.welcome');

HATEOAS Links

You can include HATEOAS links in your responses:

$links = [
    'self' => ['href' => '/api/users/1'],
    'posts' => ['href' => '/api/users/1/posts'],
];

return $this->api->successResponse('User retrieved', $userData, 200, [], $links);

Logging

API responses are logged to a dedicated channel. You can configure the channel in the config file:

'log_channel' => 'api',

5. Advanced Usage

The Laravel API Response package provides a range of advanced features to help you build robust and reliable APIs. Here are some of the key features:

Custom Response Structure

You can customize the response structure in the config file:

'response_structure' => [
    'success_key' => 'success',
    'message_key' => 'message',
    'data_key' => 'data',
    'errors_key' => 'errors',
    'error_code_key' => 'error_code',
    'meta_key' => 'meta',
    'links_key' => '_links',
    'include_api_version' => true,
],

Filtering Response Fields

You can filter the fields returned in the response:

$fields = ['id', 'name', 'email'];
return $this->api->successResponse('User data', $userData, 200, [], [], $fields);

Custom Status Codes

You can specify custom HTTP status codes for your responses:

return $this->api->successResponse('Resource created', $newResource, 201);

Version 2: Breaking Changes

Version 2 of the package introduces one breaking change.

  • createdResponse method has been removed. Use successResponse instead.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.