gRPC – UNARY API

Setup

Install grpc-tools and google-protobuf as node module

Folder structure will be as below:

Let’s create a dummy proto file

Its time to generate the code from the proto file. Let’s use the command that we have used in our previous blog of Protocol Buffers.

GRPC_TOOLS_PLUGIN="$HOME/AppData/Roaming/npm/grpc_tools_node_protoc_plugin.cmd" && C:/Users/deepak.sood/Downloads/protoc-3.13.0-win64/bin/protoc.exe -I=. ./proto/*.proto --js_out=import_style=commonjs,binary:./server --grpc_out=./server --plugin=protoc-gen-grpc=$GRPC_TOOLS_PLUGIN

#I ran this command on gitbash

This command will generate the below files:

Server Setup

It’s time to setup a gRPC server with no service on it and we will start out server on a specific node.

Let’s create an index.js inside the server. But before that install grpc module

npm install grpc

Our server is up and running on the defined port now.

Client Setup

In this we will connect our client to the server and will start our client on a specific port.

Unary API

  • Unary RPC calls are the basic Request/Response that everyone is familiar with
  • The client will send one message to the server and will receive one response from the server
  • Unary RPC calls are the most commonly used API calls
    – They are suited when the data is small
  • In gRPC Unary calls are defined using Protocol Buffers
  • For each RPC call we have to define a “Request” message and a “Response” message

Let’s create a “Unary” Greet API in which:

  • Our message is Greeting and contains firstname and lastname string field
  • It will take a GreetRequest that contains a Greeting
  • It will return a GreetResponse that contains a result string

Step 1 – Creating our proto

Step 2 – Generating code from the proto file

GRPC_TOOLS_PLUGIN="$HOME/AppData/Roaming/npm/grpc_tools_node_protoc_plugin.cmd" && C:/Users/deepak.sood/Downloads/protoc-3.13.0-win64/bin/protoc.exe -I=. ./protos/greet.proto --js_out=import_style=commonjs,binary:./server --grpc_out=./server --plugin=protoc-gen-grpc=$GRPC_TOOLS_PLUGIN
So we have generated a Unary API

Step 3 – Server Implementation

In this:

  • We will implement a Unary Greet RPC
  • We will hook our new GreetService to our Server
  • We will start our server

We would require the files generated in the implementation of our server. Therefore, we will import those files in the server file.

There is mistake on line 20 which is rectified in the code pasted below

We are not done yet, we need to add the service now.

Along with this we need to pass few other things for it to work i.e the RPC methods that we will be calling.

var greets = require('../server/protos/greet_pb');
var service = require('../server/protos/greet_grpc_pb');

var grpc = require('grpc');

/*
Implementing the greet RPC method
*/

// this should be the same name as our API as present in greet_grpc_pb file
function greet(call, callback){

    // creating the actual greeting response
    var greeting = new greets.GreetResponse();

    //now we have our greet response, so let's now construct the response
    // call is used as it will have all the information from line 11 when called
    //getGreeting is from the GreetRequest object
    greeting.setResult(
        "Hello" + call.getGreeting().getFirstName() 
    )

    callback(null, greeting); // passed in the greeting to be passed on to the client 


}

function main(){
    var server = new grpc.Server();
    server.addService(service.GreetServiceService, {greet: greet})
    server.bind("127.0.0.1:50051", grpc.ServerCredentials.createInsecure());
    server.start();

    console.log("Server running on port 127.0.0.1:50051")
}

main();var greets = require('../server/protos/greet_pb');
var service = require('../server/protos/greet_grpc_pb');

var grpc = require('grpc');

/*
Implementing the greet RPC method
*/

// this should be the same name as our API as present in greet_grpc_pb file
function greet(call, callback){

    // creating the actual greeting response
    var greeting = new greets.GreetResponse();

    //now we have our greet response, so let's now construct the response
    // call is used as it will have all the information from line 11 when called
    //getGreeting is from the GreetRequest object
    greeting.setResult(
        "Hello" + call.request.getGreeting().getFirstName() 
    )

    callback(null, greeting); // passed in the greeting to be passed on to the client 


}

function main(){
    var server = new grpc.Server();
    server.addService(service.GreetServiceService, {greet: greet})
    server.bind("127.0.0.1:50051", grpc.ServerCredentials.createInsecure());
    server.start();

    console.log("Server running on port 127.0.0.1:50051")
}

main();var greets = require('../server/protos/greet_pb');
var service = require('../server/protos/greet_grpc_pb');

var grpc = require('grpc');

/*
Implementing the greet RPC method
*/

// this should be the same name as our API as present in greet_grpc_pb file
function greet(call, callback){

    // creating the actual greeting response
    var greeting = new greets.GreetResponse();

    //now we have our greet response, so let's now construct the response
    // call is used as it will have all the information from line 11 when called
    //getGreeting is from the GreetRequest object
    greeting.setResult(
        "Hello" + call.getGreeting().getFirstName() 
    )

    callback(null, greeting); // passed in the greeting to be passed on to the client 


}

function main(){
    var server = new grpc.Server();
    server.addService(service.GreetServiceService, {greet: greet})
    server.bind("127.0.0.1:50051", grpc.ServerCredentials.createInsecure());
    server.start();

    console.log("Server running on port 127.0.0.1:50051")
}

main();

Let’s test this now:

The service is up and running

Step 4 – Client Implementation

We will test our client against the server running.

Let’s import the files as we did in server implementation.

The second step would be to create a greet request.

var grpc = require('grpc');
var greets = require('../server/protos/greet_pb');
var service = require('../server/protos/greet_grpc_pb');

function main(){

    console.log('Hello from Client');

    var client = new service.GreetServiceClient(
        'localhost:50051',
        grpc.credentials.createInsecure()
    )

    console.log('client', client)
    // we code here later

    var request = new greets.GreetRequest();

    //creating the actual greeting as we did for protobuf in previous blog
    //refer line 15 of proto file
    //created a protocol buffer greeting message
    var greeting = new greets.Greeting();
    greeting.setFirstName("Deepak")
    greeting.setLastName("Sood")

    //set the greeting
    request.setGreeting(greeting);

    //setting up the client now and calling the greet from the server which knows what should be the request and response
    client.greet(request, (error, response)=>{
        if(!error){
            console.log("Greeting response: "+ response.getResult());
        }else{
            console.error(error)
        }
    })
}

main()

It’s time to run our server and client.

Let’s see what happens when we stop our server

We get an error

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts