Generalizing API Response & Error Handling — Laravel

Cerwyn Cahyono
4 min readApr 26, 2020
Photo by Negative Space from Pexels

Some people say that if you want to develop an API, then you have to look at your API consumer’s perspective. It means that, all the responses (whether they are errors or not) must have a consistent and standardized JSON structure/response. So in this article, I will show you how to generalize API responses that can be used in a Laravel project and how to handle errors.

Content Overview

  • Migration
  • ApiResponser
  • Parent ApiController
  • Extends to ApiController
  • Api Routing
  • Error Handler

Before we start, I will create a general JSON structure for this entire project. Of course, you can create your own API response structure. This structure will be used in every response we return to the API consumer.

{
"status" : "Success",
"message" : null,
"data" : null
}

We have the structure now, let’s implement it!

Migration

Setup the Laravel project first using composer

composer create-project --prefer-dist laravel/laravel generalizing-response

Then, we need to migrate the database. In this article, let’s don’t talk about…

--

--

Cerwyn Cahyono

PHP/Backend Engineer at Undercurrent Capital Pte Ltd — Data Science Enthusiast