REST API: Introduction
Sebastian Pawlaczyk
Designing an architecture and selecting appropriate technologies for a new software is one of the most significant decisions. It requires extensive experience gathered from previous projects, willing to ask relevant business questions, and also a thorough review of each possible solution. Our mission is to guide you through the ins and outs of technology so that you have no doubts about why you chose this solution.
REST API
Choosing a suitable communication protocol is critical for the performance, scalability, maintainability, and security of your application. This article focuses on REST APIs, a popular choice among many developers. My aim isn’t to argue that REST is the best protocol for every situation. Instead, I want to guide you through the crucial stages of designing and implementing a REST API, helping you save time and effort during both the planning and execution phases. I will break down the guide into specific subsections, covering each aspect of REST API development in detail. To make the examples clear and practical, we will use GoLang, a language known for its efficiency and simplicity in handling web services. Whether you are new to REST APIs or looking to refine your existing knowledge, this guide aims to provide valuable insights and practical tips.
Rules
REST API architecture uses HTTP protocol and it has to fulfils several important rules:
1. Uniform interface
This principle dictates that the interface between clients and servers should be standardized, simplifying the architecture and improving decoupling. Key aspects include the use of Uniform Resource Identifiers (URIs) to uniquely identify resources and HTTP methods (such as GET, POST, PUT, DELETE) to define actions on those resources. It also involves adhering to a consistent resource-based approach, where resources are manipulated through representations. These are sent in request and response payloads, typically in formats like JSON or XML.
2. Stateless Communications
Every client-server interaction is self-contained. Each request from the client to the server containing all the
information needed to understand and complete the request. This means the server does not retain any session state about
the client, which enhances reliability and scalability by simplifying server design and allowing any available server to
service requests.
3. Client — Server separation
This rule enforces a clear separation of concerns: the client is responsible for the user interface and user-related
functionality, while the server is responsible for data access, workload management, and performance. This separation
allows clients and servers to evolve independently, provided that the interface between them remains unchanged.
4. Layered architecture
The client typically cannot discern whether it is connected directly to the end server or to an intermediary along the
way. Intermediary servers can enhance system scalability by facilitating load balancing and providing shared caches.
They can also implement security policies.
5. Cacheable
To enhance network efficiency, responses from the server should be implicitly or explicitly labeled as cacheable or
non-cacheable. If a response is deemed cacheable, the client’s cache is authorized to reuse that response data for
later, equivalent requests. Proper management of caching can partially or completely eliminate some client-server
interactions, further improving scalability and performance.
6. Code on demand — optional
This is an optional constraint that permits servers to extend or customize the functionality of a client. It is
feasible thanks to transferring executable code (e.g., Java applets, JavaScript), which the
client can execute. It’s a method to support client-side scripting or plug-ins, which not only adds flexibility but also
increases complexity.
Request & Response
In this section, I will briefly explain the construction of requests and responses and highlight the differences between
them.
Request:
POST /asset HTTP/1.1
Host: example.com
Content-Type: application/json
Authorization: Bearer token
Accept: application/json
Content-Length: 148
{
"name": "New Asset",
"type": "Equipment"
}
Response:
HTTP/1.1 200 OK
Date: Wed, 28 Feb 2024 12:00:00 GMT
Server: Apache/2.4.1 (Unix)
Content-Type: application/json
Content-Length: 123
{
"id": "12345",
"name": "New Asset",
"type": "Equipment",
"status": "Created",
"createdAt": "2024-02-28T12:00:00Z"
}
Methods
The HTTP method specifies the action to be performed on the resource.
Endpoint
The endpoint (or URL) specifies the path to the resource on the server. It typically includes the protocol (HTTP/HTTPS),
the host (domain or IP), and the path to the resource. Maintaining coherence in defining endpoints is crucial.
Generally, we aim to align them with the resource name, which could correspond to a database object or another
abstraction. Let’s examine an example of a simple CRUD API.
- POST api/users - create a new user.
- GET api/users - retrieve a list of users.
- DELETE api/users/{userID} - retrieve a specific user by ID.
- PUT api/users/{userID} - update a specific user by ID, replacing all their information.
- PATCH api/users{userID} - partially update a specific user by ID.
Header
Headers offer additional information about the request or about the content being sent to the server.
Examples:
- Host: Specifies the domain name of the server — example.com
- Content-Type: Indicates the media type of the resource being sent to the server, commonly application/json for
JSON payloads - Authorization: Contains credentials for authenticating the client to the server, often used for security purposes
- Content-Length: The length of the request body in octets (8-bit bytes)
Body
The body of the request contains the data to be sent to the server. In a POST request, this is typically where the new
resource data is included, with JSON being the most popular format.
{
"name": "John",
"age": 21,
"nationality": "PL"
}
Parameters
Parameters play a pivotal role in REST API requests, enabling the filtering of results, specifying data to be returned,
and providing additional operational context. Understanding the different types of parameters and their usage can
significantly enhance the efficiency and clarity of API interactions. Below are the common types of parameters used in
REST API requests:
Query Parameters
- Description: Query parameters are appended to the end of the URL with a ‘?’ and can be used to modify the response or request specific data. They are ideal for sorting, filtering, and pagination
- Example: `GET /api/users?status=active&sort=lastName,asc` requests a list of active users sorted by their last name in ascending order
Path Parameters
- Description: Path parameters are part of the URL path and typically used to identify a specific resource or resources
- Example: `GET /api/users/{userId}` retrieves the details of the user with the specified userId
Next Up: Designing REST API
In the following section, I will guide you through how to design a REST API with a hands-on demo.