Building API with gRPC using ProtoBuf – Part 3

Reading Time: 3 minutes

In the previous blog, we discussed the Protocol buffers. How do they work? How to define the protobuf and compile it? Whats happens when we compile our protobuf file? How Protocol buffers were designed to solve many problems? Also how to generate Java or Scala code? In order to continue our series, we will try to create a small basic application with simple client requests and servers response.

In order to build the client or server-side API, we need to follow some steps:

Step 1: Let’s Define the protobuf for our small application.

In first line you have to define the proto syntax i.e proto2 or proto3

syntax = "proto3";

In the next line you should define the package structure i.e when you compile the proto file the code will generate in the given package structure:

package knoldus.protos;

Now you can define your proto messages part like below:

message HelloRequest {
string name = 1;
HelloLastName last = 2;
}

Here is the complete proto file:

Screenshot-from-2020-06-16-09-34-51

Step 2: Now simply compile you code.

It will generate all code that will help you to the client or severe side code. You can write both synchronous and asynchronous code using.

Screenshot-from-2020-06-19-14-49-35

When you compiled the protobuf, classes under hello package will generate.

Step 3: Define the Client side code in Scala.

Create the HelloWorldClient class as shown below:

Screenshot-from-2020-06-19-14-23-28

In the above code the blockingStub.sayHello is a server side method that will give the response according to our request.

Now create the companion object for the HelloWorldClient:

Screenshot-from-2020-06-19-14-25-17

Now run the main method after server is running, you will see the following output:

Screenshot-from-2020-06-19-16-57-45
It will greet Shiv

Step 4: Now let’s see how can we define the Server-side code:

So here is the example for server side code: HelloWorldServer Class

Screenshot-from-2020-06-19-14-38-42
In this example we bind our service with port 50051. And also define our sayHello method

Lets also define the campanion object for HelloWorldServer like HelloWorldClient:

Screenshot-from-2020-06-19-14-42-32

Now run the main method:

Screenshot-from-2020-06-19-14-55-56
Your server is start now.

Now if you run above code on your machine you able to run your little client and server-side API by simply running the main method of both classes.

Summary

In this blog, we are able to create small and simple API. What is the directory structure of the API? We also saw the response of the server.

References:
* gRPC documentation.
* scalaPB example


Knoldus-blog-footer-image