Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How should the architect choose the right API for the application

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how should the architect choose the right API for the application". In the daily operation, I believe that many people have doubts about how the architect should choose the right API for the application. The editor has consulted all kinds of materials and sorted out the simple and useful operation methods. I hope it will be helpful to answer the doubts of "how the architect should choose the right API for the application". Next, please follow the editor to study!

Originally in the field of Unix/Linux programming, it provided the means of inter-process communication, such as pipes, semaphores, message queues, Socket and so on. If your application is written in different languages, you can only choose Socket communication as a means of API between applications. However, Socket communication is a very low-Level communication means, which uses the underlying data packets as abstract and communication content, so it is difficult to maintain and use. Of course, there are some other means of communication between systems, such as sharing files or FTP, which are also faced with various inconveniences. We want to provide a more advanced means of interaction, directly interacting with my application's abstractions, which may be methods, functions, and objects. As a result, there are various API technologies that support these requirements.

Early interprocess communication technologies included:

DCOM (Distributed Component Object Model) distributed component object model, which is Microsoft's technology, can only be used on Windows platform to realize communication between remote objects through the network.

RMI (Remote Method Call) Java's remote method call, which is Java's own RPC, can only be used for remote calls between Java applications.

The local interface of JNI Java supports Java applications to call local methods, which crosses the language barrier, but it is only limited to Java applications calling other local applications, which is not interoperable and is an one-way channel.

1.CORBA

In 1991, a technology called CORBA (Common Object Request Broker Architecture) appeared. I remember my first job was the development of a telecom network management system. We used CORBA to communicate between different systems. It mainly involves C++ and Java.

CORBA, similar to DCOM and RMI mentioned earlier, provides remote object / method calls, but CORBA is a language-and implementation-independent technology. I remember that our test scripts used TCL, and there was also an implementation of CORBA, which means that CORBA set the standard for communication between systems decoupled from the language. This is its greatest advantage. In those days, it was very common to use CORBA as a means of communication between systems.

The process of developing CORAB starts with the definition of IDL. Users define the object through IDL, then implement the application logic of the object on the server side, and call the object on the Client side.

But CORBA is not without shortcomings, otherwise we would not rarely see today's applications using CORAB as API. His main problems are:

The life cycle management of objects is complex. The discovery, creation and destruction of remote objects can cause problems.

The architecture of the whole CORAB is quite complex. Just look at its architecture diagram.

In short, today you are going to develop a reference, unless you want an existing system interaction, you should not choose CORBA.

2.XML-RPC / SOAP

XML-RPC was published in 1998 by Dave Winer and Microsoft of UserLand Software (UserLand Software). Later, with the continuous introduction of new features, this standard gradually evolved into today's SOAP protocol.

Here is an example of a request / response from XML-RPC:

Examples.getStateName 40 South Dakota

SOAP is the abbreviation of Simple Object Access Protocol. SOAP provides the Messaging Protocol layer of the Web service protocol stack for Web services. It is a XML-based protocol that consists of three parts:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

An envelope that defines the message structure and how to handle it

A set of coding rules for expressing instances of data types defined by an application

Conventions that represent procedure calls and responses

SOAP has three main characteristics:

Scalability (security and WS-Addressing under development)

Neutrality (SOAP can be operated through any protocol such as HTTP,SMTP,TCP,UDP)

Independence (SOAP allows any programming language)

As an example of what the SOAP process can do, an application can send an SOAP request to a server that has a Web service with search parameters enabled (for example, a real estate price database). The server then returns a SOAP response (a document in XML format containing the resulting data), such as price, location, and functionality. Because the generated data is in a standardized machine-resolvable format, the requesting application can integrate it directly.

The SOAP architecture consists of the following layers of specifications:

Message format

Mail Exchange Mode (MEP)

Underlying transport protocol binding

Message processing model

Protocol scalability

Here is an example of an SOAP message:

POST / InStock HTTP/1.1 Host: www.example.org Content-Type: application/soap+xml; charset=utf-8 Content-Length: 299 SOAPAction: "http://www.w3.org/2003/05/soap-envelope" T

Compared with XML-RPC, it has more functions and, of course, more complex message structure.

SOAP is a Webservice standard recommended by W3C, and it was once very popular, but we can see that the message based on XML is more complex, and the message itself has a lot of overhead because of XML. Then there is the RPC format based on JSON. But on the whole, SOAP is a thing of the past, and with today's application building, your chances of choosing it should be slim.

3.REST

REST is the most popular API nowadays. Because a large number of Web applications use REST as their API choice. REST is the abbreviation of Representational State Transfer. It is a kind of World wide Web software architecture style proposed by Dr. Roy Thomas Fielding in his doctoral thesis in 2000.

The purpose is to facilitate the transmission of information between different software / programs on a network, such as the Internet. Presentation layer state transition is a set of constraints and attributes based on Hypertext transfer Protocol (HTTP). It is a software construction style designed to provide World wide Web services. Network services that conform to or are compatible with this architectural style (referred to as REST or RESTful for short) allow clients to make requests to access and operate network resources with a uniform resource identifier, which is consistent with a predefined set of stateless operations. Therefore, the state transition of the presentation layer provides a collaborative nature (interoperability) in which resources can be used interactively between computing systems on the Internet.

Compared with other kinds of network services, such as SOAP services, the resources on the network are accessed by the set of operations defined by itself. At present, among the three mainstream Web service implementation schemes, because the REST pattern is more concise than the complex SOAP and XML-RPC, more and more Web services are designed and implemented in REST style. So we can see that the development of software is generally from complex to simple, only simple things will become more vitality.

In order for any application to actually implement RESTful, six architectural constraints must be followed:

Unified interface: means that the API interface must be provided to API consumers in Web applications.

Client server: the client and server must be independent of each other, and the client should only know the URI of the resource.

Stateless: the server must not store anything related to client requests. The client is responsible for maintaining the state of the application.

Cacheable: resources must be cacheable.

Hierarchical system: the architecture must be hierarchical, which means that the components of the architecture can reside on multiple servers.

On-demand code: the client must be able to get executable code in response. This is an optional constraint.

REST-based Web services are called RESTful Web services. In these applications, each component is a resource that can be accessed through a public interface using HTTP standard methods. The following four HTTP methods are commonly used in REST-based architectures:

GET- 's read-only access to resources.

POST-create a new resource.

DELETE- deletes the resource.

PUT- updates existing resources / creates new resources.

RESTFul style API all operations are a verb that corresponds to a type of HTTP request. Each operation defines some kind of behavior for the resource of the operation. This abstraction is especially suitable for many Web applications. There is a database in the background, and each REST endpoint corresponds to a database table. It is natural to use REST operations to add, delete, query and modify tables.

Of course, RESTFul's style also has its shortcomings:

Not all application operations can be matched by the addition, deletion, query and modification of resources. In actual development, it is often necessary to map an operation to a resource.

REST is a synchronous service, and a callback mechanism should be introduced if necessary. For example, Webhook.

REST only provides the option for the client to call the server, and does not support the server to initiate requests.

So new API types will appear to solve these problems.

4.GraphQL

GraphQL is an open source API data query and manipulation language and implementation of the corresponding runtime environment to achieve the above operations. GraphQL was developed internally by Facebook in 2012 and was publicly released in 2015. On November 7, 2018, Facebook transferred the GraphQL project to the newly established GraphQL Foundation.

The GraphQL specification outlines five design principles, making it a well-designed solution for modern front-end development. Let's look at the design principles of GraphQL.

The query is hierarchical, with hierarchical and nested fields, and the query matches the response data one-to-one. Queries and responses are shaped like trees, and you can query other nested fields for each project.

The structure is product-centric, focusing on how the front end wants to receive data and building the runtime needed for delivery. In this way, you can request all the data you need from the back end, and then let the server get the data from different endpoints according to the specification of GraphQL.

It uses an application-specific type system that enables developers to ensure that queries use valid types and are syntactically correct before execution.

The GraphQL query is specified on the client, so the client knows exactly in what format it will receive the data.

The server structure with GraphQL must be self-contained or can be queried by GraphQL itself. This will enable powerful developer tools, such as GraphiQL or GraphQL Playground, both of which will enable developers to see exactly which queries and fields are available for them to use on the server.

Like RESTful API, GraphQL API is designed to process HTTP requests and provide responses to those requests. But the similarities end here. In cases where REST API is based on a connection between the request method and the endpoint, GraphQL API is designed to use only one endpoint that is always queried through the POST request, usually using URL yourdomain.com/graphql.

Once the GraphQL endpoint is reached, the burden of the client request will be handled entirely within the request body. The request subject must comply with the GraphQL specification, and the API must have the appropriate server-side logic to process these requests and provide the appropriate response. This provides a smoother client experience than RESTful API, which may require the client to make multiple requests for multiple data and operate after the data is returned.

As in the example in the figure above, a user requests data through the API of RESTFul. Two GET requests are required. First, get Assets, and then get comments through AssetID. Through GraphQL, users only need to describe the structure and conditions of the requested data, and then they can get all the data they need through one request, which simplifies the interaction between the client and the server.

GraphQL provides better performance than REST API and can pay off for front-end developers. Creating a server using the GraphQL specification may require more setup and writing predictive server-side logic to parse and process requests. Although the installation cost of GraphQL may be higher than that of traditional REST architectures, more maintainable code, powerful development tools, and simplified client queries are all good benefits.

In addition to the greatest advantage of flexibility, GraphQL has the following advantages:

Declarative data acquisition avoids additional interaction between client and server

A good development experience does not require version control because the introduction of new fields does not affect API queries. At the same time, client-side and server-side teams can work independently in parallel.

Strongly typed GraphQL patterns make the code predictable and detect errors early.

Of course, GraphQL is not without its shortcomings:

With GraphQL, it can be tricky if you need to find information about a list or a collection of records. For example, if you want to get the details of the list of users with their addresses, it will execute n + 1 queries. One is used for the user list, and then n queries the address of each user. Now it can seriously affect performance, so you have to handle it very carefully.

It is difficult to cache, and the main purpose of caching API responses is to get responses from future requests more quickly. Unlike GraphQL, RESTful API can take advantage of the cache built into the HTTP specification. As mentioned earlier, GraphQL queries can request any field of a resource, so caching is inherently difficult.

5.gRPC

GRPC is an open source remote procedure call framework for high-performance communication between services. This is an effective way to connect services written in different languages with pluggable support for load balancing, tracking, health checking, and authentication. By default, gRPC uses Protobuf (protocol buffer) to serialize structured data. In general, gRPC is considered to be a better alternative to the REST protocol for micro-services architecture. The "g" in gRPC can be attributed to the Google that originally developed the technology.

GRPC is an adaptation of the traditional RPC framework. So, how is it different from the existing RPC framework?

The most important difference is that gRPC uses the protobuf protocol buffer as the interface definition language for serialization and communication, rather than JSON / XML. Protocol buffers can describe the structure of the data, and code can be generated from that description to generate or parse byte streams that represent structured data. This is why gRPC prefers Web applications in multiple languages (implemented using different technologies). The binary data format makes communication easier. GRPC can also be used with other data formats, but protobuf is preferred.

Similarly, gRPC is built on top of HTTP / 2 and supports two-way communication as well as traditional request / response. GRPC allows loose coupling between the server and the client. In practice, the client opens a long-term connection to the gRPC server, and a new HTTP / 2 stream is opened for each RPC call.

As shown in the figure above, gRPC supports different modes of client-side and server-side communication, greatly facilitating different interoperability capabilities.

Unlike REST that uses JSON (mainly JSON), gRPC uses Protobuf, which is a better way to encode data. Because JSON is a text-based format, it is much heavier than compressed data in protobuf format. Another significant improvement of gRPC over REST is that it uses HTTP 2 as its transport protocol. HTTP 1.1 used by REST is basically a request-response model. GRPC takes advantage of the two-way communication capabilities of HTTP 2 and the traditional response request structure. In HTTP 1.1, when multiple requests come from multiple clients, they are processed one by one. This slows down the system. HTTP 2 allows multiplexing, so multiple requests and responses can be processed at the same time.

The development model of gRPC is somewhat similar to that of CORBA mentioned earlier. Protobuf acts as IDL, then uses tools to generate code in various languages, and finally implements server-side and client-side logic on the generated code.

The advantages of gRPC are:

Excellent performance due to the use of protobuf coding and http/2

Support two-way communication between server and client

Easy to use and requires less code than REST development

Disadvantages:

A steeper learning curve

There are not as many languages supported as REST, and of course it is still in development.

Because of the need for Protobuf compilation, this brings some coupling between the server and the client, because the code needs to be recompiled when the interface changes. For REST, there may be different solutions based on different tool chains

Because of its high performance, gRPC is more suitable for communication selection of internal components of the system. In the micro-service architecture shown below, external services use REST or GraphQL's API, while internal micro-services use gRPC.

At this point, the study on "how the architect should choose the right API for the application" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report