Laravel Response Macros for APIs

Jad Joubran
1 min readMar 27, 2016

--

I would like to show you a use case for response macros when building an API with Laravel.

Dealing with APIs

Consistency is one of the most important aspects to consider when building an API. You often find yourself returning 2 types of responses; one for success and one for error.

As you can see, we are returning error responses in a specific format, and success responses in a different format.
Soon enough you’ll notice that you’re repeating this over and over again.

Using response macros

Response macros allow you to define a macro that can be called on the response() function.

We will create a new ResponseMacroServiceProvider and define a success and error macros inside the boot function:

We also need to add this ServiceProvider to the providers array in config/app.php.

So now we can refactor the previous code:

As you can see, response macros help us remain consistent when returning data from the API. Whether it was a success or an error.
This means your front-end API calls will expect a consistent response.

I will write a new tutorial soon on how you can take it a step further in your front-end by implementing Response Interceptors to handle error responses.

--

--