Rest API
What is REST? What do you understand by RESTful Web Services?
REST, which stands for Representational State Transfer, is an architectural style for designing networked applications. It uses a stateless, client-server communication model where each request from the client to the server must contain all the information needed to understand and process the request. The server does not store any client context between requests
A RESTful API (Application Programming Interface) adheres to the principles of REST. It facilitates communication between different software applications over the internet by following a set of rules and conventions.
Statelessness: Each request from the client to the server must be able to stand alone, with no dependencies on prior requests. This means the server does not keep any client-specific data between requests. REST APIs are stateless, meaning each request must contain all the information needed to process it.
Client-Server Architecture: The client and server are separate entities that communicate over a network. The client is responsible for the user interface and user experience, while the server manages the data and business logic. The client software should only know the URI of the requested resource
Cacheable Responses: Responses from the server can be cached by the client to reduce latency and server load. This is achieved by including appropriate cache-control directives in the response headers.
Uniform Interface: The API provides a uniform way of interacting with resources. This is typically achieved through the use of standard HTTP methods (GET, POST, PUT, DELETE) and URIs (Uniform Resource Identifiers) to identify resources
Layered System: The architecture allows for intermediaries (like proxies or load balancers) between the client and the server. This enables the creation of complex systems without affecting the client or server directly
RESTful APIs are designed to be platform-independent, supporting multiple data formats (e.g., JSON, XML), and can leverage HTTP caching mechanisms to improve performance. They are widely used due to their simplicity, scalability, and ease of use, making them a preferred choice for developing web services and integrating disparate systems
What is URI?
Uniform Resource Identifier is the full form of URI which is used for identifying each resource of the REST architecture. URI is of the format:
<protocol>://<service-name>/<ResourceType>/<ResourceID>
What is URL?
URL: Uniform Resource Locator has the information regarding fetching of a resource from its location.
Examples include:
http://abc.com/samplePage.html
ftp://sampleServer.com/sampleFile.zip
file:///home/interviewbit/sampleFile.txt

What are the features of RESTful Web Services?
Every RESTful web service has the following features:
The service is based on the Client-Server model.
The service uses HTTP Protocol for fetching data/resources, query execution, or any other functions.
The medium of communication between the client and server is called “Messaging”.
Resources are accessible to the service by means of URIs.
It follows the statelessness concept where the client request and response are not dependent on others and thereby provides total assurance of getting the required data.
These services also use the concept of caching to minimize the server calls for the same type of repeated requests.
These services can also use SOAP services as implementation protocol to REST architectural pattern.
What is statelessness in REST?
Ans: In REST architecture, statelessness refers to a communication method in which the server completes every client request independently of all previous requests. Clients can request resources in any order, and every request is stateless or isolated from other requests.
Statelessness simplifies the communication between clients and servers, as there is no need for the server to store or manage the client's state between requests.

What are HTTP Status codes?
These are the standard codes that refer to the predefined status of the task at the server. Following are the status codes formats available:
1xx - represents informational responses
2xx - represents successful responses
3xx - represents redirects
4xx - represents client errors
5xx - represents server errors
Most commonly used status codes are:
200 - success/OK
201 - CREATED - used in POST or PUT methods.
304 - NOT MODIFIED - used in conditional GET requests to reduce the bandwidth use of the network. Here, the body of the response sent should be empty.
400 - BAD REQUEST - This can be due to validation errors or missing input data.
401- UNAUTHORIZED - This is returned when there is no valid authentication credentials sent along with the request.
403 - FORBIDDEN - sent when the user does not have access (or is forbidden) to the resource.
404 - NOT FOUND - Resource method is not available.
500 - INTERNAL SERVER ERROR - server threw some exceptions while running the method.
502 - BAD GATEWAY - Server was not able to get the response from another upstream server.
Can you tell what constitutes the core components of HTTP Request?
In REST, any HTTP Request has 5 main components, they are:
Method − This part tells what methods the request operation represents. Methods like GET, PUT, POST, DELETE, etc are some examples.
URI − This part is used for uniquely identifying the resources on the server.
HTTP Version − This part indicates what version of HTTP protocol you are using. An example can be HTTP v1.1.
Request Header − This part has the details of the request metadata such as client type, the content format supported, message format, cache settings, etc.
Request Body − This part represents the actual message content to be sent to the server.
What constitutes the core components of HTTP Response?
HTTP Response has 4 components:
Response Status Code − This represents the server response status code for the requested resource. Example- 400 represents a client-side error, 200 represents a successful response.
HTTP Version − Indicates the HTTP protocol version.
Response Header − This part has the metadata of the response message. Data can describe what is the content length, content type, response date, what is server type, etc.
Response Body − This part contains what is the actual resource/message returned from the server.
What are the HTTP Methods?
HTTP Methods are also known as HTTP Verbs. They form a major portion of uniform interface restriction followed by the REST that specifies what action has to be followed to get the requested resource. Below are some examples of HTTP Methods:
GET: This is used for fetching details from the server and is basically a read-only operation.
POST: This method is used for the creation of new resources on the server.
PUT: This method is used to update the old/existing resource on the server or to replace the resource.
DELETE: This method is used to delete the resource on the server.
PATCH: This is used for modifying the resource on the server.
OPTIONS: This fetches the list of supported options of resources present on the server.
The POST, GET, PUT, DELETE corresponds to the create, read, update, delete operations which are most commonly called CRUD Operations.
What are the best practices to develop RESTful web services?
Below are some best practices for developing REST APIs:
Since REST supports multiple data formats, it is however good practice to develop REST APIs that accept and responds with JSON data format whenever possible. This is because a majority of the client and server technologies have inbuilt support to read and parse JSON objects with ease, thereby making JSON the standard object notation.
Content-Type must be set to
application/JSON
on the request header.
While naming the resource endpoints, ensure to use plural nouns and not verbs. The API endpoints should be clear, brief, easy to understand, and informative.
User Management
GET
/users
: Retrieve a list of usersPOST
/users
: Create a new userGET
/users/{userId}
: Retrieve a specific user by IDPUT
/users/{userId}
: Update a specific user by IDDELETE
/users/{userId}
: Delete a specific user by ID
Product Management
GET
/products
: Retrieve a list of productsPOST
/products
: Create a new productGET
/products/{productId}
: Retrieve a specific product by IDPUT
/products/{productId}
: Update a specific product by IDDELETE
/products/{productId}
: Delete a specific product by ID
Error Handling should be done gracefully by returning appropriate error codes the application has encountered. REST has defined standard HTTP Status codes that can be sent along with the response based on the scenario.
Error codes should also be accompanied by appropriate error messages that can help the developers to take corrective actions. However, the message should not be too elaborate as well which can help the hacker to hack your application.
Common status codes are:
400 - Bad Request – client-side error - failed input validation.
401 - Unauthorized – The user is not authenticated and hence does not have authority to access the resource.
403 - Forbidden – User is authenticated but is not authorized to access the resource.
404 - Not Found – The resource is not found.
500 - Internal server error – This is a very generic server-side error that is thrown when the server goes down. This shouldn’t be returned by the programmer explicitly.
502 - Bad Gateway – Server did not receive a valid response from the upstream server.
503 - Service Unavailable – Some unexpected things happened on the server such as system failure, overload, etc.
While retrieving huge resource data, it is advisable to include filtering and pagination of the resources. This is because returning huge data all at once can slow down the system and reduce the application performance. Hence, filter some items reduces the data to some extent. Pagination of data is done to ensure only some results are sent at a time. Doing this can increase the server performance and reduce the burden of the server resources.
Since REST supports the feature of caching, we can use this feature to cache the data in order to improve the application performance. Caching is done to avoid querying the database for a request repeated time. Caching makes data retrieval fast. However, care must be taken to ensure that the cache has updated data and not outdated ones. Frequent cache update measures need to be incorporated. There are many cache providers like Redis that can assist in caching.
API Versioning: Versioning needs to be done in case we are planning to make any changes with the existing endpoints. We do not want to break communication between our application and the apps that consume our application while we are working on the API release. The transition has to be seamless. Semantic versioning can be followed. For example, 3.0.1 represents 3rd major version with the first patch. Usually, in the API endpoints, we define
/v1
,/v2
, etc at the beginning of the API path.
Last updated