For quite a few projects now, I have been implementing API in Laravel 5. I did no programming for UI. I found that Laravel 5 is made for API implementation.

When we talk about API, we would want it to be RESTful & safe. It is ideal that the endpoints return JSON responses with appropriate response codes. All of these comes inbuilt with Laravel 5.

This is going to be a brief overview of the features available in favour of API rather than detailed explanation about features and how-tos.

RESTful:

The framework is RESTful. When you define routes, you will do them the RESTful way. For e.g. if you want to access user’s ToDo you will define route to be /users/{users}/todos.

Moreover, there are functionalities such as route prefixing - it allows us to prefix a group of routes. For e.g. you could prefix all user’s todo resources with ‘api’. After doing that, you won’t have to write the prefix every time you define new route in that group. It will be automatically prefixed! Such a bliss!

Let us also mention Route Model Binding. What this does is that when your route has, say, user id in it, it will automatically find the relevant record from the database and you will directly get the model object in your controller as argument. This is especially good when working with APIs, because, if you just want to return the requested todo as-is, you will be writing only one line in your controller method! We will talk about this line in a bit.

 

JSON Responses:

Eloquent Model classes, which represent our database result as an Object also inherently support several things that are essential for API.

Every Model object has a method toJson(). Cool right?

You can define which model properties to white-list or blacklist when converting to JSON.

You can define attributes to append to the object. These appended attributes are useful when you want to add additional info that is not present in the database.

The white-list and blacklist can be controlled at execution time.

When you fetch more than one record from database, it is returned as Collection class’ object. Now, that class is “arrays on fire”. Notable method is toJson(). Look at the class to know more.

An example:

Suppose you are accessing a user’s details. And you have bound your user resource to routes (route-model binding). Then your route might be: /users/2 and following would be your controller method:

public function show(Request $request, $user)
{
    return response()->json($user);
}

That’s it! That’s all you’ve to do in the controller!

 

HTTP Error Responses:

Laravel throws appropriate Exceptions when things go wrong. For e.g. when validation fails, it throws 422 - Unprocessable Entity. This is done everywhere. You can also throw custom Exceptions.

Exceptions extend PHP’s Exception class. So methods such as getCode(), getMessage() are available.

Now, Laravel has a Handler class. The class resides in app/Exceptions/Handler.php. All the exceptions can be handled from here! Throw exceptions from anywhere, with the messages you want, with the codes that you think are appropriate, and handle them all from here (or extend the class, separate code based on exceptions).

So what does it mean? It means that you can return appropriate JSON responses with HTTP Status Code from the Handler. Controllers will never have to return errors! They’ll only worry about returning 200-OK responses or throw exceptions.

 

Additional Features:

BugSnag and other such services - You can integrate with platform error monitoring services such as BugSnag with ease.

Laravel Collective Package - This package is amazing. It has annotations, which will make things even easier with Routes, Models etc.

CORS - Handling CORS is super easy and gives enough control over what goes in and comes out of your API. A package I use is - barryvdh/laravel-cors

Request Validation - Laravel 5 has inbuilt support for Request validation via Request class. Refer to docs for further details.

Middlewares - Laravel Middlewares decides whether to let the request go any further when it enters your app. It comes into picture the earliest. So, you could check for authorization, request type (whether it is json request or not), resource ownership etc in Middleware and can be sure that your API is being accessed only by the clients you’ve authorized.

 

I think I’ve made it clear why Laravel should be the choice to go for when you are making your API. It’s as easy as it could get with Laravel.

 

Happy coding!