Generalizing API Response & Error Handling — Laravel
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…