What is gRPC ? How to implement gRPC in Node.js
Tags: showdev, microservices, node
Published: 2019-05-11 07:36:40

---
title: What is gRPC ? How to implement gRPC in Node.js
published: true
description: gRPC is a protocol which can be used for communication in Microservices Architecture
tags: showdev, MicroServices, Node
canonical_url : https://cloudnweb.dev/2019/05/what-is-grpc-how-to-implement-grpc-in-node-js/
---

<!-- wp:paragraph -->
<p>by definition,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>gRPC (gRPC Remote Procedure Calls) is an open source remote procedure call (RPC) system initially developed at Google. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as authentication, bidirectional streaming and flow control, blocking or nonblocking bindings, and cancellation and timeouts. </code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>so many jargon words..right?. Let's break it down one by one.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>gRPC built on top of Remote Procedure Call and Http/2 with Protocol Buffers.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>what is Remote Procedure Call(RPC) ?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Firstly,<a href="https://www.youtube.com/watch?v=gr7oaiUsxSU">Remote Procedure Call</a> is a protocol where one program can use to request a service which is located in another program on different network without having to understand the network details.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>it differs from normal procedure call. it makes use of kernel to make a request call to another service in the different network.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>what is Protocol Buffer?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><a href="https://developers.google.com/protocol-buffers/">protocol buffers</a> are language neutral way of serializing structure data. In simple terms, it converts the data into binary formats and transfer the data over the network. it is lightweight when compare to XML,JSON</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>How gRPC Works?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>gRPC client sends the request to the server and gRPC server sends back the response. Most importantly, the way that gRPC sends and receive the request makes it more special</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>gRPC supports <strong>Bi-Directional streaming </strong>which is not supported in any other communication. Bi-Directional Streaming is sending stream of data and receiving stream of data. there are different way to send request/response</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>Unary RPC's</strong> - it is a way of sending a single request and receiving the response</li><li><strong>Server Streaming RPC's</strong> : it is a process of sending the stream of data from server end.</li><li><strong>Client Streaming RPC's</strong> : it is a process of sending the stream of data from client side.</li><li><strong>Bi-Directional Streaming RPC's</strong> : it is a process of sending the stream of data from client as well as Server.</li></ul>
<!-- /wp:list -->

<!-- wp:image {"id":443} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/05/gRPC.png" alt="" class="wp-image-443"/><figcaption>Source : <a href="https://grpc.io/docs/guides/">https://grpc.io/docs/guides/</a></figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Implementing gRPC in Node.js</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Let's see how we can use gRPC in Node.js by building a simple to-do application with CRUD APi's</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Firstly, we need to install, dependencies for the application</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npm install --save grpc
npm install --save uuid</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>After that, we need to create a file called <strong>todo.proto</strong> which is nothing but a protocol buffer of the data.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>API to Fetch the Data</h3>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>syntax = "proto3";


service TodoService {
    rpc List(Empty) returns (TodoList) {}
}

message Empty {}

message Todo {
    string id=1;
    string title = 2;
    bool iscompleted = 3;
}

message TodoList {
    repeated Todo todo = 1;
}
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Firstly, .proto file is something like a way we define to structure the request and response data.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Mainly, there are three parts in the proto buffer file which are <strong>Entity</strong> , <strong>Request Object</strong> and <strong>Response Object</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>message Empty {} </code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>It is the Request Object which is used in the Service <strong>rpc</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>message TodoList {
    repeated Todo todo = 1;
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p><strong>TodoList</strong> is the <strong>Response Object</strong>. which you sends to the client as the response. If you note that, there is something called <strong>repeated</strong>. it is something like an Array. Here, we are defining it like <em>Array of todo</em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, you need to create a file called <strong>server.js</strong> where we <a href="https://cloudnweb.dev/2019/04/handle-file-upload-in-node-js/">handle the request</a></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const grpc = require('grpc');
const uuid = require('uuid/v1');
const todoproto = grpc.load('todo.proto')
const server = new grpc.Server()


server.bind('127.0.0.1:50051',
grpc.ServerCredentials.createInsecure())
console.log('server is running at http://127.0.0.1:50051')
server.start()</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>if you run the server.js in the command line , it should display the message</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>server is running at http://127.0.0.1:50051</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>node server.js</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Now, we need to Add the service to the server file. add the following code in <strong>server.js</strong> file</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>server.addService(todoproto.TodoService.service,{
    list : (_,callback) =>{
        callback(null,todos)
    }
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>After that, create a file name called <strong>client.js</strong> which act as a client to sends request to gRPC Server.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const grpc = require('grpc');

const PROTO_PATH = './todo.proto'

const TodoService = grpc.load(PROTO_PATH).TodoService

const client = new TodoService('localhost:50051',
grpc.credentials.createInsecure())

module.exports = client</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>To make a call from client, you need to import the file in actual file which calls the service. create a file called <strong>get_todos.js </strong>which calls the service using client.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const client = require('./client')

client.list({},(error,todos) => {
    if(!error){
        console.log('successfully fetched todo lists');
        console.log(todos);
    }
    else{
        console.error(error);
    }
});</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>To test the List API.  you need to Run the server and client which calls the Service.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>node server.js
node get_todos.js</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3>Create Insert RPC Service to Create New&nbsp;Todo </h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Firstly, you need to add the insert service in the<strong> todo.proto</strong> .</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>syntax = "proto3";


service TodoService {

    rpc List(Empty) returns (TodoList) {}
    rpc Insert(Todo) returns (Todo) {}
}

message Empty {}

message Todo {
    string id=1;
    string title = 2;
    bool iscompleted = 3;
}

message TodoList {
    repeated Todo todo = 1;
}
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>After that, we need to add the insert service in <strong>server.js</strong></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>server.addService(todoproto.TodoService.service,{
    list : (_,callback) =>{
        callback(null,todos)
    },
     insert : (call,callback) => {
            let todo = call.request;
            todo.id = uuid()
            todos.push(todo)

            callback(null,todo)
        },
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Now, you need to create a file called <strong>insert_todo.js</strong> which calls the insert service using the client.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const client = require('./client')

let newTodo = {
    title : 'New checklist',
    iscompleted : false
 }

 client.insert(newTodo,(error,todo) => {
     if(!error){
         console.log('New Todo inserted successfully');

     }
     else{
         console.error(error);
     }
 })</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>After that, we can run the file using command line.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>node server.js
node insert_todo.js</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Similarly, we can define the Update and Delete Service calls and use it from the gRPC client</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Complete Source Code can be found here : <a href="https://github.com/ganeshmani/grpc-node">https://github.com/ganeshmani/grpc-node</a></p>
<!-- /wp:paragraph -->