Laravel RESTful API Development

These days REST API plays major role in web development and developers are heavily use REST API when they build applications. REST is very popular because it is very simple to use and you can build it on top of the HTTP.

What is REST?

REST stands for Representation State Transfer. We will try to understand what it means in the following section

REST is not a standard
REST is not a specification
REST is not a protocol

Then, what is REST?
We can call this as generally agreed upon set of principle and constraints.

Definition

There are six constrains in REST
1 Client Server Architecture
Client manages the user interface and server manages the data storage. So we have complete separation between data and its representation
2 Statelessness
3 Cache-ability
4 Layered system
5 Code on demand
6 Uniform interface

How does REST relate to HTTP?

HTTP is the Hyper Text Transfer Protocol which is used to access the HTML documents in the World Wide Web

REST must not run on HTTP.
REST and HTTP are not linked together but this pair can work together.
When REST run on HTTP protocol to give us access to web resource we call it RESTfull service

You can map noun to HTTP verbs

GET
You can use GET to retrieve resource or collection of resource. You should never use GET other than retrieving the data

DELETE
You can use verb DELETE to delete resource

PUT
Put is used to update the resource

POST
You can use this to create new resource
You can use to update the state of the resource
You can use this verb to do action what other verbs can not do

When you consider the Employee example, you can use GET verb to list the employee and get the details of selected employee

API Resource In Laravel

You can use Laravel Eloquent to get the data from the database. For example Product::all() will return the all products. Now you can use API resource to convert this data set to JSON data to send via response.

API End points

What is API end point?

If you want to create new product you can define a new route like this

/createProduct
You can write the other API end point like this

/getProduct
/updateProduct
/deleteProduct

Although you can create the end point like above that is not the standard way of creating them. So you can adhere to the following method

Your URL should contain noun only. You have to avoid verbs and actions in the endpoint

So /createProduct should become /products

Then, how do define Add Product, Update Product, List Products etc?.

You can use HTTP methods (GET, POST, DELETE, PUT). We normally call this as HTTP verbs. Together HTTP verbs, we can define our all end points

HTTP Method Path Meaning
GET /products Get all products
GET /products/12 Get product where id is equal to 12
PUT /products/12 Update product where id is equal to 12
DELETE /products/12 Delete product where id is equal to 12

You can see that this representation is very meaningful than the previous