marcinorlowski / laravel-api-response-builder Goto Github PK
View Code? Open in Web Editor NEWBuilds nice, normalized and easy to consume REST JSON responses for Laravel powered APIs.
License: MIT License
Builds nice, normalized and easy to consume REST JSON responses for Laravel powered APIs.
License: MIT License
Can I customize the message text to save successfully?t here.
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:
Expected behavior
Receiving an status code 422
**Environemnt:Desktop (please complete the following information):
I'm getting this error Uncaught RuntimeException: Missing "{$keyName}" for "{$className}"
ever since I updated with composer.
My composer version: ^2.1
Tried 3.0.1
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.
When passing custom message string to error reporting methods (i.e. errorWithMessageAndData()
the error_code
is not validated and it will pass, even it is outside of defined range. ExceptionHandlerHelper
is relying on this behavior in @dev branch.
Add configurable debug
data JSON key so we can have any key needed.
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.
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:
'locale' => 'fa'
in config/app.php
.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;
}
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',
],
resources/lang/fa/api.php
:<?php
return [
'PHONE_NUMBER_FLOOD' => 'دفعات تلاش شما بیش از حد مجاز است.',
'OTP_CODE_INVALID' => 'رمز یکبار مصرف وارد شده صحیح نیست.',
'ACTIVATION_CODE_INVALID' => 'کد فعالسازی وارد شده صحیح نیست.',
'OTP_CODE_CREATE_FAILED' => 'امکان ارسال رمز یکبار مصرف وجود ندارد.',
'ACTIVATION_CODE_CREATE_FAILED' => 'امکان ارسال کد فعالسازی وجود ندارد.',
];
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:
Inproper buiding of HTTP error code in Exception Handler Helper for uncaught exceptions. Due to broken conditions, error codes higher than 499 can slip by causing Response object to fail later
We're using API Resources to filter the model attributes that are transformed in JSON.
Do you plan to support UserResources in the ResponseBuilder in addition to Collections and Arrays?
How can I return a video of say 999mb or a pdf file?
buildErrorResponse() must check upper bounds of http_code too, not just the lower 400.
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.
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.
Describe the bug
A clear and concise description of what the bug is.
To Reproduce
Steps to reproduce the behavior:
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):
Additional context
Now in this case it returns:
{
"success": false,
"code": 112,
"locale": "en",
"message": "HTTP exception Symfony\\Component\\HttpKernel\\Exception\\HttpException",
"data": null
}
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.
Move EX_* consts from BaseApiCodes to ResponseBuilder class
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()
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)
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.
Rename ErrorCode class to ApiCode class in preparation for success() codes feature
RuntimeException: Missing "{$keyName}" for "{$className}" mapping in /var/www/.../vendor/marcin-orlowski/laravel-api-response-builder/src/ResponseBuilder.php:58
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.
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.
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!
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;
}
}
https://packagist.org/packages/marcin-orlowski/laravel-api-response-builder
Can't update to v6.3.1 with composer update
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
.
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!
Add support for Laravel 5.5's auto-discovery feature: laravel/framework#19420
i want to change the response code for all my success calls and bad calls
When I use the FormRequest it just gives me a 500 internal error instead of giving me a array of the fields that failed validation.
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.
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.
Debug information should not pollute data
node and be completely separated (i.e. by having own root leaf)
Process $data recursively to handle nested objects like Model, Collection etc
I believe require-dev
dependency orchestra/testbench: ~3.1
should rather be rchestra/testbench: ^3.1
For now it always would add trace elements to returned JSON when app.debug
is true
.
As PHP 5.x is EOL, no need to support it in future release. Legacy code can still pull current version though.
Make user's ApiCode class mandatory but turning ApiCodeBase into abstract class.
@php artisan package:discover --ansi
In ResponseBuilderServiceProvider.php line 89:
Class 'MarcinOrlowski\ResponseBuilder\Arr' not found
Laravel Version: 6.1
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.
Some methods signatures prevent null
from being allowed as argument, and using of such will cause Fatal Error to be thrown.
Expand classes
config map to hold method name to call to have object converted to JSON, so we could have literally any type automatically converted.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.