SocolaDaiCa / laravel-api-response-helpers

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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 in your controller:

<?php

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 excpetion object can optionally be passed.

respondWithSuccess(?array $contents = [])

Returns a 200 HTTP status code

respondOk(string $message)

Returns a 404 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 $data = [])

Returns a 201 HTTP status code, with response optional data

respondNoContent(?array $data = [])

Returns a 204 HTTP status code, with response optional data. Technically the response body should be empty. However, functionality to optionally return data was added to handle legacy projects.

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')

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

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 rob@f9web.co.uk instead of using the issue tracker.

Credits

License

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

About

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

License:MIT License


Languages

Language:PHP 100.0%