Blog Detail

22

Jul
Render HTTP JSON Responses for API-based Projects in Laravel cover image

arrow_back Render HTTP JSON Responses for API-based Projects in Laravel

Laravel API Response is an amazing package that helps to provide and render consistent HTTP JSON responses to API calls as well as convert and format exceptions to JSON responses.

Installation

You can install the package via composer:

composer require kennedy-osaze/laravel-api-response

You can publish the translation files using:

php artisan vendor:publish --tag="api-response-translations"

Optionally, you can publish the config file using:

php artisan vendor:publish --tag="api-response-config"

Usage

Using Package Traits

This package provides two traits that can be imported into your projects; namely:

  • The \KennedyOsaze\LaravelApiResponse\Concerns\RendersApiResponse trait which can be imported into your (base) controller class, middleware class, or even your exception handler class
  • The \KennedyOsaze\LaravelApiResponse\Concerns\ConvertsExceptionToApiResponse trait which should only be imported into your exception handler class.

So we can have on the base controller class (from which all other controllers may extend from):

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use KennedyOsaze\LaravelApiResponse\Concerns\RendersApiResponse;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests, RendersApiResponse;
}

Or some random controller class:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use KennedyOsaze\LaravelApiResponse\Concerns\RendersApiResponse;

class RandomController extends Controller
{
    use RendersApiResponse;
}

In any case, you have access to a load of methods which you can call to render your data. This includes:

// Successful Responses
return $this->okResponse('This is a random message', $data = null, $headers = []);
return $this->createdResponse('This is a random message', $data = null, $headers = []);
return $this->acceptedResponse($message, $data, $headers);
return $this->noContentResponse();
return $this->successResponse($message, $data = null, $status = 200, $headers = []);

// Successful Responses for \Illuminate\Http\Resources\Json\JsonResource
return $this->resourceResponse($jsonResource, $message, $status = 200, $headers = []);
return $this->resourceCollectionResponse($resourceCollection, $message, $wrap = true, $status = 200, $headers = []);

// Error Responses
return $this->unauthenticatedResponse('Unauthenticated message');
return $this->badRequestResponse('Bad request error message', $error = null);
return $this->forbiddenResponse($message);
return $this->notFoundResponse($message);
return $this->clientErrorResponse($message, $status = 400, $error = null, $headers = []);
return $this->serverErrorResponse($message);
return $this->validationFailedResponse($validator, $request = null, $message = null);

$messages = ['name' => 'Name is not valid'];
$this->throwValidationExceptionWhen($condition, $messages);

Also to handle exceptions, converting them to API response by using the \KennedyOsaze\LaravelApiResponse\Concerns\ConvertsExceptionToApiResponse trait in your exception handler which provides the renderApiResponse public method and this can be used as follows:

<?php

namespace App\Exceptions;

use App\Traits\HandleApiException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use KennedyOsaze\LaravelApiResponse\Concerns\ConvertsExceptionToApiResponse;
use Throwable;

class Handler extends ExceptionHandler
{
    use ConvertsExceptionToApiResponse;

    public function render($request, Throwable $e)
    {
        return $this->renderApiResponse($e, $request);
    }
}

Response Data

The response data $data to be rendered for successful response can be any of the following type:

  • array e.g. [‘name’ => ‘Dummy’]
  • standard object e.g. new stdClass
  • integer e.g. 1
  • boolean e.g. true
  • any Model object, the instance of \Illuminate\Database\Eloquent\Model
  • any Collection object, the instance of \Illuminate\Support\Collection
  • any JsonResource object, the instance of \Illuminate\Http\Resources\Json\JsonResource
  • any Jsonable object, the instance of \Illuminate\Contracts\Support\Jsonable
  • any JsonSerializable object, the instance of \JsonSerializable
  • any Arrayable object, the instance of \Illuminate\Contracts\Support\Arrayable

Any of the above can be used stored as $data and used thus:

use \KennedyOsaze\LaravelApiResponse\ApiResponse;

ApiResponse::create(200, 'A message', $data)

This package has a lot more features and methods with code examples, If you want to learn more, you can visit its complete documentation on Github.

Closing Note

Codebrisk is here to help you grow your business. Our expert developers have plenty of experience in Laravel Custom Web Application Development. We can enhance the performance of applications with easy syntax, third-party API integrations, and built-in functions, followed by a high level of security to prevent unauthorized access to data. We always provide a customized website solution tailored to our client’s needs. So if you’re interested, you can get in touch with us or get a free quote from us.

Published at : 22-07-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project