Giter Site home page Giter Site logo

marcinorlowski / laravel-api-response-builder Goto Github PK

View Code? Open in Web Editor NEW
718.0 17.0 79.0 1.94 MB

Builds nice, normalized and easy to consume REST JSON responses for Laravel powered APIs.

License: MIT License

PHP 100.00%
laravel api json php rest-api api-helper json-response chained-apis

laravel-api-response-builder's Introduction

REST API Response Builder for Laravel

REST API Response Builder for Laravel

Latest Stable Version Codacy Grade Badge Monthly Downloads Code Quality Code Coverage License

Master branch: Unit Tests Static Analysis Coding Standards

Development branch: Unit Tests Static Analysis Coding Standards

Table of contents


Introduction

ResponseBuilder is a Laravel package, designed to help you build a nice, normalized and easy to consume REST API JSON responses.

Benefits

ResponseBuilder is written for REST API developers by REST API developer and is based on long-lasting experience on both "sides" of API. It's lightweight, with no dependencies, extensively tested and simple to use yet flexible and powerful, with support for on-the-fly data conversion, localization support, automatic message building, chained APIs and (hopefully) exhaustive documentation. But that's not all! The JSON structure produced by ResponseBuilder is designed with users of your API in mind, so its structure is predictible and well-defined which makes dealing with your API using ResponseBuilder library a breeze. Simple JSON response, with well-defined and predictable structure, easy to consume without any hassle or trickery. Your clients will love it. And will love you too :)

You are also covered in a case of emergency, as provided ExceptionHandlerhelper, ensures your API keeps talking JSON (and NOT lame HTML) to its clients even in case of unexpected.

Did I mention, you would also get testing traits that automatically add PHPUnit based unit test to your whole ResponseBuilder related code and configuration with just a few lines of code absolutely for free?

Features

License

  • Written and copyrighted ©2016-2024 by Marcin Orlowski <mail (#) marcinorlowski (.) com>
  • ResponseBuilder is open-sourced software licensed under the MIT license

laravel-api-response-builder's People

Contributors

ehsan-soleimanian avatar faridaghili avatar iamroi avatar jcmcclorey avatar marcinorlowski avatar mustafa-online avatar szepeviktor avatar victorioustr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-api-response-builder's Issues

Add configurable encodingOptions to avoid character escaping

For now, we rely on Laravel's default $encodingOptions of Symfony\Component\HttpFoundation\JsonResponse which by default is JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT. This causes valid UTF8 characters to being returned escaped i.e. ąćę => \u0105\u0107\u0119. We need encodingOption config value passed to json() + perhaps option to override by each call.

Endless loop with ExceptionHandler in "laravel/framework": "5.2.45"

Endless loop with ExceptionHandler in "laravel/framework": "5.2.45"

Interface

<?php
namespace Test\Fooooooo\Bar;

interface Bar {}

implementation

<?php
use Test\Foo\Bar;

class Foo implements Bar {}

then

$a = new Foo();

is caught by ExceptionHandler but it seems like autoload loops forever so all ends up with unhandled 500 due to reaching nesting limit.

buildResponse() should have access to raw message key

buildResponse() method should deal with localization itself, instead of being provided with final message by make(). This would allow anyone to better handle localization or tweak the message creation if for any reason built-in approach is not sufficient w/o need of changing any other method.

On the ExceptionHandler the render should check for if it's a Ajax request.

When I just used return ExceptionHandlerHelper::render($request, $e); it even responded with a json response on regular http 404 error in the browser. Which would not be user friendly.

public function render($request, Exception $e)
{
        if ($request->ajax() || $request->wantsJson())
        {
            return ExceptionHandlerHelper::render($request, $e);
        }
        
        return parent::render($request, $e);
}

So I think it should check for if it's a ajax request. The user just needs to add the Accept:application/json header. Or if you have a better way that would be awesome to see!

Update UnitTests for PHPUnit 9

The @ExpectedException, @expectedExceptionCode, @expectedExceptionMessage, and @expectedExceptionMessageRegExp annotations are deprecated. They will be removed in PHPUnit 9. Refactor your test to use expectException(), expectExceptionCode(), expectExceptionMessage(), or expectExceptionMessageRegExp() instead.

Add option to return custom code with success() methods

Currently there's no way to return other code than 0 with success... methods. This may be problematic if one would like to return some sub-status i.e. indicating different state (esp. in case of deferred execution, like "pending", "queue" etc)

Wrong config path when publishing using vendor:publish

When I install the package on a brand new fresh install of Laravel 5.4 & call vendor:publish it creates a directory for the config file.

// Wrong
/config/response_builder.php/response_builder.php

// Right
/config/response_builder.php

The package config doesn't work when its in another directory under the config directory.

Getting this error after composer update

RuntimeException: Missing "{$keyName}" for "{$className}" mapping in /var/www/.../vendor/marcin-orlowski/laravel-api-response-builder/src/ResponseBuilder.php:58

Unable to get localization working

Describe the bug
I'm not able to use the localization feature and can't find any doc about it.

To Reproduce
Steps to reproduce the behavior:

  1. I have 'locale' => 'fa' in config/app.php.
  2. I have ApiCodes.php in app:
<?php

namespace App;

use MarcinOrlowski\ResponseBuilder\BaseApiCodes;

class ApiCodes extends BaseApiCodes
{
    public const PHONE_NUMBER_FLOOD = 100;
    public const OTP_CODE_INVALID = 101;
    public const ACTIVATION_CODE_INVALID = 102;
    public const OTP_CODE_CREATE_FAILED = 103;
    public const ACTIVATION_CODE_CREATE_FAILED = 104;
}
  1. In config/response_builder.php I've set map as follow:
    'map' => [

        \App\ApiCodes::PHONE_NUMBER_FLOOD => 'api.PHONE_NUMBER_FLOOD',
        \App\ApiCodes::OTP_CODE_INVALID => 'api.OTP_CODE_INVALID',
        \App\ApiCodes::ACTIVATION_CODE_INVALID => 'api.ACTIVATION_CODE_INVALID',
        \App\ApiCodes::OTP_CODE_CREATE_FAILED => 'api.OTP_CODE_CREATE_FAILED',
        \App\ApiCodes::ACTIVATION_CODE_CREATE_FAILED => 'api.ACTIVATION_CODE_CREATE_FAILED',

    ],
  1. And of course resources/lang/fa/api.php:
<?php

return [

    'PHONE_NUMBER_FLOOD' => 'دفعات تلاش شما بیش از حد مجاز است.',
    'OTP_CODE_INVALID' => 'رمز یکبار مصرف وارد شده صحیح نیست.',
    'ACTIVATION_CODE_INVALID' => 'کد فعالسازی وارد شده صحیح نیست.',
    'OTP_CODE_CREATE_FAILED' => 'امکان ارسال رمز یکبار مصرف وجود ندارد.',
    'ACTIVATION_CODE_CREATE_FAILED' => 'امکان ارسال کد فعالسازی وجود ندارد.',

];
  1. Finally in controller:
return ResponseBuilder::error(ApiCodes::PHONE_NUMBER_FLOOD);

Expected behavior
If everything go well, I should get this response:

{
    "success": false,
    "code": 100,
    "locale": "fa",
    "message": "دفعات تلاش شما بیش از حد مجاز است.",
    "data": null
}

But instead, it gives:

{
    "success": false,
    "code": 100,
    "locale": "fa",
    "message": "Error #100",
    "data": null
}

Notice the Error #100 part.

Environemnt:

  • Name and version of OS: Windows 10
  • PHP version 7.2
  • Laravel version 6.4

Create own interface for automatic object data conversion

Create own interface for automatic object data conversion, without the need of manual configuration. It would be sufficient for the object to implement that interface. Conversion method name must not be toArray() to not potentially conflict, but default implementation should try to call onArray() on self or throw failure exception.

Lumen support

Response Builder is NOT compatible with Lumen framework, mainly due to lack of Lang class.
I also got no experience with Lument so please send PR if you would like to help making ResponseBuilder compatible with Lumen.

Model to response

Hi, maybe will be fine to cast not only array objects.

Now I need to do that with my model:

$users = User::get()->toArray();
return ResponseBuilder::success($users);

Will be greate to call like:

$users = User::all();
return ResponseBuilder::success($users);

Thanks!

Uncaught exception message encoding issue

When PDO is unable to connect to configured database, it will throw PDOException with the descriptive message, yet it seems it may not necessary be UTF8 in all the cases and it ends up as: SQLSTATE[HY000] [2002] Nie mo�na nawi�za� po��czenia, poniewa� komputer docelowy aktywnie go odmawia. causing InvalidArgumentException being thrown by JsonResponse with message Malformed UTF-8 characters, possibly incorrectly encoded.

Exception does not support getStatusCode()

FILE: marcin-orlowski/laravel-api-response-builder/src/ExceptionHandlerHelper.php:79

if ($http_code == 0) {
    $http_code = $ex->getStatusCode(); 
// $ex is an Exception not a Symfony HttpException, it sholud be $ex->getCode()

unauthenticed() is never called when using ExceptionHandler with Laravel 5.3+

Inside the exception handler render I have:

return ExceptionHandlerHelper::render($request, $e);

Just below that the unauthenticed function is never called

/**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }
        return redirect()->guest(route('login'));
    }

So if I want the unauthenticed to be called I have to remove the ExceptionHandlerHelper. Is this by design?

I know why because the parent::render() function checks for exceptions https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/Exceptions/Handler.php#L113 your exception handler doesn't use the unauthenticated so it throws 500 internal error instead of a 401.

Validation error message?

I noticed when reading through the Readme you don't have anything for validation errors set in place?

Is this something you are planning on adding or have you already thought about it?

Thanks for your work & time on this project.

ExceptionHandlerHelper Sensitive Information In Message

It will be good if you check is debug mode enabled or not to show the actual class. I’m not sure but the package should handle is it ok to show the actual message for the exception because there could be some sensitive information. I’m not sure but I think it’s a real case and maybe should be handled.

http_code == 0 will never be executed

FILE: marcin-orlowski/laravel-api-response-builder/src/ExceptionHandlerHelper.php:77

if ($http_code < 400) {
    $http_code = 0;
} elseif ($http_code == 0) {   // this will never be executed
    $http_code = $ex->getStatusCode();

    if ($http_code < 400) {
        $http_code = 0;
    }
}

Handle Forbidden StatusCode in ExceptionHandlerHelper

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Add abort(403) in some API route
  2. Make request to that route.

Expected behavior
I expect to work like abort(401).

{
    "success": false,
    "code": 114,
    "locale": "en",
    "message": "Forbidden",
    "data": null
}

**Environemnt:Desktop (please complete the following information):

  • Name and version of OS MacOS Catalina
  • PHP version 7.3
  • Laravel version 6.4.0

Additional context
Now in this case it returns:

{
    "success": false,
    "code": 112,
    "locale": "en",
    "message": "HTTP exception Symfony\\Component\\HttpKernel\\Exception\\HttpException",
    "data": null
}

http_code 5xx

Hi there,

Other HTTP codes, like redirection (3xx) or (5xx) are not allowed and will throw \InvalidArgumentException.

Why are 5xx http codes not allowed?

Thank you in advance for you answer.

Fix the response status code for ValidationException in ExceptionHandlerHelper

Please align the ValidationException code with the default one for laravel which is 422 instead of just 400 like in your code.

To Reproduce
Steps to reproduce the behavior:

  1. Add a route validation
  2. Make request to this route with invalid/missing data

Expected behavior
Receiving an status code 422

**Environemnt:Desktop (please complete the following information):

  • Name and version of OS: macOS Catalina
  • PHP version 7.3
  • Laravel version 6.4.0

Drop PHP 5.x support

As PHP 5.x is EOL, no need to support it in future release. Legacy code can still pull current version though.

error when installing the package

@php artisan package:discover --ansi
In ResponseBuilderServiceProvider.php line 89:
Class 'MarcinOrlowski\ResponseBuilder\Arr' not found

Laravel Version: 6.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.