Implementing Unary API Server

A unary API server in gRPC handles a single request and sends a single response. Here’s a detailed guide on how to implement one:

1. Define the Service and Messages

  • Create a .proto file to define the service and message definitions.
  • Use clear and concise names for services and messages.
  • Specify the request and response types for the unary API.

Example:

Protocol Buffers

syntax = "proto3";

service Greeter {
  rpc SayHello(HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

2. Generate Server Code  

  • Use the protoc compiler to generate server code from the .proto file.
  • The generated code will include an interface that defines the service and a base class for implementing the service.

Example:

Java

public interface GreeterGrpc {
  public static abstract class GreeterImplBase extends io.grpc.stub.AbstractStub<GreeterImplBase> {
    ...
  }
}

3. Implement the Service

  • Create a class that extends the generated base class.
  • Override the method corresponding to the unary API you defined.
  • Implement the logic for handling the request and generating the response.

Example:

Java

public class GreeterImpl extends GreeterGrpc.GreeterImplBase {
    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
        HelloReply reply = HelloReply.newBuilder().setMessage("Hello,    " + request.getName()).build();
        responseObserver.onNext(reply);
        responseObserver.onCompleted();   
    }
}

4. Start the Server

  • Create a ManagedChannelBuilder object to configure the server.
  • Set the server address and port.
  • Build the channel and start the server.

Example:

Java

public class Server {
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerBuilder serverBuilder = ServerBuilder.forPort(50051);   
        serverBuilder.addService(new GreeterImpl());
        Server server = serverBuilder.build();

        server.start();
        System.out.println("Server started on port " + server.getPort());

        server.awaitTermination();
    }
}

By following these steps, you can create a basic unary API server in gRPC. You can customize the server implementation to handle specific use cases and add additional features as needed.

Understanding Unary API
Overview of Server Streaming API

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?