Representational State Transfer (REST)

Representational State Transfer (REST)

The word REST stands for Representational State Transfer. REST API s have become the de facto standard for building web services, offering a simple, scalable, and stateless approach to data exchange. They leverage HTTP methods to perform various operations on resources, making them intuitive and easy to understand.

Key Principles

  • Uniform interface. Specific resources should be identified in the request. Usually, they are described by Uniform Resource Identifier (URI). Moreover, internal implementation is separate from resource representation. Further, representation should provide all information to modify or delete the resource or fetch additional data.
  • ?Client-server architecture. The client uses URIs to obtain resources. It doesn’t concern how the server process the request. On the other hand, the server process and returns the resources. It doesn’t impact a user interface in any way. Both client and server don’t need to know about other responsibilities. Thus, they can evolve independently. It allows using a single API in many different clients, e.g., web browsers, mobile apps.
  • Statelessness. A RESTful API should be stateless. In simple words, it means that it doesn’t store any information about the user’s session. Therefore, every single request should provide complete data to process it. Thus, it leads to greater availability of the API.
  • Cacheability. The server’s response should provide information on whether it should be cached and for what time or not. Caching the data that updates rarely improves performance and eliminates redundant client-server interactions.
  • Layered system. A REST API can consist of multiple layers, eg., business logic, presentation, data access. Moreover, layers shouldn’t directly impact others. Further, the client shouldn’t know if it’s connected directly to the end server or intermediary. Therefore, we can easily scale the system or provide additional layers such as gateways, proxies, load balancers.
  • Code on demand. This one is an optional constraint. The server can return a part of the code itself instead of the data in JSON format. The point is to provide specific operations on the data that the client can use directly. Although, it’s not a common practice.

With the REST architecture Resource is an important key word. Lets discuss about resource.

Resource

REST architecture treats every content as a resource. These resources can be Text Files, Html Pages, Images, Videos or Dynamic Business Data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ Global IDs. REST uses various representations to represent a resource where Text, JSON, XML. The most popular representations of resources are XML and JSON.

Representation of Resources

A resource in REST is a similar Object in Object Oriented Programming or is like an Entity in a Database. Once a resource is identified then its representation is to be decided using a standard format so that the server can send the resource in the above said format and client can understand the same format.

For example a user is a resource which is represented using the following XML format ?

<user> 
   <id>1</id> 
   <name>Mahesh</name>
   <profession>Teacher</profession> 
</user>         

The same resource can be represented in JSON format as follows ?

{ 
   "id":1, 
   "name":"Mahesh", 
   "profession":"Teacher" 
}        

HTTP Methods

Here's a breakdown of the most commonly used HTTP methods:

GET

  • Purpose: Retrieves a resource from the server.
  • Usage: Used to fetch data, such as a list of users, a specific product, or a page of content.
  • Example: GET /users to fetch a list of users.

POST

  • Purpose: Creates a new resource on the server.
  • Usage: Used to submit data to the server, such as creating a new user account, posting a comment, or uploading a file.
  • Example: POST /users to create a new user.

PUT

  • Purpose: Updates an existing resource on the server.
  • Usage: Used to modify the properties of an existing resource.
  • Example: PUT /users/123 to update the details of user with ID 123.

DELETE

  • Purpose: Removes a resource from the server.
  • Usage: Used to delete an existing resource.
  • Example: DELETE /users/123 to delete the user with ID 123.

PATCH

  • Purpose: Partially updates an existing resource.
  • Usage: Used to modify specific properties of a resource without replacing the entire object.
  • Example: PATCH /users/123 to update only the email address of user with ID 123.

HEAD

  • Purpose: Retrieves the HTTP headers of a resource without the body.
  • Usage: Used to check if a resource exists, get its size, or determine its last modified time.

OPTIONS

  • Purpose: Returns the allowed HTTP methods for a given resource.
  • Usage: Used to discover the capabilities of a server or resource.

TRACE

  • Purpose: Echoes back the request message to the client.
  • Usage: Primarily used for debugging and testing.

CONNECT

  • Purpose: Switches to a different protocol, typically used for tunneling protocols like HTTPS over HTTP.

Choosing the Right Method:

  • GET: For retrieving data.
  • POST: For creating new resources.
  • PUT: For updating entire resources.
  • PATCH: For partially updating resources.
  • DELETE: For deleting resources.

Important part of the REST is to maintain the responses. Response should be meaningful and informational. For this we maintain HTTP codes to indicate the status of the request we made.

HTTP response codes

HTTP status codes are numerical codes returned by a web server to indicate the status of a request. They provide essential information about the success or failure of a request, allowing clients to take appropriate actions.

Here are some of the most common HTTP status codes:

1xx Informational

  • 100 Continue: The server is expecting more data.
  • 101 Switching Protocols: The server is switching protocols.

2xx Success

  • 200 OK: The request was successful.
  • 201 Created: A new resource was created.
  • 202 Accepted: The request has been accepted for processing.
  • 204 No Content: The server successfully processed the request but has no content to return.

3xx Redirection

  • 301 Moved Permanently: The resource has been permanently moved to a new location.
  • 302 Found: The resource has been temporarily moved to a new location.
  • 304 Not Modified: The resource has not been modified since the last request.

4xx Client Error

  • 400 Bad Request: The server could not understand the request.
  • 401 Unauthorized: The client is not authorized to access the resource.
  • 403 Forbidden: The client is forbidden from accessing the resource.
  • 404 Not Found: The requested resource could not be found. ?
  • 405 Method Not Allowed: The specified HTTP method is not allowed for this resource.
  • 409 Conflict: The request could not be completed due to a conflict.

5xx Server Error

  • 500 Internal Server Error: The server encountered an unexpected condition.
  • 503 Service Unavailable: The server is temporarily unavailable.

Example: If you send a GET request to a URL that doesn't exist, the server might return a 404 Not Found status code. This indicates that the requested resource could not be found.

Understanding Status Codes:

  • 1xx: Informational codes are used to provide feedback during the request process.
  • 2xx: Success codes indicate that the request was successful.
  • 3xx: Redirection codes tell the client to redirect to a different URL.
  • 4xx: Client error codes indicate that the client caused the error.
  • 5xx: Server error codes indicate that the server encountered a problem.

Now we discussed basic things regarding the REST. When comes to REST there are several ruleset to be followed. Lets see on this.

Key Rules for Designing REST APIs

While REST architecture provides a set of guiding principles, there are specific rules and best practices to follow when designing REST APIs:

Resource-Based Approach

  • Identify Resources: Determine the fundamental entities or objects that your API will manage.
  • Use Nouns for URLs: Represent resources with nouns in the URL path (e.g., /users, /products).
  • Use HTTP Verbs: Employ appropriate HTTP methods to perform actions on resources: GET: Retrieve a resource. POST: Create a new resource. PUT: Update an existing resource. DELETE: Remove a resource.

Self-Describing Messages

  • Include Metadata: Provide information about the API, resources, and responses in the HTTP headers or response body.
  • Use JSON or XML: Choose a suitable data format for representing resources and responses.

Uniform Interface

  • Adhere to HTTP Standards: Use standard HTTP methods and status codes consistently.
  • Use Consistent Representations: Ensure that responses for the same resource type have a consistent format.

Statelessness

  • Avoid Session State: Each request is independent and doesn't rely on previous requests.
  • Use Query Parameters: Pass necessary information as query parameters in the URL.

Cacheability

  • Set Cache Headers: Use HTTP headers like Cache-Control and Expires to indicate if responses can be cached.
  • Leverage Caching: Implement caching mechanisms to improve performance and reduce server load.

Layered System

  • Separate Concerns: Organize the API into layers (e.g., presentation, business logic, data access) for better maintainability and scalability.

Hypermedia Controls

  • Provide Links: Include links in responses to related resources, allowing clients to discover and navigate the API.
  • Use HATEOAS: Follow the Hypermedia as the Engine of Application State (HATEOAS) principle to make APIs more flexible and client-driven.

Security

  • Implement Authentication: Ensure that only authorized users can access the API.
  • Protect Data: Use encryption and other security measures to protect sensitive information.
  • Handle Errors Gracefully: Return informative error messages with appropriate HTTP status codes.

Additional Considerations

  • Versioning: Consider versioning your API to manage changes and support older clients.
  • Documentation: Provide clear and comprehensive documentation to help developers understand and use the API.
  • Testing: Thoroughly test your API to ensure it functions as expected and handles various scenarios.


要查看或添加评论,请登录

Supun Geethanjana的更多文章

社区洞察

其他会员也浏览了