<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anderson Borges on Medium]]></title>
        <description><![CDATA[Stories by Anderson Borges on Medium]]></description>
        <link>https://medium.com/@andersonborges_70700?source=rss-9894cf3c8edb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3oZka3YDUpc6vwGU89GOHg.jpeg</url>
            <title>Stories by Anderson Borges on Medium</title>
            <link>https://medium.com/@andersonborges_70700?source=rss-9894cf3c8edb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:45:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andersonborges_70700/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[gRPC with Golang and Python]]></title>
            <link>https://medium.com/@andersonborges_70700/grpc-with-golang-and-python-f5b7aa602d74?source=rss-9894cf3c8edb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5b7aa602d74</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[buffer]]></category>
            <dc:creator><![CDATA[Anderson Borges]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 11:02:05 GMT</pubDate>
            <atom:updated>2019-03-19T11:02:05.544Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will create a small application using gRPC to create a communication between Golang and Python, but first we need understand what gRPC is.</p><p>gRPC is short for Google’s Remote Procedure Call, is an open source RPC framework used to call code that is running remotely, gRPC uses Client-server architecture which many clients request and receive service from a centralized server. In that way, clients and servers can talk to each other independently of the environments. gRPC uses HTTP/2 for transport and protocol buffers (a binary serialization format that is very small and quick to encode and decode) for serializing structured data.</p><p>First, we need to install the Protocol Buffer <a href="https://github.com/protocolbuffers/protobuf/releases">https://github.com/protocolbuffers/protobuf/releases</a></p><p>Once the Protocol Buffer is ready, we’ll need to add a plugin that will allow us to work with Go code. In a terminal, run a “go get” command:</p><pre>go get -u github.com/golang/protobuf/{proto,protoc-gen-go}<br>go get -u google.golang.org/grpc</pre><p>Our project is going to be a simple application the receive a country name and returns information about the country [Name, Capital, Population, Currencies].</p><h3>Let’s start coding</h3><p>Let’s begin creating a new folder in $GOPATH/src/ called grpc, this folder is going to be a root folder to the projects and 2 subfolders called server and client inside the grpc folder. The server directory is going to have the Golang code and client directory Python Code.</p><pre>mkdir $GOPATH/src/grpc<br>mkdir $GOPATH/src/grpc/{client,server}</pre><p>In order to create the gRPC we need to start creating a .proto file, this file is going to contain the protocol buffer data signature, I am naming as countries.proto in the root directory.</p><p>#$GOPATH/src/grpc/countries.proto</p><pre>syntax = &quot;proto3&quot;;<br>package countries;</pre><pre>service Country {<br>  rpc Search (CountryRequest) returns (CountryResponse) {}<br>}</pre><pre>message CountryRequest {<br>  string name = 1;<br>}</pre><pre>message Currencies {<br>  string code = 1;<br>  string name = 2;<br>  string symbol = 3;<br>}</pre><pre>message CountryResponse {<br>  string name = 1;<br>  string alpha2Code = 2;<br>  string capital = 3;<br>  string subregion = 4;<br>  int32  population = 5;<br>  string nativeName = 6;<br>  repeated Currencies currencies = 7;<br>}</pre><p>The important thing we specify in the .proto is that we are using the “proto3” version, for more detail just read the docs <a href="https://developers.google.com/protocol-buffers/docs/proto3">proto3</a> and <a href="https://developers.google.com/protocol-buffers/docs/proto">proto2</a>.</p><p>The service rpc block has one method “Search” that must be implemented and return the ‘CountryResponse’.</p><p>Note the Go or Python doesn’t understand proto3 code, to work with those languages you have to compile the proto file, that’s why we have installed the “protoc-gen-go”.</p><h3>Creating Go code from .proto</h3><pre>cd $GOPATH/src/grpc/<br>mkdir $GOPATH/src/grpc/server/countries<br>protoc --go_out=plugins=grpc:server/countries countries.proto</pre><p>After running the command you will see there are one file “countries.pb.go” inside server/countries folder, feel free to open the file and check its contents. A bunch of code is generated and you shouldn’t modify this code if for any reason you have to change something, you change in the .proto and then compiles again.</p><p>Keep in mind that does not matter which language is going to be the .proto is the same and each language plugin has its own output.</p><h3>Building the server</h3><pre>touch $GOPATH/src/grpc/server/main.go<br>touch $GOPATH/src/grpc/server/main_test.go</pre><p># $GOPATH/src/grpc/server/main.go</p><pre>package main</pre><pre>import (<br>  &quot;encoding/json&quot;<br>  &quot;grpc/server/countries&quot;<br>  &quot;io/ioutil&quot;<br>  &quot;log&quot;<br>  &quot;net&quot;<br>  &quot;net/http&quot;</pre><pre>  &quot;golang.org/x/net/context&quot;<br>  &quot;google.golang.org/grpc&quot;<br>)</pre><pre>func main() {</pre><pre>  grpcServer := grpc.NewServer()</pre><pre>  var server Server</pre><pre>  countries.RegisterCountryServer(grpcServer, server)</pre><pre>  listen, err := net.Listen(&quot;tcp&quot;, &quot;0.0.0.0:3000&quot;)</pre><pre>  if err != nil {<br>    log.Fatalf(&quot;could not listen to 0.0.0.0:3000 %v&quot;, err)<br>  }</pre><pre>  log.Println(&quot;Server starting...&quot;)<br>  log.Fatal(grpcServer.Serve(listen))<br>}</pre><pre><em>// Server is implementation proto interface</em><br>type Server struct{}</pre><pre><em>// Search function responsible to get the Country information</em><br>func (Server) Search(ctx context.Context, request *countries.CountryRequest) (*countries.CountryResponse, error) {</pre><pre>  resp, err := http.Get(&quot;https://restcountries.eu/rest/v2/name/ &quot; + request.Name)</pre><pre>  if err != nil {<br>    return nil, err<br>  }<br>  defer resp.Body.Close()</pre><pre>  jsonData, err := ioutil.ReadAll(resp.Body)</pre><pre>  if err != nil {<br>    return nil, err<br>  }</pre><pre>  var data []countries.CountryResponse<br>  if err := json.Unmarshal(jsonData, &amp;data); err != nil {<br>    return nil, err<br>  }<br>  return &amp;data[0], nil<br>}</pre><p>Probably you are thinking why I am using a list of CountryResponse to serializer the data, I do this because the api rest countries return a list of country not a single country.</p><p>Run the server</p><pre>go run main.go</pre><h3>Test is important</h3><p># $GOPATH/src/grpc/server/main_test.go</p><pre>package main</pre><pre>import (<br>  &quot;grpc/server/countries&quot;<br>  &quot;log&quot;<br>  &quot;testing&quot;</pre><pre>  &quot;golang.org/x/net/context&quot;<br>)</pre><pre>func TestCountry(t *testing.T) {<br>  ctx := context.Background()<br>  request := countries.CountryRequest{Name: &quot;Brazil&quot;}<br>  server := Server{}<br>  response, err := server.Search(ctx, &amp;request)<br>  if err != nil {<br>    t.Error(err)<br>  }<br>  if response.Alpha2Code != &quot;BR&quot; {<br>    t.Error(&quot;Different Country returned&quot;)<br>  }<br>  log.Println(response)<br>}</pre><p>inside the server folder run the command “go test” you should get a message like this “PASS — ok grpc/server 1.001s”</p><h3>Creating Python code from .proto</h3><p>Now that we have the gRPC server running and tested we going to create the client using Python. Imagine that you don’t have any contact with the gRPC server the only file that you have is the countries.proto, in fact, you do not know which language the server was built.</p><p>To start working with python we are going to create a virtualenv project, virtualenv is a tool to create isolated Python environments. creates a folder which contains all the necessary executables to use the packages that a Python project would need. <a href="https://gist.github.com/Geoyi/d9fab4f609e9f75941946be45000632b">Here</a> a tutorial showing how to install virtualenv.</p><p>The virtualenv project does not need to be inside the Project.</p><pre>virtualenv -p python3.6 /tmp/country</pre><p>For now, let create inside the /tmp directory. To start using the virtual environment, it needs to be activated.</p><pre>source /tmp/country/bin/activate</pre><p>As we did in Go we have to install the plugins, packages and compile the countries.proto file in Python as well.</p><pre>pip install grpcio grpcio-tools</pre><p>If you run “pip freeze” you should see something like this:</p><pre>grpcio==1.19.0<br>grpcio-tools==1.19.0<br>protobuf==3.7.0</pre><p>Creating Python code from the countries.proto:</p><pre>cd $GOPATH/src/grpc/<br>python -m grpc_tools.protoc -I. --python_out=client --grpc_python_out=client countries.proto</pre><p>The command will create 2 files in client folder “countries_pb2_grpc.py” and “countries_pb2.py”</p><p>The python client file:</p><pre>touch $GOPATH/src/grpc/client/app.py</pre><p>We can set this client to run a Python script or as a web application, how we run is not important as long as we have to connect to the gRPC server. To create a web application let’s install Flask as the web framework</p><pre>pip install Flask</pre><p>#$GOPATH/src/grpc/client/app.py</p><pre>from flask import Flask<br>from flask import jsonify</pre><pre>app = Flask(__name__)</pre><pre>import grpc<br>import countries_pb2<br>import countries_pb2_grpc</pre><pre>def obj_to_dict(obj):return obj.__dict__</pre><pre>@app.route(&#39;/&lt;countrie&gt;&#39;)<br>def countrie(countrie):<br>    print(&quot;Start service&quot;)<br>    try:<br>      channel = grpc.insecure_channel(&#39;localhost:3000&#39;)<br>      stub = countries_pb2_grpc.CountryStub(channel)<br>      countryRequest = countries_pb2.CountryRequest(name=countrie)<br>      countryResponse = stub.search(countryRequest)</pre><pre>      return jsonify({<br>          &quot;name&quot;: countryResponse.name,<br>          &quot;alpha2Code&quot;: countryResponse.alpha2Code,<br>          &quot;capital&quot;: countryResponse.capital,<br>          &quot;subregion&quot;: countryResponse.subregion,<br>          &quot;population&quot;: countryResponse.population,<br>          &quot;nativeName&quot;: countryResponse.nativeName<br>      })<br>    except Exception as e:<br>      print(e)<br>      return e</pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run()</pre><p>Running the client, don’t forget to start the gRPC server first.</p><pre>python app.py</pre><pre>curl <a href="http://localhost:5000/brazil">http://localhost:5000/brazil</a><br>More country names to test:</pre><pre>germany<br>afghanistan<br>albania<br>colombia</pre><p>We covered a few things and we put together a simple example of gRPC, we learned how gRPC give us efficient transport communications between clients and servers regardless of the language used.</p><pre>├── client<br>│   ├── app.py<br>│   ├── countries_pb2_grpc.py<br>│   ├── countries_pb2.py<br>├── countries.proto<br>└── server<br>    ├── countries<br>    │   └── countries.pb.go<br>    ├── main.go<br>    └── main_test.go</pre><h3>Source Code</h3><p><a href="https://bitbucket.org/burdzand/grpc">https://bitbucket.org/burdzand/grpc</a></p><h3>Links</h3><ul><li><a href="https://grpc.io/docs/">https://grpc.io/docs/</a></li><li><a href="https://developers.google.com/protocol-buffers/">https://developers.google.com/protocol-buffers/</a></li><li><a href="https://github.com/grpc/grpc">https://github.com/grpc/grpc</a></li><li><a href="https://github.com/golang/protobuf">https://github.com/golang/protobuf</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5b7aa602d74" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>