REST API ANATOMY
What really is RESTful API? And its Anatomy?
Ever wondered how login/signup on a website works on the behind (in back-end)?
Let’s say you’re trying to find videos about Batman on Youtube. You open up Youtube, type “Batman” into a search field, hit enter, and you see a list of videos about Batman. A REST API works in a similar way. Your search for something, and you get a list of results back from the service you’re requesting from.
REST stands for Representational State Transfer protocol.
So, what is REST? According to Wikipedia:
Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. RESTful Web services allow the requesting systems to access and manipulate textual representations of Web resources by using a uniform and predefined set of stateless operations
In general,
REST is basically a set of rules for communication between a client and a server.
( or )
REST is a set of rules that allow programs to talk to each other. The developer creates the API on the server and allows the client to talk to it.
There are a few architectural constraints on the definition of REST:
- Client-Server Architecture: The user interface of the website (UI) should be separated from data storage (request), so each part can be scaled individually. In general, a client is someone who is requesting resources and are not concerned with data storage, which remains internal to each server. A server is someone who holds the resources and is not concerned with the user interface or user state. The client doesn’t need to know anything about business working logics and Server doesn’t need to know anything about frontend UI.
- Statelessness: In order to handle Request, the necessary states required are within the request itself and server would not store anything related to the session and no assumptions should be made if the server has any data from previous requests. In REST, the client must include all information for the server to fulfil the request whether as a part of query params, headers or URI. Statelessness enables greater availability since the server does not have to maintain, update or communicate that session state.
- Layered system: the client should not be able to tell if it is communicating directly with the server or some intermediary. An application architecture needs to be composed of multiple layers. Each layer doesn’t know anything about any layer other than that of the immediate layer. These intermediary servers (be it proxy or load balancers) allow for scalability and security of the underlying server.
Rules of REST API:
There are certain rules which should be kept in mind while creating REST API endpoints.
- REST is based on the resource or noun instead of action or verb-based. It means that a URI of a REST API should always end with a noun.
Example: /api/users is a good example, but /api?type=users is a bad example of creating a REST API.
- HTTP verbs/methods are used to identify the action. Some of the HTTP verbs are — GET, PUT, POST, DELETE, UPDATE, PATCH.
- Always use plurals in URL to keep an API URI consistent throughout the application.
- Send a proper HTTP code to indicate a success or error status.
How does REST look?
In very broad terms, we ask the server for a certain data or ask it to save some data, and the server responds to the requests. In terms of programming, there is an endpoint (a URL) that the server is waiting to get a request. We connect to that endpoint and send in some data about us (since REST is stateless, no data about the request is stored) and the server responds with the correct response. Each URL is called a request while the data sent back to you is called a response.
Postman to show you the request and response:
The returned data is in JSON (JavaScript Object Notation) and can be accessed directly. Here, https://official-joke-api.appspot.com/random_joke
is called an endpoint of an API. There will be a server listening on that endpoint for requests like the one we made.
Anatomy of REST:
now we know that data can be requested by the client and the server will respond appropriately. Let’s look deeper into how a request is formed.
It’s important to know that a request is made up of four things:
- The endpoint
- The method
- The headers
- The data (or body)
- Endpoint: Endpoint(or route) is the URL you request for. It follows this structure:
root-endpoint/?
The root-endpoint is the starting point of the API you’re requesting from. The root-endpoint of Github’s API is https://api.github.com
while the root-endpoint Twitter’s API is https://api.twitter.com
. The path determines the resource you’re requesting. Think of it like an automatic answering machine that asks you to press 1 for service, press 2 for another service, 3 for yet another service and so on.
You can access paths just like you can link to parts of a website. For example, to get a list of all posts tagged under “JavaScript” on Smashing Magazine, you navigate to https://www.xyz.com/tag/javascript/
. https://www.xyz.com/
is the root-endpoint and /tag/javascript
is the path.
To understand what paths are available to you, you need to look through the API documentation.
/users/:username/repos
Any colons (:
) on a path denotes a variable. You should replace these values with actual values of when you send your request. In this case, you should replace :username
with the actual username of the user you’re searching for. If I’m searching for my Github account, I’ll replace :username
with pkmr
.
The endpoint to get a list of my repos on Github is this:
https://api.github.com/users/pkmr/repos
The final part of an endpoint is query parameters. Technically, query parameters are not part of the REST architecture, but you’ll see lots of APIs use them. So, to help you completely understand how to read and use API’s we’re also going to talk about them. Query parameters give you the option to modify your request with key-value pairs. They always begin with a question mark (?
). Each parameter pair is then separated with an ampersand (&
), like this:
?query1=value1&query2=value2
When you try to get a list of a user’s repositories on Github, you add three possible parameters to your request to modify the results given to you:
If you’d like to get a list the repositories that I pushed to recently, you can set sort
to push
.
https://api.github.com/users/pkmr/repos?sort=pushed
2. Method: Earlier, I wrote that you can either request data or modify it, but how will the server know what kind of operation the client wants to perform? REST implements multiple ‘methods’ for different types of request, the following are the most popular:
- GET: Get a resource from the server.
- POST: Create a resource to the server.
- PATCH or PUT: Update existing resource on the server.
- DELETE: Delete existing resource from the server.
3. Headers: The additional details provided for communication between client and server (remember, REST is stateless). Some of the common headers are:
Request:
- host: the IP of client (or from where request originated)
- accept-language: language understandable by the client
- user-agent: data about client, operating system and vendor
Response:
- status: the status of request or HTTP code.
- content-type: type of resource sent by server.
- set-cookie: sets cookies by server
4. Data: (also called the body or message) contains the info you want to send to the server.
API Parameters
- PATH: required to access the resource E.g.
/cars
,/fruits
- Query Parameters: optional filter the list E.g.
/cars?type=SUV&year=2010
- Body: Resource specific logic. Advance search query. Sometimes it might have both Query and body.
- Header: Should contain global or platform-wide data. E.g. API key parameters, encrypted keys for auth, device type information e.g. mobile or desktop or endpoint, device data type e.g. XML or JSON. Use the header to communicate these parameters
HTTP Status Codes
Use correct status codes
CodesMeaning1xxRequest received and understood.2xxAction requested by the client was received, understood and requested.3xxClient must take additional action to complete the request. Most of these status codes are used in URL Redirection.4xxIntended for situations where it seems the error was caused by the client.5xxThe server failed to fulfil a request. In general, the numbers follow the following rules:
- 200+ means the request has succeeded.
- 300+ means the request is redirected to another URL
- 400+ means an error that originates from the client has occurred
- 500+ means an error that originates from the server has occurred
Little more on 2xx!
- 201 Resource Created. POST
/cars
should return HTTP 201 created withlocation
header stating how to access the resource E.g.location
:api.com/cars/124
in header
202 — Accepted
Use this if the task is huge to run. Tell the client, it has accepted the request and will/is process/processing No payload is returned
204 — No content
Used when deleted DELETE cars/124
Returns no content. But can also return 200 OK
if API intends to send the deleted resource for further processing.
The dangerous 5xx resources!
- 500 Internal Server Error
- 504 Gateway Timeout. The server didn’t receive a timely response
Less known 4xx suggests that you are passing the wrong parameter. Can also pass information that is wrong. E.g.
DELETE /cars/MH09234
returns 4xx
or message Expecting int car id /car/id got string car/MH09234
Credit: For a more detailed article on REST API header and on freecodeCamp