01. All we need to know about Restful API

It will take about 3 minutes to finish reading this article.

Restful API is also one of the necessary knowledge points on the mobile terminal, but only need to understand is enough.

1. What is Restful API?

Restful (Representational State Transfer presentation layer state transition) is currently the most popular interface design specifications. Restful is a design style (a design style rather than a standard) for creating reliable, scalable and easy-to-maintain Web services. It follows the REST architectural style and is resource-centric, communicating via the HTTP protocol.

The Restful API is based on a request and response model between the client and the server. Client requests resources from the server by request methods (GET, POST, PUT, DELETE, etc.) The server responds according to the request method and the requested resource path, and returns the corresponding resource or status code. The request and response data format of a Restful API is usually JSON or XML.

2. Features of Restful API

It has several features:

Based on HTTP protocol:
RESTful API uses HTTP protocol as a communication protocol, the client sends a request to the server via HTTP protocol and the server sends a response to the client via HTTP protocol.

Statelessness:
RESTful APIs are stateless, and each request contains enough information so that the server does not need to save any state information about the client.

Resource Oriented:
RESTful API is a resource-oriented API that treats all operations as operations on resources. Each resource has a unique identifier (URI) and the client can request a representation of the resource via the URI.

Unified Interface:
The RESTful API uses a standard set of HTTP methods (GET, POST, PUT, DELETE, etc.) to manipulate resources, and the client performs operations on the resources through these methods.

Cacheability:
The RESTful API supports a caching mechanism where the client can cache responses to improve performance and the server can use caching to reduce the load.

Hierarchical systems:
The RESTful API supports a hierarchical system, which allows the server to distribute the load across multiple hierarchies and allows clients to access resources by accessing different hierarchies.

Common status codes for Restful API:

1
2
3
4
5
6
7
8
9
10
200 OK: indicates that the request was successful.
201 Created: indicates that the resource was successfully created.
204 No Content: The request was executed successfully, but no content was returned.
400 Bad Request: Indicates an error in the request, such as an incorrectly formatted or missing request parameter.
401 Unauthorized: indicates unauthorized access and requires valid credentials to access the resource.
403 Forbidden: indicates that access has been authorized, but access to the resource is not allowed.
404 Not Found: indicates that the requested resource does not exist.
405 Method Not Allowed: indicates that the requested HTTP method does not support the resource, such as using POST to request a read-only resource.
409 Conflict: indicates a request conflict, such as a version conflict when updating a resource.
500 Internal Server Error: Indicates an internal server error, such as an inability to connect to the database or an exception when processing a request.

3. Swift call Restful API sample code

The following is sample code for a Restful API style request:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Foundation

let url = URL(string: "https://example.com/api/users/1")!

var request = URLRequest(url: url)
request.httpMethod = "GET"

let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, let response = response as? HTTPURLResponse, error == nil else {
print("Error: \(error?.localizedDescription ?? "Unknown error")")
return
}

if (200..<300).contains(response.statusCode) {
if let jsonObject = try? JSONSerialization.jsonObject(with: data) {
print(jsonObject)
}
} else {
print("Error: \(response.statusCode)")
}
}

task.resume()

The above code is an example of a GET request, requesting information about a user resource via a URL and printing the response data.

The code uses Swift’s URLSession for the network request, where the dataTask method creates and executes an HTTP/HTTPS request, and calls a callback function to process the response data when the request is complete.

4. Pros and Cons of Restful API

4.1 Advantages of the Restful API include:
Simple to use:
The Restful API follows the HTTP protocol and is easy to understand and implement.

Extensible:
The resource-centric design of the Restful API makes it easy for the server side to add or remove resources, while the client side simply gets the resources it needs via a URL.

Cacheable:
Restful API supports caching, which can improve performance and reduce network transfers.

Cross-platform compatible:
The Restful API supports a variety of data formats, such as JSON, XML, etc., and can interact with different platforms and languages.

4.2 Disadvantages of the Restful API include:
Security:
Restful APIs are usually based on the HTTP protocol, which can be a security risk during transmission.

Performance issues:
Since the Restful API is based on the HTTP protocol, a connection needs to be established for each request, and there may be a performance bottleneck for a large number of concurrent requests or a large amount of data transfer.

5. Other ways

However, it is important to note that Restful APIs are not the only way to communicate and exchange data.Other common ways are RPC, WebSocket, etc.

5.1 RPC
Remote procedure calls, a standard that shields the underlying communication details and can be called directly.
Simply, RPC is to call a function or method (collectively referred to as a service) on another machine (server) from one machine (client) by passing parameters and get the returned result. RPC is used to call remote functions (or methods) just like calling local functions (or methods).

There is such a principle: internal service: first use RPC, RPC is suitable for internal, efficient and fast communication. The disadvantage is that it is best to use Java systems on both sides. External service: RESTful is the first to be used. REST is suitable for external use, easy to use, and cross-language. The disadvantage is that the operation is limited (CRUD), and it is not efficient enough. Therefore, RPC tends to be applied to scenarios with high performance and reliability requirements such as microservice architecture, distributed systems, database access, and high-performance computing.

5.2 WebSocket
WebSocket is a full-duplex communication protocol over a single TCP connection that allows a persistent connection between a client and a server for real-time data transfer.

WebSocket can be realized through a simple API, supporting cross-platform and cross-browser use. Therefore, WebSocket is more suitable for some scenarios such as instant messaging (online chatting), real-time data pushing (stock data), remote monitoring and controlling real-time collaboration.

Reference

[1] https://zhuanlan.zhihu.com/p/334809573
[2] https://blog.csdn.net/The_Time_Runner/article/details/86518448
[3] https://www.cnblogs.com/zhongyuanzhao000/p/11700815.html