{ REST : API }

Let us suppose we have a server that is hosting the information about the student. If a client, say a web/android app needs the information regarding the student, then the client must request the server for the resource and the server should send back the response to the client.

API is the acronym for Application Programming Interface which allows clients and servers to talk to each other. 

Key Elements

Request URL/Endpoint: Request URL is the address of the resource where information/data is present. Let’s assume the URL of the web application is https://agamimys.com/ which consists of data about students. So in order to get the information about the particular student, the request URL can be https://agamimys.com/student/1 . The operation will request the server to get the information of the student whose student number/id is 1.

Request Header

Request Header is the additional information sent to the server. This usually contains the information related to the authorization.

Suppose the web application wants to restrict access to their resource only to a particular client then the request header is sent containing a key/token usually known as Apikey.

Whenever the request is made from the client, the server receives the key in the header, then the server validates the key and based on the result it processes the request.  

Request Methods

Request methods help you describe what operation you are going to perform on the resource. Methods can be POST, GET, PUT, DELETE, etc. Different methods are used to perform different operations. For example, we use the GET method to fetch the information of student 1.

Request Body

Request body is sent with the request when we want to add information/data on the server. The method used is POST, It means the client tells the server that the data in the request body needs to be added to the server.  

Response Body

 When a request is made from the client, the server processes the request and sends back the response. The requested data is sent in the response body. 

Response Code

When a response is sent back to the client, It  consists of a status code . Status code is usually 200(OK) if there is no error. Different status codes are used in different cases . Such as 404(Not Found),400(Bad Request),401(Unauthorized) etc.

Methods In API

Rest API allows us to perform all types of CRUD (Create, Read, Update, Delete) operations. Different methods are used to perform different operations. All the methods have their specific role. Some of the most commonly used methods are :

HTTP GET

The GET method is used to retrieve (Read) the information from the server.It is only used to perform a READ operation on the data. The data modification is not allowed hence these are also said to be safe methods.

For any request using the GET method, if the resource is found then it will return with status 200(OK) and response body. 

The response body consists of the information/data which we want from the server. It can be either XML or JSON.

If the resource is not found then it returns with status 404 (NOT FOUND).

HTTP POST

The POST method is used to add new information (Create) to the server.   POST requests are never cached and also do not remain in the browser history.

HTTP PUT

The PUT method is used to Update/Modify the existing information on the server if it exist.If the information does not exist then it adds the new information.

 HTTP DELETE

The DELETE method is used to delete the existing information.

HTTP Response Codes 

Every time the client requests the server for any resource the server responds back with the information and status code. The HTTP status code indicates whether the client request for the resource has been successfully completed.

All HTTP status codes are separated into five different categories

Informational Responses (1XX)

This class of status code indicates that the request is received and everything is OK so far so that client can continue with the request.

Successful (2XX)
This class of status code represents that the client request is successfully received, accepted, and processed. This status indicates that everything is fine with the request and on the server.

Redirects (3XX)
This class of status code is used to indicate the client that the additional action is needed to complete the request

Client Error (4XX)
This class of status code indicates that there is something wrong with the client’s request. For example, the API key used by the client to authorize the request on the server is incorrect.

Server Error (5XX)
This class of status code indicates that the server is experiencing the problem. In this case, the server is failing to process the client’s request.

Some Commonly Used HTTP Response Codes :

CodeDescription
100Continue
102Processing
200Ok
201Created
202Accepted
204No Content
304Not Modified
400Bad Request
401Unauthorized
402Payment Required
403Forbidden
404Not Found
408Request Timeout
409Conflict
500Internal Server Error
502Bad Gateway
503Service Unavailable
507Insufficient Storage

APIs Making It Easy
It is a fact that we cannot develop everything in our application but we all want to use various services. If we start making everything of our own then our application will become slow and heavy. The solution is APIs. we can use different APIs to perform different functions with minimal code. All we need to do is make use of the APIs which already exist and are tested.

Some of the common APIs are listed below:

Weather API
These days weather apps are very common, in fact, everyone is using the weather app on the phone. suppose you are creating an application that will display the real-time weather based on the location. So the question is how the application is going to work. Are you going to place the sensor all over the place and measure the weather? That would cost you a lot. So the simplest way is to use some API that can get you the weather and you can then simply display the results. There are many open-source APIs available to do so. All you need to do is just pass the location details and in response, you will get the desired results.

Payment API 
Payment APIs are also too common these days. most of the eCommerce using these APIs for payment transactions.mostly all the payment gateways have their integration Apis for online transactions. The integration is simple and secure. we just need to pass the parameters as specified by the payment gateway provider. After successful or failed transactions, the payment gateway responds back with the result.

Twilo
Sometimes we need to integrate the communication services in our platform. like calling and SMS. Twilio is one of the cloud communication platforms that provides us all the ways of communication from our own platform. 

All you need to do is get the authorization credentials from the Twilio and then you can use their APIs to send and receive SMS and calls.

Amazon S3
When an application grows, then there is a need for a large and secure storage option. Amazon S3 provides the API to do so. Amazon S3 is a simple storage service that allows you to store and retrieve any amount of data, at any time from anywhere.

All we need to do is use their APIs to add or fetch the data. We need authorization details provided by amazon which is required during the API calls.

Login APIs
If you are developing a website where users need to register themself then you may need a fast and efficient way to make them register. There may be a type of users who does not like to fill up the registration form, So what you can do is provide them the options like login as google or log in as Facebook. By doing this you are making it easy for the user as they don’t need to fill up their details and do not need to remember the password either. All they need to do is use the existing Google or Facebook account. Both Google and Facebook provide APIs which allow the developers to use the login facilities.

Perform CRUD operation using Rest API

We will be using Node.js, Express, and SQL to perform CRUD operation.we will use Sequelize for interacting with the database.

Create   (POST) 
Read     (GET)
Update  (PUT)
Delete   (DELETE)

Express: Express.js is a Node js web application server framework. It makes web application development fast and simple. It is easy to configure and allows us to define routes based on HTTP methods and URLs. It includes various middleware modules that help us in performing additional tasks on request and response.

To Install – npm -g express

Sequelize: Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

Let’s create a simple program for Books.

Start by creating a package.json file.
Go to the project folder .
Run command  $ npm init.

Install dependencies

$ npm install express  mysql  sequelize –save

Initially, index.js is loaded. The index.js will route all the incoming routes with /api to route.js.

index.js

In route.js we loaded the controller to perform operations. All four operations will be performed in the controller. route.js will just redirect the incoming request to the function based on the request.

model/Book.js

The model represents a table in the database. Instances of this class represent a database row.

controller.js
Controllers consist of the definitions of the function called from the route.js.

In the controller, we are interacting with the database to add, fetch, update and delete information.

Once the operation is completed the response is sent back in JSON  format with status code.

try ,catch is used to handle the error in the controller.

Require the model in the controller file to perform crud operation.

  1. POST Request

To add the book information in the database POST request is used.

The content-type is application JSON and the information is passed in the body. Once the request is received by the controller, the create function will insert the book information in the database and send back the response 200 to the client.

In case of any error status, 500 is sent back to the client.

  1. GET Request

To get the book information from the database GET request is used.

findAll will fetch all the books from the database and send back the response to the client in JSON format.

  1. UPDATE Request

To update the book information in the database PUT request is used.

The update function will update the books against the ID and send back the response 200 to the client.

  1. DELETE Request

To delete the book information from the database DELETE method is used.

delete function will delete  the books from the database against the Id and send back the response 200 to the client.

Test Your API
We can test the API using any api testing tool.One of the popular API testing tools is Postman.

Postman is a scalable API testing tool that allows you to test the calls to the API you already created.

It acts as a client so that you can hit the server and perform all the operations on the server.

Postman consists of all the methods and functions that are required to test the API.

1 .Add Book (CREATE)
Here, we are inserting the book information in the database.
Request:
URL : http://localhost/core/api/addBook
METHOD : POST
HEADER  : application/json
BODY :
  {
               “title” : “To Kill a Mockingbird”,
                “author”  : “Harper Lee”,
                “publisher” : “J. B. Lippincott & Co.”,
                “category” : “Thriller”
 }

Response:
Status : 200
{
  message : “Book Added Successfully”
}

In this API we are adding a book using the API addBook,As the request is to create/insert, the method used is POST.

The body consists of the JSON which is having the information about the book.

After clicking on the send button, the API call hits the server and data is inserted in the database. 

The response we get is in JSON format with status code 200.

2. Get Books (READ)
Here, We are fetching the book information from the database.
Request : 

URL :  http://localhost/api/getbooks

METHOD : GET

Response:

Status : 200

[

{

      “title” : “To Kill a Mockingbird”,

                “author”  : “Harper Lee”,

                “publisher” : “J. B. Lippincott & Co.”,

                “category” : “Thriller”

 },

{

      “title” : “The sound and the fury”,

                “author”  : “William Faulkner”,

                “publisher” : “‎Jonathan Cape‎”,

                “category” : “Fiction”

 }

]

This API will fetch all the books from the database. As the request is to get/fetch the data, therefore the method used is GET.

Once we click the send button to execute the API call the server fetch all the books and respond back with the data in json format with status code 200.

3 .Update Book (UPDATE)

Here, we are inserting the book information in the database.

Request:

URL : http://localhost/core/api/book/2

METHOD : PUT,

Params : 2 (bookId)

HEADER  : application/json

BODY :

  {

         “publisher” : “J. B. Lippincott & Co.”

  }

Response:

Status : 200

{

  “message” : “Book Updated Successfully”   

}

This API will update the book information. To update the book information ID is passed as a params so that the information will be updated against the particular ID.

Suppose there are 20 books,Each book will have their unique ID also called primary key.

We call the updateBook API , the method used will be PUT as the information is being updated. In body the updated information is passed ,suppose we want to update the publisher of the book having ID 2. So in params we pass the ID i.e 2 and in body the information.

The server will update the publisher against the book id 2.

Once the operation is completed , Server responds back with status 200 and message.

4.Delete Book (DELETE)

Here, we are inserting the book information in the database.

Request:

URL : http://localhost/core/api/book/2

METHOD : DELETE,

Params : 2 (bookId)

Response:

Status : 200

{

  “message” : “Book Deleted Successfully”   

}

This API will delete the book from the database. To delete the book information ID is passed as a params so that the information will be deleted against the particular ID.

The method used will be DELETE as the information is being deleted from the database. 

Suppose we want to delete the book having ID 2. So in params we pass the ID i.e 2.

The server will delete the book having ID 2.

Once the operation is completed , Server responds back with status 200 and message.