Laravel 5’s Approach to RESTful API Response

The function can provide either a successful or failed response and is compatible with Laravel versions 7 and 8. It can handle validation and 500 responses. The response can be managed through Fractal, which is well-documented at http://fractal.thephpleague.com/. Additionally, Phil Sturgeon’s book, “Build APIs You Won’t Hate,” offers valuable insights. The goal is to maintain response logic in a centralized location.


Question:

As a Laravel developer, I consistently ensure the smooth operation of my API. To streamline the process, I aim to centralize response logic. Presently, the API controller referenced by

Route::controller()

contains an amusing and highly beneficial example of my current approach.

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);
}

As an example, my
API route
could be

/double/13

which can be accessed through the GET method. However, the issue is that I have to repeat the try…catch block in each method. My aim is to have my API methods structured in a similar manner.

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

What would be the optimal application architecture approach for catching exceptions and creating JSON in a separate location?


Solution:

Response on Exception

One way to accomplish this is by managing the exception within

AppExceptionsHandler


.

One way to achieve this is by placing the code within the render method, as shown below:

/**
 * Render an exception into an HTTP response.
 *
 * @param  IlluminateHttpRequest  $request
 * @param  Exception  $e
 * @return IlluminateHttpResponse
 */
public function render($request, Exception $e)
{
    if($e instanceof HttpException) {
        return response()->json($e->getMessage(), $e->getStatusCode());
    }
    return parent::render($request, $e);
}

Success Response

There are multiple methods to accomplish this task, but I believe that Middleware is the most appropriate option.

  • Design a middleware module, which can be named as ApiResponseFormatterMiddleware.
  • Add

    $routeMiddleware

    to the array in your ‘AppHttpKernel’.
  • Utilize it on the API paths where you desire to analyze the responses.

You can consider doing something similar to:

/**
 * Handle an incoming request.
 *
 * @param  IlluminateHttpRequest  $request
 * @param  Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $response = $next($request);
    return response()->json($response->getOriginalContent());
}

Naturally, some adjustments to the parsing logic may be necessary to achieve your desired content output, but the framework remains consistent.

Frequently Asked Questions

Posted in Php