RESTful API response in Laravel 5

I am creating a RESTful API with Laravel. My API always returns JSON. What I would like to do is to maintain the logic of the answer in one place. Here's how I do it right now in the API controller that I'm pointing to Route::controller(). A nice and ultra-useful example:

public function getDouble($number) {
    try {
        if (!is_numeric($number)) {
            throw new HttpException(400, 'Invalid number.');
        }

        $response = $number * 2;
        $status = 200;
    }
    catch (HttpException $exception) {
        $response = $exception->getMessage();
        $status   = $exception->getStatusCode();
    }

    return response()->json($response, $status);
}

In this example, my API route will be, for example, an /double/13accessible GET method. The problem is that I repeat this attempt ... catch block in each method. I would like my API methods to be like this:

public function getDouble($number) {
    if (!is_numeric($number)) {
        throw new HttpException(400, 'Invalid number.');
    }

    return $number;
}

And then, catch these exceptions and form the JSON elsewhere. What is the best approach in terms of a good application architecture?

+4
source share
1

, App\Exceptions\Handler.

, likeo:

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    if($e instanceof HttpException) {
        return response()->json($e->getMessage(), $e->getStatusCode());
    }

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

, , Middleware .

  • (, ApiResponseFormatterMiddleware)
  • "App\Http\Kernel" $routeMiddleware.
  • api, .

- :

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $response = $next($request);

    return response()->json($response->getOriginalContent());
}

, , , , .

+12

All Articles