Creating REST API in Laravel – Part I(Introduction)

API stands for application program interface and REST stands for Representational state transfer. In any web development, if we want to make separate front end and back end development, Then we can use restful api for transfer of data from front end to back end and vice versa.

According to wikipedia, “Representational State Transfer (REST) is a software architectural style that defines a set of constraints used for creating web services. Web services that conform to the REST architectural style, termed RESTful web services, provide interoperability between computer systems on the Internet.”

In laravel, we can easily create restful API services. There may be different ways to create api in laravel. Now, we will create a Controller which returns different kind of http responses after processing a request.

We will extend this controller in another controller where we will create api. After sending client request to the controller then, based on outcome we will return one of above function.

More details about Http errors and exception are in following link:

HTTP Error and Exceptions in Laravel

Let’s discuss all the functions above.

Fail Function

When some thing went wrong while processing request, we will return this function as response. This function correspond to the HTTP_INTERNAL_SERVER_ERROR with status code 500.

Success Function

For the successful outcome while processing request, we will return this function. This function corresponds to HTTP_OK with status code 200.

Not Found

If something we are looking for is not found then we will return this function as response. This function corresponds to HTTP_NOT_FOUND with status code of 404.

Bad Request

When request sent to server doesn’t fulfill the necessary requirements then, we will send this function as response. This function corresponds to HTTP_BAD_REQUEST with status code of 400.

Forbidden

when resource we are trying to get is absolutely forbidden for some reason, then we will send this function as response. This function corresponds to HTTP_FORBIDDEN with status code of 403.

Unauthorized

When resource we are trying to get is unauthorized for us for some security reason then, we will send this function as response. This function corresponds to HTTP_UNAUTHORIZED with status code of 401.

You can find all the details in github: https://github.com/sagautam5/laravel-rest-api

In the next article, we will create migration, model, resource controller and routes for article. In order to create restful api, We will use article as our entity.



sagautam5

sagautam5

Computer Enginner, A Laravel Developer,
http://sagargautam.stacklearning.com

Leave a Reply

Your email address will not be published. Required fields are marked *