Understanding REST

Understanding REST

Representational State Transfer (REST) is a widely adopted architectural style for designing networked applications, particularly web services and APIs. RESTful systems emphasize simplicity, scalability, and flexibility, making them popular choices for building distributed systems. In this article, we'll go into the core principles and concepts of REST, exploring each corner to gain a comprehensive understanding.

What is the REST?

REST is not a protocol but rather an architectural style that defines a set of constraints and guidelines for designing networked applications. At its core, REST encourages a stateless client-server communication model, where clients interact with server resources through well-defined interfaces.

REST Constraints

REST is guided by a set of constraints that define its architectural style. Here are the key constraints of REST:

1- Client-Server: The system is divided into client and server components that are independent of each other. This separation of concerns allows them to evolve independently and enables the client and server to be developed and deployed separately.

2- Statelessness: The server does not maintain any client state between requests. Each request from the client to the server must contain all the information necessary to understand and fulfill the request. This constraint enhances scalability by allowing servers to handle requests without the need to manage session state.

3- Cacheability: Responses from the server can be explicitly marked as cacheable or non-cacheable. Cacheable responses can be reused by clients or intermediaries to improve performance and reduce latency. Cacheability enhances scalability and reduces network traffic.

4- Uniform Interface: The uniform interface constraint defines the standard set of operations that can be performed on resources. This constraint includes four sub-constraints:

  • Identification of Resources: Each resource is uniquely identified by a URI.
  • Manipulation of Resources through Representations: Clients interact with resources through representations, such as JSON or XML.
  • Self-Descriptive Messages: Each message includes metadata that describes how to process the message.
  • Hypermedia as the Engine of Application State (HATEOAS): Clients navigate the application state by following hypermedia links provided by the server.

5- Layered System: The architecture is organized as a layered system, where each component (e.g., client, server, proxy) operates independently and interacts only with adjacent layers. Layers can be added, removed, or modified without affecting other components, enhancing scalability and flexibility.

6- Code-On-Demand (Optional): This constraint is optional and states that servers can extend the functionality of clients by transferring executable code, such as JavaScript, which the client can execute. While not commonly used, this constraint adds flexibility to the system by allowing clients to dynamically download and execute code.

Benefits of REST

  • Simplicity: RESTful systems are simple to understand, design, and implement, fostering rapid development and adoption.
  • Scalability: The stateless nature and layered architecture of REST enable horizontal scalability, allowing systems to handle increased load by adding more resources.
  • Flexibility: RESTful interfaces provide flexibility in representing resources, supporting diverse data formats and content types.
  • Interoperability: RESTful APIs are platform-independent and language-agnostic, facilitating interoperability between heterogeneous systems.

Challenges and Considerations

  • Over-fetching and Under-fetching: Inefficient API designs may lead to over-fetching (retrieving more data than needed) or under-fetching (not retrieving enough data), impacting performance and usability.
  • API Versioning: Managing API versions and backward compatibility is essential to ensure smooth transitions and minimize disruptions for clients.
  • Security: Protecting RESTful APIs against common security threats, such as cross-site scripting (XSS) and SQL injection, requires robust authentication, authorization, and encryption mechanisms.

What are HTTP verbs?

In RESTful systems, HTTP verbs, also known as HTTP methods, are used to perform operations on resources. RESTful APIs leverage the HTTP verbs as the primary means of interacting with resources. Each HTTP verb corresponds to a specific action or operation on resources, aligning closely with the principles of REST. The most commonly used HTTP verbs in RESTful APIs are:

GET: The GET method is used to retrieve resource representations from the server. It is safe and idempotent, meaning it should not modify the state of the server and can be called multiple times without changing the server's state (I’ll talk about Idempotency and safety soon). ?

In the safe path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).

POST: The POST method is used to create new resources on the server. It submits data to be processed by the server, typically resulting in the creation of a new resource. POST requests may have side effects on the server and are not idempotent.

On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status.?

PUT: The PUT method is used to update or replace existing resources on the server. It sends a complete representation of the resource to be updated, replacing the existing resource if it exists, or creating a new resource if it does not.

On successful update, return 200 (or 204 if not returning any content in the body) from a PUT. If using PUT for create, return HTTP status 201 on successful creation. PUT is not a safe operation but it’s idempotent.?

DELETE: The DELETE method is used to remove resources from the server. It deletes the specified resource, if it exists, from the server.

On successful deletion, return HTTP status 200 (OK) along with a response body.?

PATCH: The PATCH method is used to partially update resources on the server. It sends a set of changes to be applied to the resource, rather than the complete representation of the resource. PATCH requests in general are not idempotent, although in some situation and use cases it can be idempotent.

HEAD: The HEAD method is similar to the GET method but only retrieves the headers of the resource, without the body. It is often used to check resource metadata, such as headers or status codes, without transferring the entire resource.

Sample:

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270        

OPTIONS: The OPTIONS method is used to retrieve information about the communication options available for a resource or server. It allows clients to determine the supported methods, headers, and other capabilities of the server.

Sample:

HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0        

TRACE: The TRACE method is used to perform a loop-back test along the path to the target resource. It echoes back the received request to the client, allowing clients to see what changes or additions have been made by intermediate servers.

CONNECT: The CONNECT method is used to establish a tunnel connection to the server for use with SSL/TLS protocols, typically for HTTPS connections through proxies.

What is Idempotency and safety?

An idempotent HTTP method is a HTTP method that can be called many times without different outcomes. It would not matter if the method is called only once, or ten times over. The result should be the same. Again, this only applies to the result, not the resource itself.?

Safe methods are those that do not change any resources internally. These methods can be cached and can be retrieved without any effects on the resource.

Idempotency and Safety of HTTP Methods

REST Request/Response

A request is sent from client to server in the form of a web URL as HTTP GET or POST or PUT or DELETE request. After that, a response comes back from the server in the form of a resource which can be anything like HTML, XML, Image, or JSON. But now JSON is the most popular format being used in Web Services.?

HTTP Request format

In REST, any HTTP Request has 5 main components, they are:

  • Method/Verb ? 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.

HTTP Request Format

HTTP Response format

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.

HTTP Response Format

What are HTTP Status codes?

These are the standard codes that refer to the predefined status of the task at the server. Here are the available category of status codes:

  • 1xx - represents informational responses
  • 2xx - represents successful responses
  • 3xx - represents redirects
  • 4xx - represents client errors
  • 5xx - represents server errors

Most commonly used status codes in each category are:

  • 100 - Continue - client should continue the request or ignore the response if the request is already finished.
  • 200 - success/OK
  • 201 - CREATED - used in POST or PUT methods.
  • 202 - Accepted - The request has been received but not yet processed
  • 301 - Redirected Permanently
  • 302 - Redirected Temporarily
  • 303 - See Other - Redirect to new URI
  • 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.

Conclusion

REST is more than just a set of guidelines; it's a philosophy that promotes simplicity, scalability, and interoperability in distributed systems design. By embracing the key principles and concepts of REST, developers can build robust, flexible, and scalable web services and APIs that meet the evolving needs of modern applications.?

In the feature I’ll dedicated an article to writing REST API in C#.


#rest #api #web #http


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

社区洞察

其他会员也浏览了