Member-only story

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 making complicated tables. We can use the migration template for Users that Laravel has when we create a new project. You can find it in the database->migrations->create_user_table.php. So, let’s run the migration

php artisan migrate

Don’t forget to set your database in an .env file of your project. If your migration is successful, then you can see new tables appear in your database.

ApiResponser

First thing first, let’s create an API response structure. We will create a new file in app/Traits/ApiResponser.php which will give you a general model of the JSON response. You can modify it as you wish, but in this case we stick into our standard response as explained above.

--

--

Cerwyn Cahyono
Cerwyn Cahyono

Written by Cerwyn Cahyono

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

Responses (5)

Write a response