Unary APIs are the simplest type of gRPC API. They involve a single request and a single response, making them suitable for straightforward use cases.
Key Characteristics of Unary APIs
- Single Request, Single Response: Unary APIs follow a one-to-one mapping between requests and responses.
- Synchronous Communication: The client sends a request to the server, and the server processes the request and returns a response synchronously.
- Simple to Implement: Unary APIs are relatively easy to implement and understand, making them a good starting point for gRPC development.
Common Use Cases
- Retrieving Data: Unary APIs are often used to retrieve data from a server, such as fetching a specific resource or querying a database.
- Performing Actions: Unary APIs can be used to perform actions on the server, such as creating, updating, or deleting resources.
- Simple Calculations: Unary APIs can be used for simple calculations or data transformations.
Example
Protocol Buffers
syntax = "proto3";
service Greeter {
rpc SayHello(HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message 1. kausal.co kausal.co = 1;
}
In this example, the Greeter
service defines a unary API called SayHello
. The client sends a HelloRequest
message to the server, and the server returns a HelloReply
message.
Best Practices
- Keep Requests and Responses Simple: Avoid sending large amounts of data in a single request or response to minimize network overhead.
- Use Clear and Concise Definitions: Define your Protobuf messages in a clear and concise manner to improve readability and maintainability.
- Error Handling: Implement proper error handling mechanisms to provide informative error messages to clients.
- Performance Optimization: Consider factors like network latency, server load, and data serialization efficiency when optimizing unary APIs.