This article discusses four major API architectural styles, compares their strengths and weaknesses, and highlights the API architectural styles that are most appropriate for each situation.
Two separate applications need mediators to communicate with each other. As a result, developers often need to build Bridges — application programming interfaces (apis) — to allow one system to access information or functionality from another.
To integrate disparate applications quickly and on a large scale, apis use protocols or specifications to define the semantics and information of those messages that travel over the network. These specifications form the architecture of the API.
In the past, many different API architectural styles have been released. Each architectural style has its own pattern for standardizing data exchange. This array of API architectural style options has led to a great deal of debate about which architectural style is best.
The editor
Switch to center
(Optional) Add image annotations in 140 characters or less
Today, many API users refer to REST as “REST in peace” and rejoice in GraphQL. Ten years ago, it was an entirely different story: REST was the winner in replacing SOAP. The problem with these ideas is that they start by endorsing a particular technology, rather than considering how its actual attributes and features match up with current needs.
The editor
Switch to center
(Optional) Add image annotations in 140 characters or less
1.RPC: Call a function of another system
Remote procedure call is a specification that allows functions to be executed remotely in different contexts. RPC extends the concept of a local procedure call and places it in the context of an HTTP API.
The original XML-RPC was problematic because it was difficult to ensure the data type of the XML payload. As a result, RPC apis later began to use a more specific JSON-RPC specification, which was considered a simpler alternative to SOAP. GRPC is the latest VERSION of RPC developed by Google in 2015. With pluggable support for load balancing, tracking, health checking, and authentication, gRPC is ideal for connecting to different microservices.
How RPC works
The client invokes a remote procedure, serializes the parameters and additional information into a message, and then sends the message to the server. Upon receiving the message, the server deserializes the contents of the message, performs the requested operation, and then sends the results back to the client. The client and server are respectively responsible for serializing and deserializing parameters.
The editor
Switch to center
(Optional) Add image annotations in 140 characters or less
The advantage of the RPC
Simple and direct interaction. RPC uses GET to GET information and POST to handle all other operations. The mechanism for interaction between the server and client comes down to calling the endpoint and getting the response.
Easy to add new functions. If the API has a new requirement, we can easily add another endpoint that implements that requirement: 1) write a new function and place it after a new endpoint; 2) Now, customers can access this endpoint and get the information that meets their needs.
High performance. Lightweight payloads do not strain the network and thus provide high performance, which is important for sharing servers and performing parallel computing on a network of workstations. RPC also optimizes the network layer, making it very efficient to send massive amounts of messages between different services every day.
The shortage of the RPC
Tightly coupled to the underlying system. The API’s level of abstraction contributes to its reusability. The more tightly the API is coupled to the underlying system, the less reusable it is to other systems. RPC’s tight coupling to the underlying system does not allow it to establish a layer of abstraction between system functions and external apis. This can easily cause security problems, as details about the implementation of the underlying system can easily leak into the API.
The tight coupling of RPC makes scalability requirements and loosely coupled teams difficult to achieve. As a result, clients either worry about any possible side effects of calling a particular endpoint, or they need to try to figure out which endpoint to call because they don’t know how the server names its functions.
Low discoverability. In RPC, there is no way to validate the API summary or send a request to begin to understand which function should be called based on the requirements.
The function explodes. Creating new functions is easy. Therefore, rather than re-editing existing functions, we tend to create new ones, resulting in a large number of unintelligible, overlapping functions.
RPC use cases
The RPC model began to be used in the eighties, but that doesn’t mean it’s obsolete. Large companies such as Google, Facebook (Apache Thrift), and Twitch (Twirp) are now using high-performance RPC versions internally to perform extremely high performance, low overhead messaging. Their vast microservices systems require that internal communications remain clear even with short messages.
Command API. RPC is the correct choice for sending commands to remote systems. For example, the Slack API is very command-centric: join a channel, leave a channel, send a message. So the designers of the Slack API modeled it in a rPC-like fashion, making it small, compact, and easy to use.
Customer-specific apis for internal microservices. Since we are building direct integration between a single provider and a single consumer, we don’t want to spend too much time transporting large amounts of metadata over the network as REST apis do. With their high message rates and message performance, gRPC and Twirp become reliable use cases for microservices. By using HTTP 2 at the bottom, gRPC can optimize the network layer, making it very efficient to transfer large amounts of information between different services on a daily basis. However, if you are not looking to improve network performance, you are looking to establish a stable API connection between microservices teams that publish highly independent microservices. REST does that.
SOAP: Make data available as a service
SOAP is a highly standardized network communication protocol in XML format. SOAP was released by Microsoft a year after XML-RPC was released and inherits many of xmL-RPC’s features. REST followed, and at first they were used together, but soon REST won the competition and became the more popular protocol.
How SOAP works
XML data formats are a drag on many data specifications. With a large number of message structures, the XML data format makes SOAP the most verbose API architectural style.
SOAP messages are made up of these parts:
-
An envelope label: Used to start and end each message
-
Contains the body of the request or response
-
A header: Used to indicate whether a message is acknowledged by some specification or additional requirement
-
Fault notification: Contains any errors that can only occur during request processing
The editor
Switch to center
(Optional) Add image annotations in 140 characters or less
The logic of the SOAP API is written in Web Services Description Language (WSDL). The API description language defines the endpoints and describes all the procedures that can be performed. This enables communication between different programming languages and ides to be established quickly.
SOAP supports both stateful and stateless messaging. In a stateful case, the server can be cumbersome to store the information received. But it makes sense for operations involving multiple parties and complex transactions.
The advantage of SOAP
Language and platform independent. The built-in ability to create Web services enables SOAP to handle message communication while sending language – and platform-independent responses.
Bind to various protocols. SOAP is flexible in terms of transport protocols that can be used in multiple scenarios.
Built-in error handling. The SOAP API specification allows an XML retry message to be returned with an error code and its description.
A series of security extensions. SOAP is integrated with ES-Security, so SOAP can meet enterprise-level transaction requirements. It provides privacy and integrity within a transaction while allowing encryption at the message level.
The editor
Switch to center
(Optional) Add image annotations in 140 characters or less
The shortage of the SOAP
Today, many developers are uncomfortable with the idea of having to integrate SOAP apis for several reasons.
-
Use ONLY XML. SOAP messages contain a lot of metadata and support only verbose XML formats for requests and responses.
-
Heavyweight. SOAP services require a lot of bandwidth due to the size of XML files.
-
Very specialized knowledge. Building a SOAP API server requires a deep understanding of all the protocols involved and their strict limitations.
-
Boring news updates. This rigid SOAP pattern slows down adoption because of the extra work required to add or remove a message attribute.
The SOAP use cases
Today, SOAP architectures are most commonly used for internal integration within an enterprise or with trusted partners.
Highly secure data transmission. SOAP’s strict message structure, security, and authorization capabilities make it the most suitable choice for enforcing formal software agreements between APIS and clients, while still conforming to the legal contract between API providers and API consumers. This is why financial organizations and other enterprise users choose to apply SOAP.
3.REST: Make data available as a resource
REST is now an unexplained API architectural style defined by a set of architectural constraints intended for adoption by a wide range of API consumers.
The most common API architectural style today was originally proposed by Roy Fielding in his doctoral thesis. REST makes data available on the server side and represents it in simple formats (usually JSON and XML).
How REST works
REST is not as strictly defined as SOAP. RESTful architectures should adhere to the following six architectural constraints:
-
Unified interface: A unified way to interact with a given server, regardless of device or application type.
-
Stateless: The request itself contains the state needed to process the request, and the server does not store anything related to the session.
-
The cache
-
Client-server architecture: Allows both sides to evolve independently
-
A hierarchical system of applications
-
The ability for a server to provide executable code to a client
In fact, some services are RESTful only up to a point. Their kernels, on the other hand, use RPC-style decomposition of larger services into resources and efficient use of HTTP infrastructure. But a key part Of REST is hypermedia, or HATEOAS, which stands for Hypertext As The Enginer Of Application State.
Basically, this means that the REST API provides metadata in each response that links all relevant information about how to use the API. This decouples the client and the server. As a result, both API providers and API consumers can evolve independently without hindering their communication.
The editor
Switch to center
(Optional) Add image annotations in 140 characters or less
“HATEOAS is the key feature of REST because it really makes REST REST. But since most people don’t use HATEOAS, they’re really using HTTP RPC.” These are some of the radical ideas expressed on Reddit. Indeed, HATEOAS is the most mature version of REST.
However, this is very difficult to achieve because it requires API clients to become much more advanced and intelligent than the way they are built and used today. So even today’s very good REST apis don’t always do that. This is why HATEOAS exists primarily as a long-term development vision for RESTful API design.
Such a gray area can indeed exist between REST and RPC when the server implements some of REST’s capabilities and some of RPC’s capabilities. But REST is based on resources or nouns, not actions or verbs.
The editor
Switch to center
(Optional) Add image annotations in 140 characters or less
In REST, HTTP methods such as GET, POST, PUT, DELETE, OPTIONS, and possibly PATCH are used to complete operations.
The editor
Switch to center
(Optional) Add image annotations in 140 characters or less
The advantage of the REST
Decoupling of client and server: Because REST decouples client and server as much as possible, REST can provide better abstraction than RPC. A system with an abstraction level can encapsulate its implementation details to better identify and maintain its properties. This makes the REST API flexible enough to evolve over time while maintaining a stable system.
Discoverability: Communication between the client and the server describes everything, so you don’t need external documentation to understand how to interact with the REST API.
Cache-friendly: REST reuses many HTTP tools and is the only API architectural style that can cache data at the HTTP level. In contrast, implementing caching on any other API requires configuring additional caching modules.
Multiple format support: REST’s ability to support multiple formats for storing and exchanging data is one of the reasons it is now a major choice for building public apis.
The lack of REST
There is no standard REST structure: There is no specific right way to build REST apis. How and which resources need to be modeled depends on different situations. This makes REST simple in theory but difficult in practice.
Heavy load: REST returns a wealth of metadata so that the client can learn all the necessary information about the state of the application from the response alone. For large network systems with a lot of bandwidth capacity, this “verbose” communication is not too much of a load. But bandwidth capacity is not always sufficient. This was the key driver behind Facebook’s GraphQL architecture style in 2012.
Over-response and under-response problems. REST responses can contain too much or too little data, often resulting in the client needing to send another request.
The REST of the case
Management API. Apis that focus on managing objects and cater to many consumers are the most common type of API in systems. REST helps make such apis discoverable and well documented, so REST is a good fit for this object model.
Simple resource-driven applications. REST is a very effective way to connect resource-driven applications that do not require query flexibility.
4.GraphQL: Request only the data you need
The REST API needs to be called multiple times to return the required resources. So GraphQL was invented and changed the rules of the game.
GraphQL is a syntax that describes how to make precise data requests. In applications where the data model has many complex entities that reference each other, implementing GraphQL is worthwhile.
The editor
Switch to center
(Optional) Add image annotations in 140 characters or less
Today, the GraphQL ecosystem is thriving, with powerful libraries and tools such as Apollo, GraphiQL, and GraphQL Explorer.
How GraphQL works
GraphQL starts with building schemas. A schema is a description of all the queries a user can make in the GraphQL API and all the types returned. Schema construction is difficult because it requires strong typing using schema Definition Language (SDL).
Because the schema is defined before the client queries, the client can validate its query statements to ensure that the server can respond to the query statements. When the query statement reaches the back-end application, the GraphQL operation is interpreted in terms of the entire schema and the front-end application returns the parsed data. The API sends a huge query to the server, and the API returns a JSON response containing only the data we need.
The editor
Switch to center
(Optional) Add image annotations in 140 characters or less
In addition to containing RESTful CRUD operations, GraphQL also has a subscription mechanism that allows it to receive real-time notifications from servers.
The advantage of GraphQL
Typed schema: GraphQL improves its discoverability by exposing what it can do up front. By pointing the client to the GraphQL API, we can find out what query statements are available.
No versioning: The best practice for versioning is not to version the API.
While REST provides different versions of the API, GraphQL uses a single version that is constantly updated, giving users constant access to new features and helping to provide cleaner, more maintainable server code.
Detailed error messages: GraphQL provides detailed information about the error that occurred in a soap-like manner. Its error message includes all parsers and points to the exact part of the query where the failure occurred.
Flexible permissions: GraphQL allows you to selectively expose some functionality while retaining private information. A REST architecture, on the other hand, cannot display only some data, either all or none.
The shortage of the GraphQL
Performance issues. GraphQL balances complexity to achieve its power. Too many nested fields in a request can cause system overload. Therefore, REST is still a better choice for complex queries.
Cache complexity. Since GraphQL no longer uses HTTP cache semantics, consumers need to customize additional caches.
Lots of pre-development education. Since there is not enough time to learn about a GraphQL operation and SDL, many projects decide to use the well-known REST approach.
GraphQL use cases
Mobile API. In this case, network performance and single message payload optimization are important. As a result, GraphQL provides a more efficient way to load data for mobile devices.
Complex systems and microservices. GraphQL is able to hide the complexity of multiple system integration behind its API. GraphQL aggregates data from multiple places and merges them into a global schema. This is especially important for legacy infrastructures or third-party apis that scale over time.
5. Which API pattern is best for your use case?
Each API project has different limitations and requirements. In general, the choice of API architecture depends on:
-
The programming language used,
-
Your development environment, as well
-
Your resource budget, both human and financial.
After understanding the pros and cons of each design style, the API designer can choose the one that best fits the project.
-
RPC, with its strong coupling, is good for internal microservices, but it is not a good choice for external apis or API services.
-
SOAP is a bit of a hassle to use, but its powerful security extensions make it irreplaceable for billing operations, reservation systems, and payments.
-
REST is the highest level of abstraction and best model for apis. But it tends to be “verbose” and add to the burden on the system — a problem if you’re using a mobile device.
-
GraphQL is a big step forward in data acquisition, but not everyone has the time and energy to master it.
At the end of the day, it’s appropriate to try out a particular API architecture for small use cases to see if it fits your use case and solves your problem. If it works for your use case, try extending it and see if it works for more use cases.
PS: In case you can’t find this article, please click “like” to browse and find it