A simple package allowing for consistent API responses throughout your Laravel application

Overview

run-tests Packagist Version Packagist PHP Version Packagist License

Laravel API Response Helpers

A simple package allowing for consistent API responses throughout your Laravel application.

Requirements

  • PHP ^7.4 | ^8.0
  • Laravel 6, 7 and 8

Installation / Usage

composer require f9webltd/laravel-api-response-helpers

Simply reference the required trait within your controller:



namespace App\Http\Api\Controllers;

use F9Web\ApiResponseHelpers;
use Illuminate\Http\JsonResponse;

class OrdersController
{
    use ApiResponseHelpers;

    public function index(): JsonResponse
    {
        return $this->respondWithSuccess();
    }
}

Optionally, the trait could be imported within a base controller.

Available methods

respondNotFound(string|Exception $message, ?string $key = 'error')

Returns a 404 HTTP status code, an exception object can optionally be passed.

respondWithSuccess(array|Arrayable|JsonSerializable|null $contents = [])

Returns a 200 HTTP status code

respondOk(string $message)

Returns a 200 HTTP status code

respondUnAuthenticated(?string $message = null)

Returns a 401 HTTP status code

respondForbidden(?string $message = null)

Returns a 403 HTTP status code

respondError(?string $message = null)

Returns a 400 HTTP status code

respondCreated(array|Arrayable|JsonSerializable|null $data = [])

Returns a 201 HTTP status code, with response optional data

respondNoContent(array|Arrayable|JsonSerializable|null $data = [])

Returns a 204 HTTP status code, with optional response data. Strictly speaking, the response body should be empty. However, functionality to optionally return data was added to handle legacy projects. Within your own projects, you can simply call the method, omitting parameters, to generate a correct 204 response i.e. return $this->respondNoContent()

Use with additional object types

In addition to a plain PHP array, the following data types can be passed to relevant methods:

  • Objects implementing the Laravel Illuminate\Contracts\Support\Arrayable contract
  • Objects implementing the native PHP JsonSerializable contract

This allows a variety of object types to be passed and converted automatically.

Below are a few common object types that can be passed.

Laravel Collections - Illuminate\Support\Collection

$users = collect([10, 20, 30, 40]);

return $this->respondWithSuccess($users);

Laravel Eloquent Collections - Illuminate\Database\Eloquent\Collection

$invoices = Invoice::pending()->get();

return $this->respondWithSuccess($invoices);

Laravel API Resources - Illuminate\Http\Resources\Json\JsonResource

This package is intended to be used alongside Laravel's API resources and in no way replaces them.

$resource = PostResource::make($post);

return $this->respondCreated($resource);

Motivation

Ensure consistent JSON API responses throughout an application. The motivation was primarily based on a very old inherited Laravel project. The project contained a plethora of methods/structures used to return an error:

  • response()->json(['error' => $error], 400)
  • response()->json(['data' => ['error' => $error], 400)
  • response()->json(['message' => $error], Response::HTTP_BAD_REQUEST)
  • response()->json([$error], 400)
  • etc.

I wanted to add a simple trait that kept this consistent, in this case:

$this->respondError('Ouch')

Contribution

Any ideas are welcome. Feel free to submit any issues or pull requests.

Testing

composer test

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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

Comments
  • Success response with an empty array

    Success response with an empty array

    I dropped this library into one of my projects, but some of the tests started failing because the default value of [] is converted to [ 'success' => true ]. This makes sense if you just call return $this->respondWithSuccess() with no arguments, but in my case I'm returning an array of some models and when there aren't any in the database I actually want the response to be an empty array.

    I ended up using my own method with null as the default:

        public function respondWithSuccess($contents = null): JsonResponse
        {
            $contents = $this->morphToArray($contents ?? [ 'success' => true ]);
    
            return $this->apiResponse($data);
        }
    

    Didn't want to just create a PR though since I know this would be a breaking change.

    opened by AdamGaskins 18
  • Implemented success response with an empty array

    Implemented success response with an empty array

    1. Pulled out default success response data to a field
    2. Added fluent method for setting default success response data
    3. Added tests for usage of new method
    4. Added missing tests for null values in respondWithSuccess, respondCreated, respondNoContent and fixed problems
      • null values were allowed both in types and phpdocs, yet exceptions were thrown when passed, this is fixed and null values are returned as empty arrays
    5. Added missing tests for Arrayable, JsonSerializable and Collection and their empty variants
    6. Strengthened tests to use strict assertions
    hacktoberfest-accepted 
    opened by JacekAndrzejewski 6
  • Added test cases for EloquentCollection & ResourceCollection & Resource object types

    Added test cases for EloquentCollection & ResourceCollection & Resource object types

    Issue

    • https://github.com/f9webltd/laravel-api-response-helpers/issues/11

    Description

    • updated ResponseTest
    • created User model for the test
    • created UserResource for the test
    opened by kzvonov 6
  • Test additional objects types

    Test additional objects types

    As the package now supports content types other than arrays, it would be good to test common use cases.

    The tests currently cover array and Laravel collection types.

    Ideally having tests covering Eloquent collections and API resources would be good.

    This will also require updating workflows.

    I'd imagine we'd end up with something similar to https://github.com/f9webltd/laravel-deletable/tree/master/tests.

    enhancement good first issue help wanted 
    opened by ultrono 6
  • chore: add config files and update `composer.json` test script

    chore: add config files and update `composer.json` test script

    This commit adds the following config files:

    • .editorconfig
    • .gitattributes
    • phpunit.xml.dist

    and also update composer.json test script so it can use phpunit.xml.dist

    P.S.: I know this is a small contribution, but could you please add a hacktoberfest-accepted label on it? I really appreciate it!

    hacktoberfest-accepted 
    opened by chapeupreto 5
  • Allow overriding of default response data

    Allow overriding of default response data

    merging the response array instead of overwriting it would make it possible to just add data. Like this:

    $this->respondWithSuccess(['token' => $superSecret]);
    
    ----------
    
    {
      "success": true,
      "token": "n8tJiZrIS8"
    }
    

    you could still overwrite the success value:

    return $this->respondWithSuccess(['success' => "maybe", 'token' => superSecret]);
    
    ----------
    
    {
      "success": "maybe",
      "token": "Ru4nL9IxE3"
    }
    
    opened by twdnhfr 5
  • Pagination Response

    Pagination Response

    Hi There This is a good work and a very useful package but wee need a response function for pagination

      public function returnDataPagination($paginator,contents,$page)
        {
            if($paginator->url($page))
            {
               $contents = $this->morphToArray($contents);
    
              $data = [] === $contents
                  ? ['success' => true]
                  : $contents;
                return $this->apiResponse($data);
            }
        }
    

    this is the function I hope this help thanks

    question 
    opened by AhemdHegazy 5
  • Response File Type

    Response File Type

    As a developer sometimes I'd like to respond with a file in certain routes, e.g.

    Instead of constructing a response like:

        /**
         * Returns the file as a response.
         *
         * @return Response
         */
        public function getInvoiceAsPdf(): Response
        {
            $file = Storage::disk($this->disk)->file('invoice.pdf');
    
            return new Response($file, Response::HTTP_OK, [
                'Content-Type'        => 'application/pdf',
                'Content-Disposition' => 'attachment; filename="invoice.pdf"',
                'Content-Length'      => strlen($file),
            ]);
        }
    

    I can simply do

        /**
         * Returns the file as a response.
         *
         * @return Response
         */
        public function getInvoiceAsPdf(): Response
        {
            $file = Storage::disk($this->disk)->file('invoice.pdf');
    
            $this->respondWitFile($file);
        }
    
    opened by gogl92 4
  • Advanced use case: respondFailedValidation

    Advanced use case: respondFailedValidation

    Hi,

    The respondFailedValidation method simply returns a message and the response looks like this if multiple errors are present:

    {
        "message": "The test field is required. (and 1 more error)"
    }
    

    Wouldn't it be better if we could know on which field the error occurs? (and have the error code so we can do the translation outside the API maybe).

    Example:

    {
        "message": "validation_rule_failed",
        "errors": {
            "myField.required": {
                "code": "validation_rule_required",
                "field": "myField",
                "message": "The test field is required."
            }
        }
    }
    

    What do you think about this?

    Thank you.

    help wanted 
    opened by valh1996 3
  • Content for respondNoContent?

    Content for respondNoContent?

    I'm a bit confused about the method respondNoContent. The current signature is: public function respondNoContent(?array $data = []) But as it responds with the status code 204, shouldn't it's signature be public function respondNoContent(), so it does not return any content as indicated by the status?

    2.x 
    opened by berbeflo 3
  • Add support for JsonResources (and any other Arrayables/JsonSerializables)

    Add support for JsonResources (and any other Arrayables/JsonSerializables)

    Here's what I was envisioning with #9 ! This is basically the same thing that also happens inside JsonResources:

    https://github.com/laravel/framework/blob/76380cfc6a675d9ad0b1714d6268de13ce406758/src/Illuminate/Http/Resources/Json/JsonResource.php#L98-L102

    opened by AdamGaskins 1
  • File response trait

    File response trait

    Finally, I got some time to work on this, I'm not sure if this is the correct approach but I decided to create a new trait for file-related operations. Please let me know your thoughts.

    For #21

    opened by gogl92 6
Releases(1.5.1)
  • 1.5.1(Feb 15, 2022)

    What's Changed

    • Laravel 9 support by @stephenjude in https://github.com/f9webltd/laravel-api-response-helpers/pull/19

    New Contributors

    • @stephenjude made their first contribution in https://github.com/f9webltd/laravel-api-response-helpers/pull/19

    Full Changelog: https://github.com/f9webltd/laravel-api-response-helpers/compare/1.5.0...1.5.1

    Source code(tar.gz)
    Source code(zip)
  • 1.5.0(Oct 6, 2021)

    What's Changed

    • Allow setting of default response data, with correct handling of nulls and empty arrays by @JacekAndrzejewski in https://github.com/f9webltd/laravel-api-response-helpers/pull/16
    • Add various useful repository configuration files and remove composer.lock by @chapeupreto in https://github.com/f9webltd/laravel-api-response-helpers/pull/17

    New Contributors

    • @JacekAndrzejewski made their first contribution in https://github.com/f9webltd/laravel-api-response-helpers/pull/16
    • @chapeupreto made their first contribution in https://github.com/f9webltd/laravel-api-response-helpers/pull/17

    Full Changelog: https://github.com/f9webltd/laravel-api-response-helpers/compare/1.4.2...1.50

    Source code(tar.gz)
    Source code(zip)
  • 1.4.2(Sep 20, 2021)

    Improve test coverage. Add tests to cover usage of Laravel API resources, Laravel collections and Laravel Eloquent Collections (thanks @kzvonov and @AdamGaskins ) ๐Ÿพ

    Source code(tar.gz)
    Source code(zip)
  • 1.4.1(Sep 18, 2021)

    Refactor tests to reduce code duplication (via data providers) and test additional data types (thanks @rkhan06, @JacekAndrzejewski) ๐ŸŽธ

    Source code(tar.gz)
    Source code(zip)
  • 1.4.0(Sep 18, 2021)

    • Add support for JsonResources (and any other Arrayables/JsonSerializables) (#10, thanks @AdamGaskins) ๐Ÿค–
    • Update readme to document new objects types with examples ๐Ÿช
    • Code tidy, extract logic to fetch message from an exception to method ๐Ÿ˜Ž
    Source code(tar.gz)
    Source code(zip)
  • 1.3.2(Sep 12, 2021)

    What's Changed

    • Fix syntax highlight on readme by @milewski in https://github.com/f9webltd/laravel-api-response-helpers/pull/7

    New Contributors

    • @milewski made their first contribution in https://github.com/f9webltd/laravel-api-response-helpers/pull/7

    Full Changelog: https://github.com/f9webltd/laravel-api-response-helpers/compare/1.3.1...1.3.2

    Source code(tar.gz)
    Source code(zip)
  • 1.3.1(Sep 11, 2021)

  • 1.3.0(Sep 9, 2021)

  • 1.2.2(Sep 9, 2021)

  • 1.2.1(Sep 9, 2021)

  • 1.2.0(Sep 6, 2021)

  • 1.1.0(Sep 3, 2021)

  • 1.0.4(Sep 3, 2021)

  • 1.0.3(Sep 2, 2021)

  • 1.0.2(Sep 2, 2021)

  • 1.0.1(Sep 2, 2021)

  • 1.0.0(Sep 2, 2021)

Owner
F9 Web Ltd.
F9 Web Ltd.
This package aims to help you standardize all your API responses in a simple and structured way.

Laravel API Response This package aims to help you standardize all your API responses in a simple and structured way. By default, the stucture of the

Kode Pandai 6 Dec 6, 2022
Laravel Responder - a package for building API responses, integrating Fractal into Laravel and Lumen

A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.

Alexander Tรธmmerรฅs 776 Dec 25, 2022
A lightweight package for handling API error responses.

Laravel API Errors This package provides an easy way to manage and handle error response for JSON API's. Installation You can install the package via

3 SIDED CUBE 2 Feb 9, 2022
Flexihash is a small PHP library which implements consistent hashing.

Flexihash Flexihash is a small PHP library which implements consistent hashing, which is most useful in distributed caching. It requires PHP5 and uses

Paul Annesley 364 Oct 18, 2022
A super simple package allowing for use MySQL 'USE INDEX' and 'FORCE INDEX' statements.

Laravel MySQL Use Index Scope A super simple package allowing for use MySQL USE INDEX and FORCE INDEX statements. Requirements PHP ^7.4 | ^8.0 Laravel

Vasyl 29 Dec 27, 2022
Builds nice, normalized and easy to consume REST JSON responses for Laravel powered APIs.

REST API Response Builder for Laravel Master branch: Development branch: Table of contents Introduction Why should I use it? Usage examples Features E

Marcin Orlowski 614 Dec 26, 2022
Laravel Jsonable - Well-Formated Responses & Exceptions.

Laravel Jsonable Well-Formated Responses & Exceptions. Documentation You can find the detailed documentation here in Laravel Jsonable Documentation. C

Pharaonic 1 Aug 7, 2022
Caches responses as static files on disk for lightning fast page loads.

Laravel Page Cache This package allows you to easily cache responses as static files on disk for lightning fast page loads. Introduction Installation

Joseph Silber 1k Dec 16, 2022
PlayZ is an esport event organization and management website allowing the creation of tournaments on the most popular video games of the esport scene.

PlayZ the playz to play Table of Contents Description "What is Playz?" In one sentence PlayZ is "an esport event organization and management website a

Antoine Saunier 2 Dec 7, 2021
Madison is a platform for lawmakers to share legislation with their citizens, allowing the community to add comments and suggest improvements.

Madison Madison is an open-source document engagement and feedback platform. While Madison can be used to collaborate on many different kinds of docum

OpenGov Foundation 591 Dec 17, 2022
Jetstrap is a lightweight laravel 8 package that focuses on the VIEW side of Jetstream / Breeze package installed in your Laravel application

A Laravel 8 package to easily switch TailwindCSS resources generated by Laravel Jetstream and Breeze to Bootstrap 4.

null 686 Dec 28, 2022
A Laravel package to simplify using DPO Payment API in your application.

DPO (Direct Pay Online) Laravel Package The best DPO Laravel package, simple Ever This is the package that will help you add DPO Payment API to your L

Zepson Technologies 5 Nov 17, 2022
A Laravel chat package. You can use this package to create a chat/messaging Laravel application.

Chat Create a Chat application for your multiple Models Table of Contents Click to expand Introduction Installation Usage Adding the ability to partic

Tinashe Musonza 931 Dec 24, 2022
Simple package to handle response properly in your API.

Simple package to handle response properly in your API. This package uses Fractal and is based on Build APIs You Won't Hate book.

Optania 375 Oct 28, 2022
Laravel package to find performance bottlenecks in your laravel application.

Laravel Meter Laravel Meter monitors application performance for different things such as requests, commands, queries, events, etc and presents result

Sarfraz Ahmed 230 Dec 27, 2022
Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Rubik 4 May 12, 2022
Laravel Logable is a simple way to log http request in your Laravel application.

Laravel Logable is a simple way to log http request in your Laravel application. Requirements php >= 7.4 Laravel version >= 6.0 Installation composer

Sagar 6 Aug 25, 2022
A simple package to manage the creation of a structure composed of the service and repository layers in a Laravel application

Chapolim Este projeto tem como objetivo fornecer alguns comandos adicionais ร  interface de linha de comando do Laravel, o Artisan, para manipular a es

Eliezer Alves 51 Dec 11, 2022
A simple package to forward Laravel application logs to a Kinesis stream

Laravel Monolog Kinesis Driver A simple package to forward Laravel application logs to a Kinesis stream. Installation Require the package with compose

Pod Point 34 Sep 6, 2022