Back to Examples

gRPC client - Simple RPC

A grpc:Client is created by providing the endpoint URL of a gRPC server. In the simple RPC scenario, once connected, the client sends a request message to the remote service and waits for the response message. Use this to send a single request message and get a single response message back.

Generate the service definition

  • 1.Create a new Protocol Buffers definition file named grpc_simple.proto and add the service definition below.
syntax = "proto3";

import "google/protobuf/wrappers.proto";

service HelloWorld {
    rpc hello (google.protobuf.StringValue) returns (google.protobuf.StringValue);
}
  • 2.Run the command below from the Ballerina tools distribution for stub generation.
$ bal grpc --input grpc_simple.proto  --output stubs

Once you run the command, the grpc_simple_pb.bal file gets generated inside the stubs directory.

Prerequisites

Implement and run the client

  • 1.Create a Ballerina package (e.g., client). Delete the main.bal file created by default as it is not required for this example.
  • 2.Copy the generated grpc_simple_pb.bal file from the stubs directory to the client package.
  • 3.Create a new grpc_simple_client.bal file inside the client package and add the client implementation below.
import ballerina/io;

public function main() returns error? {
    // Creates a gRPC client to interact with the remote server.
    HelloWorldClient ep = check new ("http://localhost:9090");

    // Executes a simple remote call.
    string result = check ep->hello("WSO2");
    // Prints the received result.
    io:println(result);
}
  • 4.Run the client by executing the command below.
$ bal run clientHello WSO2

Related links

PreviousCheck deadline
NextServer-side streaming RPC