GRPC HelloWorld Service, RESTful JSON API Gateway and Swagger UI

Source: Internet
Author: User
Tags install go

Overview

This post is a complete story of what if you define and start a GRPC service through protocol buffers, and then provide a reverse proxy gateway for the RESTful JSON API on the GRPC service, and finally provide restful through the swagger UI Description of the JSON API, complete code helloworld_restful_swagger.

Helloworld Grpc Service

Refer to Grpc Quick Start for Python.

Install GRPC installation Grpc

Run the command,

$ python-m pip Install Grpcio
Installing the GRPC Toolbox

The Python grpc Toolbox includes the protol buffer compiler PROTOC and some specific plug-ins used to generate GRPC server and client code from the. Proto service definition file.

Run the command,

$ python-m pip Install Grpcio-tools
Service definition file Helloworld.proto

Create a new file Helloworld.proto in the PB directory, and then use the protocol buffers syntax to write the GRPC service definition. The contents of the file are as follows:

Syntax = "Proto3";p ackage helloworld;//The greeting service definition.service Greeter {    //sends a greeting    RPC SayHello (Hellorequest) returns (helloreply) {}}//The request message containing the user ' s name.message hellorequest {
   string name = 1;} The response message containing the Greetingsmessage helloreply {    string message = 1;}
PROTOC compiling build server and client class definitions

Use the following command to generate the server and client class definition code files for GRPC.

$ python-m grpc.tools.protoc-i.--python_out=. --grpc_python_out=. Pb/helloworld.proto

command without error, will generate two files in the PB directory helloworld_pb2.py and helloworld_pb2_grpc.py.

Where the file helloworld_pb2.py contains the message class definitions for hellorequest and Helloreploy, and the file helloworld_pb2_grpc.py provides the GRPC server class (Greeterservicer ) and the client class (greeterstub) definition.

Write a specific GRPC service class

File helloworld_pb2_grpc.py provides the GRPC server class (Greeterservicer) with a specification definition for the GRPC service, with no specific implementation. We need to write our own Grpc service class file server.py, the code is as follows,

 fromConcurrentImportFuturesImport TimeImportGrpcImportPB.HELLOWORLD_PB2 as Pb_dot_helloworld__pb2ImportPb.helloworld_pb2_grpc as Pb_dot_helloworld_pb2__grpc_one_day_in_seconds= 60 * 60 * 24classMyServer (Pb_dot_helloworld_pb2__grpc. Greeterservicer):defSayHello (Self, request, context):Print("Receive Request, Request.name: {0}". Format (request.name))returnPB_DOT_HELLOWORLD__PB2. Helloreply (Message='Hello, {0}'. Format (request.name))defserve (): Server= Grpc.server (futures. Threadpoolexecutor (max_workers=10) ) Pb_dot_helloworld_pb2__grpc.add_greeterservicer_to_server (MyServer (), server) Server.add_insecure_port ( '[::]:50051')    Print("greeterservicer start at Port 50051 ...") Server.start ()Try:         whileTrue:time.sleep (_one_day_in_seconds)exceptKeyboardInterrupt:server.stop (0)if __name__=='__main__': Serve ()

Then start GRPC Server,

$ python server.pylienhuademacbook-pro:helloworld_restful_swagger lienhua34$ python server.py GreeterServicer start at Port 50051 ...
Write Grpc client.py

File helloworld_pb2_grpc.py provides the GRPC client class (greeterstub) definition. We need to write our own client.py code to call the Grpc server method through Greeterstub. The code reads as follows:

ImportGrpcImportPB.HELLOWORLD_PB2 as Pb_dot_helloworld__pb2ImportPb.helloworld_pb2_grpc as Pb_dot_helloworld_pb2__grpcdefrun (): Channel= Grpc.insecure_channel ('localhost:50051') Stub=Pb_dot_helloworld_pb2__grpc. Greeterstub (channel) Response= Stub. SayHello (PB_DOT_HELLOWORLD__PB2. Hellorequest (name=" World"))    Print("Greeterservice Client Received:"+response.message)if __name__=='__main__': Run ()

Run the client.py code,

Lienhuademacbook-pro:helloworld_restful_swagger lienhua34$ python client.py greeterservice client Received:hello, World

At this point, we can see that our GRPC HelloWorld service is available.

RESTful JSON API Gateway

Calling the GRPC service needs to write the corresponding client code, which undoubtedly brings a certain degree of difficulty to access GRPC. We can access it directly through the RESTful JSON API by providing a RESTful API gateway on the GRPC service.

Grpc-gateway is a plug-in for Protoc that reads the GRPC service definition and then generates a reverse proxy service to convert the RESTful JSON API to a grpc call.

Install Grpc-gateway

Make sure that you have Golang 6.0 and above installed locally and added $GOPATH/bin to the $PATH. Then run the following command,

$ go get-u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway$ go get-u github.com/grpc-ecosystem/ grpc-gateway/protoc-gen-swagger$ Go get-u github.com/golang/protobuf/protoc-gen-go
Modify Helloworld.proto

Modify the file Helloworld.proto, add the Gateway option,

Syntax = "Proto3";p ackage helloworld;import "Google/api/annotations.proto"//The Greeting service Definition.service Greeter {  //sends a greeting  RPC SayHello (hellorequest) returns (helloreply) {    option (google.api.http) = { C3/>post: "/v1/hello"      Body: "*"    };}  } The request message containing the user ' s name.message hellorequest {  string name = 1;} The response message containing the Greetingsmessage helloreply {  string message = 1;}
Generate GRPC Golang stub class

Run the following command to generate the Grpc Golang stub class file,

$ python-m grpc.tools.protoc-i.        -i/usr/local/include-I        $GOPATH/src-i        $GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_ Party/googleapis        --go_out=mgoogle/api/annotations.proto=github.com/grpc-ecosystem/grpc-gateway/third_party /GOOGLEAPIS/GOOGLE/API,PLUGINS=GRPC:.        Pb/helloworld.proto 

The Helloworld.pb.go file is generated in the PB directory at this time.

Generate reverse proxy code

Run the following command to generate the reverse proxy code,

$ python-m grpc.tools.protoc-i.        -i/usr/local/include-I        $GOPATH/src-i        $GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/ Third_party/googleapis        --grpc-gateway_out=logtostderr=true:.        Pb/helloworld.proto  

If there is no error, the file Helloworld.pb.gw.go will be generated in the PB directory.

Writing entrypoint files

Write the entrypoint file proxy.go with the following content:

Package Mainimport (    "flag"    "Log" "    net/http"    "Github.com/grpc-ecosystem/grpc-gateway/runtime" "    golang.org/x/net/context" "    google.golang.org/grpc"    GW "Github.com/lienhua34/notes/grpc/helloworld _RESTFUL_SWAGGER/PB ") var (    Greeterendpoint = flag. String ("Helloworld_endpoint", "localhost:50051", "Endpoint of Greeter grpc Service")) func run () error {    CTX: = Contex T.background ()    ctx, Cancel: = context. Withcancel (CTX)    defer cancel ()    mux: = runtime. Newservemux ()    opts: = []grpc. Dialoption{grpc. Withinsecure ()}    ERR: = GW. Registergreeterhandlerfromendpoint (CTX, Mux, *greeterendpoint, opts)    if err! = Nil {        return err    }    Log. Print ("Greeter grpc Server Gateway start at port 8080 ...")    http. Listenandserve (": 8080", MUX)    return Nil}func main () {    flag. Parse ()    If err: = run (); Err! = nil {        log. Fatal (Err)    }}

Compile, generate executable file Helloworld_restful_swagger,

.
Start the service

Start the GRPC service first,

Lienhuademacbook-pro:helloworld_restful_swagger lienhua34$ python server.py greeterservicer start at Port 50051 ...

Then start the RESTful JSON API Gateway,

Lienhuademacbook-pro:helloworld_restful_swagger lienhua34$./helloworld_restful_swagger 2017/01/12 15:59:17 Greeter GRPC Server Gateway start at port 8080 ...

Access via Curl,

' {' name ': ' World '}' {' message':' Hello, World' {' name ': ' Lienhua34 '}' {' message': "Hello, Lienhua34"}         

Since then, the RESTful JSON API Gateway has been available.

Swagger description of the swagger uirestful JSON API

The swagger documentation for the RESTful JSON API can be generated using the following command.

$ python-m grpc.tools.protoc-i.        -i/usr/local/include-I        $GOPATH/src-i        $GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_ Party/googleapis        --swagger_out=logtostderr=true:.        Pb/helloworld.proto  

This command generates a Helloworld.swagger.json file in the PB directory. We directly add a file Helloworld.swagger.go in the PB directory, and then define a constant swagger in it, which is the content of Helloworld.swagger.json.

Modify the Run () method in the Proxy.go file to add an API route that returns the contents of Swagger.json.

Func run () error {    CTX: = context. Background ()    ctx, Cancel: = context. Withcancel (CTX)    defer cancel ()    mux: = http. Newservemux ()    mux. Handlefunc ("/swagger.json", func (w http). Responsewriter, req *http. Request) {        io. Copy (W, strings. Newreader (GW. Swagger)    })    Gwmux: = runtime. Newservemux ()    opts: = []grpc. Dialoption{grpc. Withinsecure ()}    ERR: = GW. Registergreeterhandlerfromendpoint (CTX, Gwmux, *greeterendpoint, opts)    if err! = Nil {        return err    }    log. Print ("Greeter grpc Server Gateway start at port 8080 ...")    http. Listenandserve (": 8080", MUX)    return nil}

Recompile and start the RESTful gateway, and then access Http://localhost:8080/swagger.json to get the swagger description of the HelloWorld restful API.

However, the Swagger.json content display is too intuitive. Swagger provides a very good visual swagger-ui. We have added swagger-ui to our gateway.

Download Swagger-ui Code

Swagger provides a visual API description. We can add Swagger-ui to the RESTful JSON API Gateway.

The dist directory of the Swagger source contains the HTML, CSS, and JS code files required for the Swagger UI, and we copy all the files under the directory to the Third_party/swagger-ui directory.

Make Swagger-ui file into go built-in file

We can use Go-bindata to make Swagger-ui's files into a go-built data file for access.

Install Go-bindata First,

$ go get-u github.com/jteeuwen/go-bindata/...

Then make all the files under Third-party/swagger-ui into the go built-in data file,

$ go-bindata--nocompress-pkg swagger-o pkg/ui/data/swagger/datafile.go third_party/swagger-ui/...

Generate File Pkg/ui/data/swagger/datafile.go,

$ ls-l pkg/ui/data/swagger/datafile.go-rw-r--r--  1 lienhua34  staff  3912436  1 22:56 pkg/ui/data/ Swagger/datafile.go
Swagger-ui File Server

After using Go-bindata to make Swagger-ui a go built-in data file, we can use Elazarl/go-bindata-assetfs to combine net/http to provide services to the Swagger-ui built-in data file.

Install ELAZARL/GO-BINDATA-ASSETFS,

$ go get github.com/elazarl/go-bindata-assetfs/...

Then modify the Proxy.go code, the final code, see Proxy.go.

Recompile, then start the Gateway service, enter Http://localhost:8080/swagger-ui in the browser,

However, the Swagger-ui opened by default is a Http://petstore.swagger.io/v2/swagger.json API description information. We need to enter the address of our API in the input box Http://localhost:8080/swagger.json, and then click Enter to see our API description,

What do we do if we want it to open by default when it's our API description? Replace Http://petstore.swagger.io/v2/swagger.json in file third_party/swagger-ui/index.html with http://localhost:8080/ Swagger.json, then regenerate the Pkg/ui/data/swagger/datafile.go file and recompile.

Reference:
    • Http://www.grpc.io/blog/coreos
    • Http://www.grpc.io/docs/quickstart/python.html
    • Https://github.com/grpc-ecosystem/grpc-gateway
    • Https://github.com/philips/grpc-gateway-example

********************************************************

Reprint please mark original source: Lienhua34 http://www.cnblogs.com/lienhua34/p/6285829.html

********************************************************

GRPC HelloWorld Service, RESTful JSON API Gateway and Swagger UI

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.