gRPC

From XennisWiki
Jump to: navigation, search

gRPC 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. It generates cross-platform client and server bindings for many languages. (Wikipedia)

Installation and setup

Install Protocol Buffers compiler

Arch Linux

Install the protobuf package.

Manual download

  • Download protoc compiler (protoc-<version>-<platform>.zip) and extract the file
  • Add it to the PATH
export PATH=${PATH}:~/path/to/protoc/bin

Go setup

Further information: gRPC - Go Quick Start

Install gRPC and the protoc plugin for GO

go get -u google.golang.org/grpc
go get -u github.com/golang/protobuf/protoc-gen-go

Python setup

Further information: gRPC - Python Quick Start

Install gRPC and gRPC tools

pip install grpcio grpcio-tools

Run Hello World examples

Go

Change to the hello world example

cd $GOPATH/src/google.golang.org/grpc/examples/helloworld

Run the server

go run greeter_server/main.go

Run the client from a different terminal and you should receive a hello world message.

go run greeter_client/main.go

Python

Download the example and change to the hello world example

git clone https://github.com/grpc/grpc
cd grpc/examples/python/helloworld

Run the server

python greeter_server.py

Run the client from a different terminal and you should receive a hello world message.

python greeter_client.py

Generate descriptor and code

Go

Compile protocol buffers and generate Go API (--go_out)

protoc \
	--include_imports \
	--include_source_info \
	--proto_path=. \
	--descriptor_set_out=api_descriptor.pb \
	--go_out=plugins=grpc:. \
	my_api.proto

Python

Generate Python files

python -m grpc_tools.protoc \
	--proto_path . \
	--python_out=. \
	--grpc_python_out=. \
	my_api.proto

Generate protocol buffer file

python -m grpc_tools.protoc \
	--include_imports \
	--include_source_info \
	--proto_path . \
	--descriptor_set_out out.pb \
	my_api.proto

Example proto file

telegram_bot_api.proto

syntax = "proto3";

package telegrambotapi;

import "google/protobuf/empty.proto";

service TelegramBotApi {
    rpc ReceiveUpdates (Update) returns (google.protobuf.Empty) {}
}

message Updates {
    bool ok = 1;
    repeated Update result = 2;
}

message Update {
    int32 update_id = 1;
    Message message = 2;
}

message Message {
    int32 message_id = 1;
    User from = 2;
    Chat chat = 3;
    int32 date = 4;
    string text = 5;
}

message User {
    int32 id = 1;
    bool is_bot = 2;
    string first_name = 3;
    string last_name = 4;
    string username = 5;
}

message Chat {
    int32 id = 1;
    string first_name = 2;
    string type = 3;
}

Tips

Transcode HTTP/JSON to gRPC

see Google Cloud Endpoints

See also

External links