1 the introduction
Whenever the project enters the joint investigation stage, or the interface is agreed in advance, the front and back end will get together and discuss enthusiastically. Probably 99% of the scenarios are about agreeing on Http interfaces, talking about what urls are, what inbound arguments are, what outbound arguments are.
Some teams have more efficient interface conventions at the front and back ends, where the back end takes out the interface definition code and the front end converts (or automatically converts) Typescript definition files.
But this work is all about Http interfaces. In today’s article on when-to-use- What -rest- GraphqL-webhooks – GRPC, we will take a look at how interfaces can be agreed and which scenarios are applicable to them. What scenario are you in right now?
2 an overview
This article focuses on four interface design schemes: REST, gRPC, GraphQL, Webhooks.
REST
REST is perhaps the most general and commonly used interface design scheme. It is stateless and resource-centered. It defines a series of URL conventions for how to operate resources, and the operation types are represented by HTTP Methods such as GET, POST, PUT and DELETE.
REST is based on the native HTTP interface, so the transformation cost is very small, and its stateless nature reduces the coupling degree of the front and back end, which facilitates rapid iteration.
As we move forward, REST may be better suited to provide microservice apis.
Examples:
The curl -v - X GET https://api.sandbox.paypal.com/v1/activities/activities?start_time=2012-01-01T00:00:01.000Z& End_time = 2014-10-01 T23:59:59. 999 z & amp; page_size=10 \ -H"Content-Type: application/json" \
-H "Authorization: Bearer Access-Token"
Copy the code
gRPC
GRPC is a new attempt to RPC, the biggest feature is the use of protobufs language formatting data.
RPC is mainly used for method calls between servers, and serialization/deserialization efficiency is the most important factor affecting its performance. The purpose of RPC is to create an efficient and low-consumption service invocation method. Therefore, RPC is suitable for resource, bandwidth, and performance-sensitive scenarios such as IOT. GRPC uses Protobufs to further improve the serialization speed and reduce the packet size.
Examples:
GRPC is mainly used for transmission between services. Here Nodejs is used as an example:
- Define the interface. Since gRPC uses Protobufs, the interface definition file is
helloword.proto
:
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
Copy the code
The service Greeter is defined. It has two methods: SayHello and SayHelloAgain. The structure of incoming and outgoing arguments is defined by the message keyword.
In fact, with Protobufs, very little of the data is transferred, and as a trade-off, both sides need to know the interface definition rules to serialize/deserialize.
- Define server:
function sayHello(call, callback) {
callback(null, { message: "Hello " + call.request.name });
}
function sayHelloAgain(call, callback) {
callback(null, { message: "Hello again, " + call.request.name });
}
function main() {
var server = new grpc.Server();
server.addProtoService(hello_proto.Greeter.service, {
sayHello: sayHello,
sayHelloAgain: sayHelloAgain
});
server.bind("0.0.0.0:50051", grpc.ServerCredentials.createInsecure());
server.start();
}
Copy the code
We support the gRPC service on port 50051, register the service Greeter, and do some business with the sayHello sayHelloAgain method and return some data to the caller.
- Define the client:
function main() {
var client = new hello_proto.Greeter(
"localhost:50051",
grpc.credentials.createInsecure()
);
client.sayHello({ name: "you" }, function(err, response) {
console.log("Greeting:", response.message);
});
client.sayHelloAgain({ name: "you" }, function(err, response) {
console.log("Greeting:", response.message);
});
}
Copy the code
As you can see, both the client and the server need to get the PROTO structure, and the data sent by the client depends on the methods provided by the PROTO package. The framework will do the serialization/deserialization work built-in.
There are also additional ways to convert gRPC into HTTP services, allowing web pages to enjoy the benefits of its high efficiency and low consumption. But don’t forget that RPC is most commonly used in hardware domains such as IOT, and web scenarios may not care about saving a few kilobytes of traffic.
GraphQL
GraphQL is not a replacement for REST, but another form of interaction where the front end determines what the back end returns.
The biggest benefit of GraphQL is that the request response is streamlined without redundant fields, and the front end can decide what data the back end returns. Note, however, that the decisions of the front end depend on what data the back end supports, so GraphQL is more like REST with a simplified return value, and the back end interface can define all the functionality at once, rather than developing it individually.
Again, compared to REST and gRPC, GraphQL is an anti-pattern that the front end decides to return results.
Examples:
GitHub GraphQL API is recommended for reference
For example, to query members of an organization, a REST-style interface might be:
curl -v https://api.github.com/orgs/:org/members
Copy the code
The meaning is clear, but the problem is that the return result is not clear and you have to actually debug it to know. The equivalent GraphQL looks like this
query {
organization(login: "github") {
members(first: 100) {
edges {
node {
name
avatarUrl
}
}
}
}
}
Copy the code
The result returns the same format structure as the convention, with no extra fields:
{
"data": {
"organization": {
"members": {
"edges": [{"node": {
"name": "Chris Wanstrath"."avatarUrl": "https://avatars0.githubusercontent.com/u/2?v=4"}}, {"node": {
"name": "Justin Palmer"."avatarUrl": "https://avatars3.githubusercontent.com/u/25?v=4"}}]}}}}Copy the code
But as you can see, doing so requires a system to help you write queries, and many frameworks provide this functionality, such as Apollo-client.
Webhooks
If GraphQL is a subversion of the front-end interaction model, then Webhooks are downright anti-pattern, because by definition, the front-end does not actively send requests, the back-end pushes them.
It’s best for round questions. Or polling is an act of compromise, when the back end does not support the Webhooks schema.
Examples:
Webhooks themselves can also be implemented by REST or gRPC, so no code will be posted. As a common example, if your friend posts a message and the backend pushes that message to all other friends’ clients, this is a typical Webhooks scenario.
Finally, the author comes to the conclusion that these four scenarios have different usage scenarios and cannot be replaced by each other:
- REST: Stateless data transfer structures suitable for scenarios with common, rapidly iterating, and standardized semantics.
- GRPC: A lightweight transmission mode, suitable for scenarios with high performance requirements or demanding environments, such as IOT.
- GraphQL: Requesters can customize the return format to reduce the cost of front-end and back-end invocation to some extent.
- Webhooks: Push service for scenarios where the server actively updates client resources.
3 intensive reading
REST is not suitable for all scenarios
This article gives us a larger perspective on interface issues in daily development. For front-line students, 90% of the interfaces are NON-REST Http interfaces, and there are very few teams that can truly implement REST. This raises an important question: how much of a part of the overall business process are the benefits of REST?
Not only the use of interface design scheme should be divided into different scenarios, but also the importance of a certain interface scheme should be further subdivided: when doing an open interface project, providing Http interface for the use of a third party, the semantics of the interface must be well planned, so that it is easier for everyone to reach a consensus to use REST conventions; In fact, when developing a product, the front and back end do not care about whether the interface format is standard or not, and even in the development of Intranet products, performance and redundancy are not considered, efficiency is the first. So the first lesson is not to blame the current team business for not using a better interface contract, because interface contracts are likely to be determined by the business form, not by a technical comparison.
GRPC is the preferred server interaction
When the front-end students switch to node development, they like to use Http for communication between servers, but may wonder why the company’s internal Java or C++ written services do not provide Http calls, but another name. After understanding gRPC, you can realize that these platforms are the encapsulation of RPC mode. Communication between servers has high requirements on performance and latency, so they are suitable for gRPC and other services that are optimized for performance.
GraphQL needs a companion
GraphQL is not a replacement for REST, so don’t expect your team to improve development efficiency by X% by migrating from the Http interface to GraphQL. GraphQL scheme is a new interaction convention between front and back ends, so the cost of getting started will be relatively high. At the same time, in order to facilitate the front end students to assemble query, part of the back-end workload is transferred to the front end. If there is no easy enough platform to quickly consult, generate and maintain these definitions, the development efficiency may decrease rather than increase.
In general, using GraphQL is ideal if you have an open API or a complete set of scenarios, but for teams that are rapidly iterating and have a less mature platform, continuing to use the standard Http interface can get projects done faster.
Webhooks solve special scenario problems
Webhooks are suitable for active data push for third-party platform authentication and login scenarios where there is no front-end interface for transfer, or payment scenarios with strong security requirements. In plain English, it is not possible to participate on the front end, or it is not appropriate to participate because of front-end security issues. This is the Webhooks scenario. Webhooks are clearly not a replacement for Http either, but they are a new way of interacting with both the front and back ends.
For slow query and other scenarios, the front-end generally uses polling to complete, which is weaker than Socket experience, but the stateless feature will reduce the burden of the server, so slow query and instant messaging should be treated differently, and the user’s sensitivity to the timeliness of the message determines which scheme to use.
4 summarizes
Finally, the above summary must have many omissions, welcome to add.
5 More Discussions
REST, GraphQL, Webhooks, & gRPC How to Type? Issue #102 dT-fe /weekly
If you’d like to participate in the discussion, pleaseClick here to, with a new theme every week, released on weekends or Mondays.