DEV Community

Cover image for What is REST?
oleg-melnic
oleg-melnic

Posted on

What is REST?

REpresentational State Transfer

REST is the acronym for REpresentational State Transfer. It is an architectural style for providing better and easier communication between computer systems on the web. REST-compliant systems, also called RESTful systems, are stateless and act as an intermediary between client and server. We'll take a look at what these terms mean and why they are useful features for online services.

Client-Server architecture

In the REST architectural style, the client implementation and the server implementation can be performed independently of each other. This means that the client-side code can be changed at any time without affecting the server's operation, and the server-side code can be changed without affecting the client’s operation.
Messages can be stored modularly and separately, as long as each side knows what message format to send to the other side. By separating user interface tasks from the data storage tasks, we increase the flexibility of the interface between platforms and improve scalability by simplifying server components. Moreover, separation allows each component to evolve independently.
By using the REST interface, different clients end up at the same REST endpoints, perform the same actions, and receive the same responses.

Statelessness

Systems that are based on REST architecture are stateless, which means the server doesn't need to know about the client's state and vice versa. Thus, both the server and the client can understand any message received without seeing the previous messages. This statelessness is ensured by using resources rather than commands. Resources are the Web nouns - they describe any objects, documents or things that may be needed to store or send to other services. Because REST systems interact through standard resource operations, they are independent of interface implementation.
These constraints help Restful applications achieve reliability, fast performance, and extensibility as components that can be managed, updated, and reused without affecting the entire system, even while the system is running.
Now, we’ll explore how the communication between the client and server actually happens when we are implementing a RESTful interface.

Communication between Client and Server

In REST architecture, clients send requests to find or modify resources, and servers send responses to those requests. Let's take a look at the standard ways of sending requests and responses.

Making Requests

REST requires the client to make a request to the server in order to get or change data on the server. The request usually consists of:
• an HTTP method that determines the type of operation
• a header, which allows the client to pass along information about the request
• a path to a resource
• an optional message body containing data

HTTP methods

There are 4 basic HTTP methods we use in requests to interact with resources in a RESTful system:
• GET — retrieve a specific resource (by id) or a collection of resources
• POST — create a new resource
• PUT — update a specific resource (by id)
• DELETE — remove a specific resource by id

Headers and Accept parameters

In the header of the request, the client sends the type of content that it is able to receive from the server. This field is called Accept, and it ensures that the server does not send data that cannot be understood or processed by the client. Content-type parameters are MIME types (or Multipurpose Internet Mail Extensions, which you can read more about in the MDN Web Docs).
MIME Types, used to specify the content types in the Accept field, consist of a type and a subtype. They are separated by a slash (/).
For example, a text file containing HTML would be specified with the type text/html. If this text file contained CSS instead, it would be specified as text/css. The general text file will be referred to as text/plain. However, this default value, text/plain, is not universal. If a client is expecting text/css and receives text/plain, it will not be able to recognize the content.
Other types and commonly used subtypes:
image — image/pngimage/jpegimage/gif
audio — audio/wavaudio/mpeg
video — video/mp4video/ogg
application — application/jsonapplication/pdfapplication/xmlapplication/octet-stream
For example, a client accessing a resource with id 23 in an articles resource on a server might send a GET request like this:

GET /articles/23
Accept: text/html, application/xhtml
Enter fullscreen mode Exit fullscreen mode

The Accept header field, in this case, is saying that the client will accept the content in text/html or application/xhtml.

Paths

Requests must contain a path to a resource that the operation should be performed on. In RESTful APIs, paths should be designed to help the client know what is going on.
Usually, the first part of the path should be the plural form of the resource. This allows easy reading and understanding of nested paths.
A path like blabla.ccc/customers/223/orders/12 is clear in what it points to, even if you’ve never seen this specific path before because it is hierarchical and descriptive. We can see that we are accessing the order with id 12 for the customer with id 223.
Paths should contain the information necessary to locate a resource with the degree of specificity needed. When referring to a list or collection of resources, it is not always necessary to add an id. For example, a POST request to the blabla.ccc/customers path would not need an extra identifier, as the server will generate an id for the new object.
If we are trying to access a single resource, we would need to add an id to the path. For example: GET blabla.ccc/customers/:id — retrieves the item in the customers resource with the id specified. DELETE blabla.ccc/customers/:id — deletes the item in the customers resource with the id specified.

Sending Responses

Content Types

In cases where the server is sending a data payload to the client, the server must include a content-type in the header of the response. This content-type header field alerts the client to the type of data it is sending in the response body. These content types are MIME Types, just as they are in the accept field of the request header. The content-type that the server sends back in the response should be one of the options that the client specified in the accept field of the request.
For example, when a client is accessing a resource with id 23 in an articles resource with this GET Request:

GET /articles/23 HTTP/1.1
Accept: text/html, application/xhtml
Enter fullscreen mode Exit fullscreen mode

The server might send back the content with the response header:

HTTP/1.1 200 (OK)
Content-Type: text/html
Enter fullscreen mode Exit fullscreen mode

This would signify that the content requested is being returned in the response body with a content-type of text/html, which the client said it would be able to accept.

Response Codes

Responses from the server contain status codes to alert the client to information about the success of the operation. As a developer, you do not need to know every status code (there are many of them), but you should know the most common ones and how they are used:

Status code Meaning
200 (OK) This is the standard response for successful HTTP requests.
201 (CREATED) This is the standard response for an HTTP request that resulted in an item being successfully created.
204 (NO CONTENT) This is the standard response for successful HTTP requests, where nothing is being returned in the response body.
400 (BAD REQUEST) The request cannot be processed because of bad request syntax, excessive size, or another client error.
403 (FORBIDDEN) The client does not have permission to access this resource.
404 (NOT FOUND) The resource could not be found at this time. It is possible it was deleted, or does not exist yet.
500 (INTERNAL SERVER ERROR) The generic answer for an unexpected failure if there is no more specific information available.

For each HTTP verb, there are expected status codes a server should return upon success:
• GET — return 200 (OK)
• POST — return 201 (CREATED)
• PUT — return 200 (OK)
• DELETE — return 204 (NO CONTENT) If the operation fails, return the most specific status code possible corresponding to the problem that was encountered.

Examples of Requests and Responses

Let’s suppose we have an application that allows you to view, create, edit, and delete customers and orders for a small clothing store hosted at blabla.ccc. We could create an HTTP API that allows a client to perform the following functions:
If we wanted to view all customers, the request would look like this:

GET http://fashionboutique.com/customers
Accept: application/json
Enter fullscreen mode Exit fullscreen mode

A possible response header would look like:

Status Code: 200 (OK)
Content-type: application/json
Enter fullscreen mode Exit fullscreen mode

followed by the customers data requested in application/json format.
Create a new customer by posting the data:

POST http://blabla.ccc/customers
Body:
{
  “customer”: {
    “name” = “Vasea Pupkin”,
    “email” = “vasea.pepkin@exemple.ccc”
  }
}
Enter fullscreen mode Exit fullscreen mode

The server then generates an id for that object and returns it back to the client, with a header like:

201 (CREATED)
Content-type: application/json
Enter fullscreen mode Exit fullscreen mode

To view a single customer we GET it by specifying that customer’s id:

GET http://fashionboutique.com/customers/123
Accept: application/json
Enter fullscreen mode Exit fullscreen mode

A possible response header would look like:

Status Code: 200 (OK)
Content-type: application/json
Enter fullscreen mode Exit fullscreen mode

followed by the data for the customer resource with id 23 in application/json format.
We can update that customer by PUT ting the new data:

PUT http://blabla.ccc/customers/123
Body:
{
  “customer”: {
    “name” = “Vasea Pupkin”,
    “email” = “vaseapupkin1@exemple.ccc”
  }
}
Enter fullscreen mode Exit fullscreen mode

A possible response header would have Status Code: 200 (OK), to notify the client that the item with id 123 has been modified.
We can also DELETE that customer by specifying its id:

DELETE http://blabla.ccc/customers/123
Enter fullscreen mode Exit fullscreen mode

The response would have a header containing Status Code: 204 (NO CONTENT), notifying the client that the item with id 123 has been deleted, and nothing in the body.

Practice with REST

Let’s imagine we are building a photo-collection site. We want to make an API to keep track of users, venues, and photos of those venues. This site has an index.html and a style.css. Each user has a username and a password. Each photo has a venue and an owner (i.e. the user who took the picture). Each venue has a name and street address. Can you design a REST system that would accommodate:
• storing users, photos, and venues
• accessing venues and accessing certain photos of a certain venue
Start by writing out:
• what kinds of requests we would want to make
• what responses the server should return
• what the content-type of each response should be

Possible Solution - Models

{
  “user”: {
    "id": <Integer>,
    “username”: <String>,
    “password”:  <String>
  }
}
Enter fullscreen mode Exit fullscreen mode
{
  “photo”: {
    "id": <Integer>,
    “venue_id”: <Integer>,
    “author_id”: <Integer>
  }
}
Enter fullscreen mode Exit fullscreen mode
{
  “venue”: {
    "id": <Integer>,
    “name”: <String>,
    “address”: <String>
  }
}
Enter fullscreen mode Exit fullscreen mode

Possible Solution - Requests/Responses

GET Requests

Request- GET /index.html Accept: text/html Response- 200 (OK) Content-type: text/html
Request- GET /style.css Accept: text/css Response- 200 (OK) Content-type: text/css
Request- GET /venues Accept:application/json Response- 200 (OK) Content-type: application/json
Request- GET /venues/:id Accept: application/json Response- 200 (OK) Content-type: application/json
Request- GET /venues/:id/photos/:id Accept: application/json Response- 200 (OK) Content-type: image/png

POST Requests

Request- POST /users Response- 201 (CREATED) Content-type: application/json
Request- POST /venues Response- 201 (CREATED) Content-type: application/json
Request- POST /venues/:id/photos Response- 201 (CREATED) Content-type: application/json

PUT Requests

Request- PUT /users/:id Response- 200 (OK)
Request- PUT /venues/:id Response- 200 (OK)
Request- PUT /venues/:id/photos/:id Response- 200 (OK)

DELETE Requests

Request- DELETE /venues/:id Response- 204 (NO CONTENT)
Request- DELETE /venues/:id/photos/:id Response- 204 (NO CONTENT)

Top comments (0)