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

Overview

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 API response looks like this:

{
  "success": true,
  "title": "Users",
  "message": "Active users only",
  "data": [
    // users...
  ],
  "errors": [],
}

Note: For now, if you want to customize the response structure, you need to manually extend ApiResponse class and override toResponse method.

Install

$ composer require kodepandai/laravel-api-response

Usage

The ApiResponse class implement a Fluent trait from laravel, so you can chain methods as you like. See the example below.

Return a success response

use Illuminate\Http\Response;
use KodePandai\ApiResponse\ApiResponse;

ApiResponse::success(['version' => 'v1.0.0']);

ApiResponse::success(['name' => 'Taylor Otwell'])
           ->title('User')
           ->message('User Data');

ApiResponse::success()
           ->statusCode(Response::HTTP_CREATED)
           ->message('Sucessfully create a user.');

Return an error response

By default the statusCode for error API response is HTTP_BAD_REQUEST.

use Illuminate\Http\Response;
use KodePandai\ApiResponse\ApiResponse;

ApiResponse::error()
           ->title('Failed')
           ->message('Only admin can delete a user.');

ApiResponse::error(['email' => ['The email field is required.']])
           ->statusCode(Response::HTTP_UNPROCESSABLE_ENTITY);
           
ApiResponse::error()
           ->statusCode(Response::HTTP_SERVICE_UNAVAILABLE)
           ->message('Out of service, please comeback later.');

Validate or Fail

Use this helper to validate user submitted request, then return an ApiResponse::error response if the validation fails.

With this helper, now you can use something like $request->validate() without worrying on how to handle the redirect response or validation errors separately.

// without helper

// in the controller, using validate helper.
// if not handled correctly, it can return a redirect reponse instead of json response
$request->validate(['email' => 'required']);

// or using validator
$validator = Validator::make(['email' => 'required']);
if ($validator->fails()) {
    return JsonResponse($validator->errors());
}

//----

// with this helper

// it will automatically return a json response if validation fails
// if the validation passes, it will return validated data
$validatedData = ApiResponse::validateOrFail([
    'email' => 'required|email',
    'username' => 'required|unique:users,username',
]);

Throwing an Exception

Instead of using ApiResponse manually, you can also throw an exception and will get the same response according to the exception type.

This package provides two exception: ApiException and ApiValidationException.

  • ApiException: throw an api error
  • ApiValidationException: throw a validation error
if (! DB::hasDriver('mysql')) {
  throw new ApiException('Mysql driver not found!', Response::HTTP_INTERNAL_SERVER_ERROR);
}

if ($user->balance <= 100_000) {
  throw new ApiValidationException(['balance' => ['Balance must be greater than 100K']]);
}

Handling all Exception

If you would like to convert all laravel exception to return an ApiResponse, you can use the ExceptionHandler::renderAsApiResponse helper.

// file: Exception/Handler.php

use KodePandai\ApiResponse\ExceptionHandler;

// new laravel (>= 8)
public function register()
{
    $this->renderable(function (Throwable $e, $request) {
        if ($request->wantsJson()) {
            return ExceptionHandler::renderAsApiResponse($e);
        }
    });
}

// old laravel (<= 7)
public function render($request, Throwable $exception)
{
    if ($request->wantsJson()) {
        return ExceptionHandler::renderAsApiResponse($exception);
    }

    return parent::render($request, $exception);
}

Develop

  • To test run composer test.
Comments
  • Should `validateOrFail` method return array?

    Should `validateOrFail` method return array?

    https://github.com/kodepandai/laravel-api-response/blob/166847ea9a997d4be735c78417a7fa86c19f8cb2/src/ApiResponse.php#L119-L124

    Should validateOrFail method return validated input array? This will usefull for sanitizing user input. For now this method return void.

    question 
    opened by axmad386 2
  • feat: add support for laravel 7 and 8

    feat: add support for laravel 7 and 8

    This PR not just adding support for laravel 7 and 8, but also refactoring the core and improve documentation.

    @axmad386 please kindly review and discuss features here.

    opened by lakuapik 2
  • fix: Exception Handler not convert ApiResponse to JsonResponse

    fix: Exception Handler not convert ApiResponse to JsonResponse

    This PR is trying to fix bug when ApiException has been thrown but not converted to JsonResponse. This solution not optimal, more appropriate solution is #15 but it will change the return type of ApiException getResponse method. That will break the v1. So this PR is aim to support v1. This is the best we can do. See you on v2 soon :)

    opened by axmad386 1
  • Instance of Model not supported to be returned as data

    Instance of Model not supported to be returned as data

    We cannot pass instance of Model to ApiResponse data. This code will throw InvalidArgumentException

    $user = User::find($userId);
    ApiResponse::success($user);
    

    For workaround, we must convert model instance to array.

    $user = User::find($userId);
    ApiResponse::success($user->toArray());
    
    opened by axmad386 0
  • Return 404 not found when model not found

    Return 404 not found when model not found

    right now, when laravel throwing \Illuminate\Database\Eloquent\ModelNotFoundException the status code is 500:

    image

    it should be rendered as 404 and no traces:

    image
    opened by lakuapik 0
  • ApiException `toReponse` method missing return statement

    ApiException `toReponse` method missing return statement

    https://github.com/kodepandai/laravel-api-response/blob/166847ea9a997d4be735c78417a7fa86c19f8cb2/src/Exceptions/ApiException.php#L35-L42 this will break in laravel Exception Handler because toResponse should return JsonResponse instead of null.

    bug 
    opened by axmad386 0
  • Add withError method

    Add withError method

    just like error

    ApiResponse::error(['email' => ['The email field is required.']]);
    

    this method will be like this:

    ApiResponse::withError('email', 'The email field is required')
    

    helpful if user want to just add one error at a time.

    enhancement help wanted 
    opened by lakuapik 0
  • TODO: Add configuration to allow custom api response structure

    TODO: Add configuration to allow custom api response structure

    Some user might want to have a custom response structure.

    For now, it can be achived by extending the ApiResponse class.

    The issue is, the other exception like ApiException and ApiValidationException still uses the original ApiResponse class. So it will not change the response structure for the user.

    We need a config file to map which ApiReponse class to be used in application.

    help wanted 
    opened by lakuapik 5
Releases(v1.3.1)
  • v1.3.1(Dec 23, 2022)

  • v1.3.0(Dec 14, 2022)

    Fixed

    • Laravel exception handler does not recognize Responsable trait (#11)
    • Return 404 NOT_FOUND for laravel ModelNotFoundException (#10)

    Added

    • Support Arrayable interface for response data (#13)
    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Jul 24, 2022)

    Fixed

    • Add try/catch handler when parsing exception to response
    • Return 401 HTTP_UNAUTHORIZED for laravel AuthenticationException
    • Get data directly from ResourceCollection data type
    • Add more tests to improve coverage
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Jun 28, 2022)

  • v1.0.0(Jun 13, 2022)

Owner
Kode Pandai
Kumpulan Kode Buatan Anak Indonesia
Kode Pandai
Validate your input data in a simple way, an easy way and right way. no framework required. For simple or large. project.

wepesi_validation this module will help to do your own input validation from http request POST or GET. INTEGRATION The integration is the simple thing

Boss 4 Dec 17, 2022
laravel package help you to implement geographical calculation, with several algorithms that help you deal with coordinates and distances.

Geographical Calculator Geographical Calculator was developed for laravel 5.8+ to help you to implement geographical calculation, with With several al

karam mustafa 342 Dec 31, 2022
A simple package allowing for consistent API responses throughout your Laravel application

Laravel API Response Helpers A simple package allowing for consistent API responses throughout your Laravel application. Requirements PHP ^7.4 | ^8.0

F9 Web Ltd. 441 Jan 5, 2023
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
Renders consistent HTTP JSON responses for API-based projects

Laravel API Response is a package that helps to provide and render a consistent HTTP JSON responses to API calls as well as converting and formatting

Kennedy Osaze 43 Nov 20, 2022
Testbench Component is the de-facto package that has been designed to help you write tests for your Laravel package

Laravel Testing Helper for Packages Development Testbench Component is the de-facto package that has been designed to help you write tests for your La

Orchestra Platform 1.9k Dec 29, 2022
Hoa is a modular, extensible and structured set of PHP libraries

Hoa is a modular, extensible and structured set of PHP libraries. Moreover, Hoa aims at being a bridge between industrial and research worlds. Hoa\Rul

Hoa 624 Dec 30, 2022
Build structured navigation menus in Filament.

Build structured navigation menus in Filament. This plugin for Filament provides a Navigation resource that allows to build structural navigation menu

Ryan Chandler 61 Dec 30, 2022
Build structured navigation menus in Filament.

Build structured navigation menus in Filament. This plugin for Filament provides a Navigation resource that allows to build structural navigation menu

HappyToDev 0 Jun 29, 2022
You already have your dream house? Sam Building will help you find the perfect home.

SAM BUILDING Setup Fork or clone this repo! git clone github.com/Igorballo/Real-Estate-App.git Installation des dépendances npm install #or yarn insta

null 4 Nov 29, 2022
Electrik is a full-featured, open-source, starter-kit to help you build you your SaaS application.

Electrik Electrik is a full-featured and open-source stater-kit for for your next SaaS application. It's built on top of Laravel, Livewire, neerajsoha

Electrik 129 Dec 31, 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
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
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
Relational Metrics - lararvel package help you to make your metrics easier

Relational Metrics This package will help you to make your metrics easier, You could get metrics about your Models, Models depending on their relation

Syrian Open Source 25 Oct 12, 2022
This package should help you with creating and managing a Laravel DDD Application

This package should help you with creating and managing a Laravel DDD Application. This package is heavily inspired by "Laravel beyond CRUD" from Spatie.

J. Regner 158 Dec 25, 2022
Postgis extensions for laravel. Aims to make it easy to work with geometries from laravel models.

Laravel Wrapper for PostgreSQL's Geo-Extension Postgis Features Work with geometry classes instead of arrays. $model->myPoint = new Point(1,2); //lat

Max 340 Jan 6, 2023
this package can help you to test race condition in Laravel Feature Test

Laravel Async Testing this package can help you to test race condition in Laravel Feature Test Requirements Laravel versions 5.7, 6.x, 7.x and 8.x PHP

Recca Tsai 61 Nov 5, 2022