Building a REST API with Laravel? Standardise your responses with JSend

Recently, I was working on a project that needed me to build an API in Laravel. I know how painful it is to work with APIs that are poorly structured, so I decided to adopt JSend for my API responses. JSend basically tries to ensure that the API consumer always knows what to expect in an API response, by defining consistent response formats for success , fail , and error states. Read more about it here.

I quickly tired of writing stuff like this:

$post = Post::create($details);
$response = ["status" => "success", "data" => $post->toArray()];
return response(json_encode($response), 200, ["Content-Type" => "application/json"]);

So I created some helpers to help me out with that. Now all I need to do is

$post = Post::create($details);
return jsend_success($post);

For error responses:

return jsend_error($errorMessage);

And for failures (bad requests):

$data = ["title" => "title is required"];
return jsend_fail($data);

I published the helpers in a package available on Packagist. Just run composer install shalvah/laravel-jsend to use them.

Please check out the source on GitHub, star, share and contribute. I hope it helps improve your productivity. Thanks!



I write about my software engineering learnings and experiments. Stay updated with Tentacle: tntcl.app/blog.shalvah.me.

Powered By Swish