Microservices, gRPC and Protocol Buffers — Hello World

From REST to gRPC

About gRPC?

gRPC Architecture diagram, link

Building APIs with gRPC

  • Client: responsible for making the gRPC call to the server.
  • Server: responsible for serving the client requests.
  • Proto file: Proto file comprises the declaration of the service that is used to generate stubs (<package_name>_pb2.py and <package_name>_pb2_grpc.py). It can be understood as a step. We actually don’t need to define it when we are working with HTTP APIs (we use JSON and we forget the rest)
syntax = "proto3";

package grpctest;

service Grpctest{
// A simple RPC.
//
// Obtains the MessageResponse at a given position.
rpc GetServerResponse(Message) returns (MessageResponse) {}

}

message Message{
string message = 1;
}

message MessageResponse{
string message = 1;
bool received = 2;
}
$ pip3 install grpcio grpcio-tools (for installing gRPC stuff)$ python3 -m grpc_tools.protoc --proto_path=. ./grpctest.proto --python_out=. --grpc_python_out=.

Writing Client and Server

import grpc
from concurrent import futures
import time
import grpctest.grpctest_pb2_grpc as pb2_grpc
import grpctest.grpctest_pb2 as pb2


class GrpctestService(pb2_grpc.GrpctestServicer):

def __init__(self, *args, **kwargs):
pass

def GetServerResponse(self, request, context):

# get the string from the incoming request
message = request.message
result = f'Hello I am up and running received "{message}" message from you'
result = {'message': result, 'received': True}

return pb2.MessageResponse(**result)


def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
pb2_grpc.add_GrpctestServicer_to_server(GrpctestService(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()


if __name__ == '__main__':
serve()
import grpc
import grpctest.grpctest_pb2_grpc as pb2_grpc
import grpctest.grpctest_pb2 as pb2


class grpctestClient(object):
"""
Client for gRPC functionality
"""

def __init__(self):
self.host = 'localhost'
self.server_port = 50051

# instantiate a channel
self.channel = grpc.insecure_channel(
'{}:{}'.format(self.host, self.server_port))

# bind the client and the server
self.stub = pb2_grpc.GrpctestStub(self.channel)

def get_url(self, message):
"""
Client function to call the rpc for GetServerResponse
"""
message = pb2.Message(message=message)
print(f'{message}')
return self.stub.GetServerResponse(message)


if __name__ == '__main__':
client = grpctestClient()
result = client.get_url(message="Hello Server you there?")
print(f'{result}')

Execution of the Server and Client

$ python3 grpctest_server.py$ python3 grpctest_client.py
Running the gRPC server
Running the gRPC client

In a Nutshell

What’s Next

--

--

--

Python, DevOps, Cryptography, Infra-Structure Automation. https://syedsaadahmed.com/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

PyBlog — Profile

Secure Forms Authentication cookie in server farm

The Forms Authentication Workflow

Best free online courses for C++

Cloning BigBasket.com: Replica of Online Supermarket.

Flywheel Shooter Software for FRC

Starting With Common Lisp

First approach with QEMU/KVM — Virtualization on Linux

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Syed Saad Ahmed

Syed Saad Ahmed

Python, DevOps, Cryptography, Infra-Structure Automation. https://syedsaadahmed.com/

More from Medium

Understanding Golang “Concurrency” using Arduino UNO.

Golang JSON Key or Value Transform Library

In conversation with Google’s gRPC | Part1

Cluster nodes in Golang using Hashicorp Memberlist