DEV Community

Cover image for Developing Quality API with Laravel - Tip #1
Hesam Rad
Hesam Rad

Posted on • Updated on

Developing Quality API with Laravel - Tip #1

Developing quality API is one of the most important factors in an application's success. In this series I try to bring easy but helpful tips to help you develop quality APIs.

So let us begin...

Tip #1 - Do not hardcode response messages into your codebase.

What is mean by this is that you don't have to hardcode every message into the codebase. You can simply store them in a file so in case of any change so you can handle the situation with ease.

Don't do this.

return response()->json([
    'message' => 'Yo, everything is cool!'
], Response::HTTP_OK);
Enter fullscreen mode Exit fullscreen mode

What if you use this piece of code in, say, 100 functions and now you want to change the message because your boss is not ok with it?

The easiest way is to ctrl + shift + f that string in vscode and replace all of it in a matter of seconds; and let's not even think about the idea of manually replacing each string ourselves.

But why do this when there's an easier and more professional way?

Let's do this instead.

Create a response.php file in /resources/lang/en folder of your Laravel project and create an array of whatever keys and values you want. But for the purpose of this article we can do this:

return [
    'successful_action' => 'Yo, everything is cool!',
];
Enter fullscreen mode Exit fullscreen mode

And modify that return statement with this:

return response()->json([
    'message' => __('response.successful_action')
], Response::HTTP_OK);
Enter fullscreen mode Exit fullscreen mode

Now even if there are a million of these return statements in your codebase and you want to change that message to something more appropriate you can easily change the value of successful_action key inside you response.php file and you're good to go.

Note
Please remember to return proper HTTP status code with each response you send back to front-end guys. They'll greatly appreciate it.

Last Words
If you know a better way or any tips at all, please feel free to share it with me, I'd be more than happy to learn something from you.


Link to cover image

Top comments (0)