What is REST?

Jun 6, 2021

As we explored in What is CRUD? guide, applications apply operations during the life cycle of the objects. REST architecture suggests some design decisions for these operations to provide a common ground between application and API developers. Understanding REST API principles has a remarkable effect on developer productivity.

Even though the REST acronym, REpresentational State Transfer, sounds a little mysterious, there are only a few REST principles used in practice.

We can divide RESTful API flow into three steps:

  1. Applications send requests after user interactions
  2. REST APIs validate incoming requests by applying business specific rules and return responses
  3. Applications update their internal state with respect to the responses

In this guide, we will examine REST concepts and common REST API use cases in real-world scenarios.

Resources

Resources are abstractions provided by RESTful APIs (for example, tasks in Todo API and recipes in Recipe API). Applications can interact with these resources without considering underlying implementation details. Resources are generally named as plural nouns.

Resource identifiers allow retrieving particular resources in a system and they are in {resource-name}/{unique-id} format (for example, /tasks/e169f251-179d-4425-96de-a73d25dbd928).

HTTP Methods

Although REST architecture doesn't enforce any protocols, most RESTful APIs adopt HTTP as the underlying protocol. Moreover, REST APIs combine resource identifiers and HTTP methods to decide which operation to perform on the resources.

Common HTTP methods and related operations:

HTTP MethodDescription
POSTCreates a resource
GETLists a set of resources or retrieves a resource
PUT and PATCHUpdates a resource
DELETEDeletes a resource

HTTP Status Codes

After sending HTTP requests to REST APIs, applications usually check HTTP status codes to display feedbacks to users (for example, notifications and form validation errors).

Frequently used HTTP status codes:

HTTP Status CodeDescription
200 OKIndicates resource or resources returned successfully
201 CreatedIndicates resource created successfully
204 No ContentIndicates resource deleted successfully
400 Bad RequestIndicates request body is invalid
401 UnauthorizedIndicates authentication is not fulfilled
404 Not FoundIndicates requested resource is not found
500 Internal Server ErrorIndicates a server error

Create a Task

Assume we are building a Todo application and we designed a form to create todo items.

In order to consume the REST API, we should check which endpoints are provided from its API documentation. After deciding which endpoint to use (for example, /tasks), we should send a valid request to it.

According to endpoint documentation, task-create endpoint accepts title, details, listId, due, isCompleted and createdAt fields in JSON format.

Endpoint schema also describes expected data types (for example, string and boolean), constraints (for example, minLength and maxLength), data formats (for example, uuid and date-time) and default values (for example, null and false).

Since REST APIs are platform and programming language independent, we can build mobile and web applications using any language like JavaScript, Dart, Swift and C#.

Let's inspect sample code written in JavaScript.

Task create endpoint

// Don't forget to replace `3a4efdb166e747d481dfd9887c638afcf5f10465`
// with your own key taken from `Account` page
const cfAccessKey = "3a4efdb166e747d481dfd9887c638afcf5f10465";
const contentType = "application/json";
const endpoint = "https://todo.crudful.com/tasks";
// Prepare request body
const taskData = {
title: "Learn Programming",
};
// Send the request
const response = await fetch(endpoint, {
method: "POST",
headers: {
cfAccessKey: cfAccessKey,
"Content-Type": contentType,
},
body: JSON.stringify(taskData), // convert request body to JSON format
});
// Get the response body
const body = await response.json();
// Check the response status code and update the application state
if (response.status === 201) {
// handle created
// for example, display task created notification
} else if (response.status === 400) {
// handle bad request
// for example, display form validation errors
} else {
// handle others
}

Retrieve a Task

Another common scenario is retrieving a specific resource from RESTful APIs (for example, task-detail and task-update screens).

As we can see from endpoint documentation, task-retrieve endpoint expects a parameter called id in uuid format.

id fields are usually set by REST APIs after a successful create operation and their values can be in integer (for example, 123), uuid (for example, b562b402-0b89-4514-9a82-7d24719898e7) and slug (for example, learn-programming) formats.

Let's inspect sample code written in JavaScript.

Task retrieve endpoint

// Don't forget to replace `3a4efdb166e747d481dfd9887c638afcf5f10465`
// with your own key taken from `Account` page
const cfAccessKey = "3a4efdb166e747d481dfd9887c638afcf5f10465";
const taskId = "b562b402-0b89-4514-9a82-7d24719898e7";
const endpoint = "https://todo.crudful.com/tasks/" + taskId;
// Send the request
const response = await fetch(endpoint, {
method: "GET",
headers: {
cfAccessKey: cfAccessKey,
},
});
// Get the response body
const body = await response.json();
// Check the response status code and update the application state
if (response.status === 200) {
// handle okay
// for example, display task detail screen
} else if (response.status === 400) {
// handle not found
// for example, display not found screen
} else {
// handle others
}

Summary

Applying REST conventions provides common practices for both API and application developers. As a result, development teams can spend more time on their ideas and products.

Please follow @crudfulcom and join Discord server for more!