Creating General API Responder in Laravel

Laravel is a MVC framework still it is being used to develop API centric applications.

So while creating APIs in Laravel, the important thing is to standardize API request and response to make all APIs consistence.

For this you have to freeze a format for request and also for response.

In this post I’m going to show you a good approach to create a general response format in json. Which can be used in all applications.

First of let us discuss that what is required in all response

  1. Success (Whether the API request was valid or not)
  2. Response Code (Helps front-end developers to add specific conditions because response message may changed)
  3. Response message ( Helps to debug)
  4. Metadata (Data about data)
  5. Data

For example API to return list of users

 

 

Sometimes only metadata and data may not be required just like after updating a user

 

 

So for this we can create a Trait so that we can use inheritance and can call function without creating object.

I am creating a folder Traits in app directory in which I will create appResponseTrait

But before creating this trait we need to create a translation file where we will have all API response code and its message

Within resources/lang/en I am creating 2 files

  • apiSuccess.php
  • apiError.php

In which response code and messages are written like

 

Now I am going to create appResponseTrait within app/Traits

 

Now here is how to use this trait in our controller

 

Leave a Reply