I think you have already heard about REST APIs before you look into the post. But maybe you don’t know the basics or you might not be understood what it meant.
So, Let’s go from basics, and have a look at API, (Application Programming Interface),
which mostly referred to communication between Client and Server. It is nothing but the architectural style to access the resources through the different Restful web services. for e.g.
If you want to process all of your users from your service, you have to create an API which communicates to your server later databases.
The Anatomy of a Request:
GET All Users:
URL: https://example.com/api/v1/users
METHOD: GET
REQUEST BODY: None
HEADERS: Authorization: Bearer Token “….“, Content-Type: application/json
and you get a response with all users you have:
{
"User": [
{
"property": [
{
"name": "username",
"value": "nimadmin"
},
{
"name": "password",
"value": "AAAAEDFsjJUDxVV9PK+2putOEiUsoPzGAcDjnMGFie4NC01Z"
}
]
},
{
"property": [
{
"name": "username",
"value": "nimuser"
},
{
"name": "password",
"value": "AAAAEI6OGUMkIH/VZWc1wS+G2qTf9QUtmYdjOLdK/PJQLHZo"
}
]
},
]
}
request endpoint
1. URL or Endpoint: The path determines the resources you are requesting, you must have seen something like :username, {username}, /authors?name=ankit etc. There are paths, query parameters, and forms that can be sent with the HTTP requests.
Query Parameters:
API Query parameters can be defined as the optional key-value pairs that appear after the question mark in the URL. Basically, they are extensions of the URL that are utilised to help determine specific content or action based on the data being delivered. Query parameters are appended to the end of the URL, using a ‘?’. The question mark sign is used to separate path and query parameters.
e.g.
https://example.com/articles?sort=ASC&page=2
http//www.techopedia.com/search.aspx?q=database&ion-all
2. METHODS:
A. GET: It is used to get or fetch all or specific resources among the server. Commonly used to show data to the client side.
B. POST: The post method is used to pass the data from client to server, Suppose a new user creation, then data would be further saved in the database with the help of the POST Method.
C. PUT: PUT is similar to POST in that it can create resources, but it does so when there is a defined URL wherein PUT replaces the entire resource if it exists or creates new if it does not exist.
D. PATCH: Unlike PUT Request, PATCH does partial updates e.g. Fields that need to be updated by the client, only that field is updated without modifying the other field.
E. DELETE: If you perform a DELETE request, the server deletes an entry in the database and tells you whether the deletion is successful. A DELETE request performs a DELETE operation.
F. OPTIONS method returns info about API.
G. HEAD method returns info about resources.
3. Headers: It is an HTTP Header that can be used in an HTTP request to provide information about the request context so that the server can tailor the response. For example, the Accept*
headers indicate the allowed and preferred formats of the response. Other headers can be used to supply authentication credentials (e.g. Authorization), control caching, get information about the user agent or referrer, etc.
4. Data/Body: The data contains information you want to be sent to the server. This option is only used with POST
, PUT
, PATCH
or DELETE
requests. e.g.
XML Response:
<Person>
<mobile>1234567890</mobile>
<firstName>Shanaya</firstName >
<lastName>Mehta</lastName>
<age>25</age>
</Person>
JSON Response:
{
"mobile":"1234567890",
"firstName":"Sub",
"lastName":"Stack",
}
A table illustrating the different RESTful API endpoints
Let’s also understand why it is called REST, (Representational State Transfer), when the browser(client) is able to send multiple requests to the server, the server needs no information regarding the client itself, hence it is a stateless transaction of data.
Restful Routes are a standard set of rules that are used to carry out CRUD operations, by using a set of HTTP Methods to finish server requests.
STATELESS:
Communication between client and server must be stateless. This means that each request from the client to the server must contain all the necessary information to complete the transaction.
The main advantage of this constraint is that the system is able to scale better because the server does not have to store the client state between requests. Not having to remember client state information frees up server resources so it can serve more clients simultaneously.
IDEMPOTENCE:
An operation is said to be idempotent if it doesn’t change the result even when applied multiple times. The multiple operations will have the same effect leaving us with the same result that we obtained when it was applied initially for the first time.
e.g. 1*1*1*1*1*1*1*1
Initially, when we multiply 1 with 1 we get 1 as the result. After that, no matter how many times we do the same operation of multiplying with 1, the end result remains the same. Hence this is an idempotent operation.
e.g. 5*5*5*5
The above operation of multiplying by 5 is not idempotent. Because every time the operation is applied, the end result changes like 25, 125, …
REST APIs and Idempotence:
When we say an HTTP method is idempotent in a REST API context, we mean that if we send multiple identical requests one after the other, only the initial request would cause a change in the underlying state of the system and all the following requests will leave the state unaltered.
Method Is Idempotent Is Safe
HEAD yes yes
OPTIONS yes yes
GET yes yes
POST no no
PUT yes no
PATCH no no
DELETE yes no
If you’re wondering what that Is Safe column means, it is just that any HTTP method that doesn’t modify the server’s state is categorised as a safe method. If you look at the table all methods that are supposed to be used to retrieve data (GET, HEAD, OPTIONS) are safe, as their handlers will essentially be a read endpoint.
HTTP Status CODES
When a client requests the server, the server provides an HTTP response status code, Which allows us to understand what is happening on the back-end of a website, and determine what errors need to be fixed. All HTTP response status codes are parted into five categories.
The first digit of the status code defines the categories of response. There are five values for the first digit:
1xx (Informational): The request initiated by the browser is continuing.
2xx (Successful): The request was successfully received, understood, and processed by the server.
3xx (Redirection): Requested information that is no longer at the provided address, further action needs to be taken in order to complete the request.
4xx (Client Error): When there was a problem with the request of the client.
5xx (Server Error): When the client made a valid request, but the server is unable to complete the transfer.
1xx Response Status Codes: Information Request
1xx HTTP status codes indicate that a server is processing information. It alerts the client to wait for a final response.
100 (Continue): The server has received the request headers and the client should proceed to send the request body. It represents that, the client's request is good and processing.
101(Switching Protocol): The requester has asked the server to switch protocols and the server has agreed to switch.
102 (Processing): When the request contains many sub-requests involving file operations, requiring a long time to complete the request than normal. This code indicates that the server has received and is processing the request, but no response is available yet.
2xx Response Status Codes: Success
2xx HTTP status codes show that a request has been received, understood, and completed and the transfer happened as planned.
200 (OK): The exchange between the client and the server is complete. Everything is set up properly and nothing should be negatively impacted. Represent standard response for successful HTTP requests.
201 (Created): The request has been fulfilled, resulting in the creation of a new resource successfully such as a new page.
202 (Accepted): The client requested to create something on the server. The request has been accepted for processing, but the processing has not been completed.
3xx Response Status Codes: Redirection
3xx HTTP status code indicates that the client must take additional action to complete the request. A user agent may automatically redirect a request.
300 (Multiple Choices): Specify multiple choices for the resource from which the client may choose.
301 (Moved Permanently): The request for a resource is permanently directed to another resource. All requests are directed to a particular resource.
302 (Found): Alike 301; but it is a temporary redirect. It directs clients from the old resource to a new one, but it does not tell search engines to update the index for the page. Tells the client to browse another URL.
4xx Response Status Codes: Client Errors
4xx status errors show that problem has occurred on the client side.
400 (Bad Request): The server cannot or will not process the request due to an apparent syntax error from the client.
401 (Unauthorized): When authorization is must obtain the requested resource but failed or has not yet been provided.
404 (Not Found): The resource no longer exists, and the server cannot return any information but may be available in the future.
5xx Response Status Codes: Server Errors
When the client made a valid request, the server is unable to complete the transfer.
500 (Internal Server Error): An error message, shown when an unwanted situation was encountered that does not match any other class errors.
501 (Not Implemented): The server either does not recognize the request method or cannot support the request.
502 (Bad Gateway): The server acts as a gateway and received an invalid message from the upstream server.
There you go! That’s pretty much all you need to know about RESTful APIs!
I hope reading this article gave you a brief idea about the working of the same. Please let me know what you like to know more about RESTful APIs and what you would like me to add to this article so that it can be more informative and easier to follow, especially for beginners!
I would also recommend getting your hands dirty and making a rest API of your own.
Thanks for reading!
Also, Follow me on Medium: https://jinxankit.medium.com
Ref:
Well explained bro. Thanks