Github url

grpc-gateway

by grpc-ecosystem

grpc-ecosystem /grpc-gateway

gRPC to JSON proxy generator following the gRPC HTTP spec

8.8K Stars 1.2K Forks Last release: about 2 months ago (v1.14.6) BSD 3-Clause "New" or "Revised" License 977 Commits 56 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:

grpc-gateway

release CircleCI fuzzit coverage license

The grpc-gateway is a plugin of the Google protocol buffers compilerprotoc. It reads protobuf service definitions and generates a reverse-proxy server which translates a RESTful HTTP API into gRPC. This server is generated according to the[

google.api.http

](https://github.com/googleapis/googleapis/blob/master/google/api/http.proto#L46)annotations in your service definitions.

This helps you provide your APIs in both gRPC and RESTful style at the same time.

architecture introduction diagram

Testimonials

We use the gRPC-Gateway to serve millions of API requests per day, and have been since 2018, and through all of that, we have never had any issues with it.

- William Mill, Ad Hoc

Check out our documentation!

Background

gRPC is great -- it generates API clients and server stubs in many programming languages, it is fast, easy-to-use, bandwidth-efficient and its design is combat-proven by Google. However, you might still want to provide a traditional RESTful JSON API as well. Reasons can range from maintaining backward-compatibility, supporting languages or clients that are not well supported by gRPC, to simply maintaining the aesthetics and tooling involved with a RESTful JSON architecture.

This project aims to provide that HTTP+JSON interface to your gRPC service. A small amount of configuration in your service to attach HTTP semantics is all that's needed to generate a reverse-proxy with this library.

Installation

The grpc-gateway requires a local installation of the Google protocol buffers compiler

protoc

v3.0.0 or above. Please install this via your local package manager or by downloading one of the releases from the official repository:

https://github.com/protocolbuffers/protobuf/releases

The following instructions assume you are usingGo Modules for dependency management. Use atool dependencyto track the versions of the following executable packages:

// +build tools package tools import ( \_ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway" \_ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger" \_ "github.com/golang/protobuf/protoc-gen-go" )

Run

go mod tidy

to resolve the versions. Install by running

$ go install \ github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway \ github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger \ github.com/golang/protobuf/protoc-gen-go

This will place three binaries in your

$GOBIN

;

protoc-gen-grpc-gateway
  • protoc-gen-swagger
  • protoc-gen-go

Make sure that your

$GOBIN

is in your

$PATH

.

Usage

  1. Define your gRPC service using protocol buffers
your\_service.proto

: ```protobuf syntax = "proto3"; package example; message StringMessage { string value = 1; }

service YourService { rpc Echo(StringMessage) returns (StringMessage) {} } ```

  1. Add a [
    google.api.http
    ](https://github.com/googleapis/googleapis/blob/master/google/api/http.proto#L46)annotation to your .proto file
your\_service.proto

: ```diff syntax = "proto3"; package example; + +import "google/api/annotations.proto"; + message StringMessage { string value = 1; }

service YourService {
  • rpc Echo(StringMessage) returns (StringMessage) {}
  • rpc Echo(StringMessage) returns (StringMessage) {
  • option (google.api.http) = {
  • post: "/v1/example/echo"
  • body: "*"
  • };
  • } } ```

You will need to provide the required third party protobuf files to the

protoc

compiler. They are included in this repo under the

third\_party/googleapis

folder, and we recommend copying them into your

protoc

generation file structure. If you've structured your proto files according to something like the Buf style guide, you could copy the files into a top-level

./google

folder.

See a_bit_of_everything.proto for examples of more annotations you can add to customize gateway behavior and generated Swagger output.

If you do not want to modify the proto file for use with grpc-gateway you can alternatively use an external gRPC Service Configuration file. Check our documentation for more information.

  1. Generate gRPC stub

Here is an example of what a

protoc

command might look like:

protoc -I. --go\_out=plugins=grpc,paths=source\_relative:./gen/go/ your/service/v1/your\_service.proto

It will generate a stub file with path

./gen/go/your/service/v1/your\_service.pb.go

.

  1. Implement your service in gRPC as usual

    1. (Optional) Generate gRPC stub in the other programming languages.

For example, the following generates gRPC code for Ruby based on

your/service/v1/your\_service.proto

: ```sh protoc -I. --ruby_out=./gen/ruby your/service/v1/your_service.proto

protoc -I. --grpc-ruby_out=./gen/ruby your/service/v1/your_service.proto ``` 2. Add the googleapis-common-protos gem (or your language equivalent) as a dependency to your project. 3. Implement your gRPC service stubs

  1. Generate reverse-proxy using

protoc-gen-grpc-gateway
protoc -I. --grpc-gateway\_out=logtostderr=true,paths=source\_relative:./gen/go \ your/service/v1/your\_service.proto

It will generate a reverse proxy

gen/go/your/service/v1/your\_service.pb.gw.go

.

  1. Write an entrypoint for the HTTP reverse-proxy server
package main import ( "context" "flag" "net/http" "github.com/golang/glog" "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc" gw "github.com/yourorg/yourrepo/proto/gen/go/your/service/v1/your\_service" // Update ) var ( // command-line options: // gRPC server endpoint grpcServerEndpoint = flag.String("grpc-server-endpoint", "localhost:9090", "gRPC server endpoint") ) func run() error { ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() // Register gRPC server endpoint // Note: Make sure the gRPC server is running properly and accessible mux := runtime.NewServeMux() opts := []grpc.DialOption{grpc.WithInsecure()} err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, \*grpcServerEndpoint, opts) if err != nil { return err } // Start HTTP server (and proxy calls to gRPC server endpoint) return http.ListenAndServe(":8081", mux) } func main() { flag.Parse() defer glog.Flush() if err := run(); err != nil { glog.Fatal(err) } }
  1. (Optional) Generate swagger definitions using
    protoc-gen-swagger
protoc -I. --swagger\_out=logtostderr=true:./gen/swagger your/service/v1/your\_service.proto

Video intro

This GopherCon UK 2019 presentation from our maintainer@JohanBrandhorst provides a good intro to using the grpc-gateway. It uses the following boilerplate repo as a base: https://github.com/johanbrandhorst/grpc-gateway-boilerplate.

gRPC-Gateway presentation

Parameters and flags

During code generation with

protoc

, flags to grpc-gateway tools must be passed through protoc using the

--<tool_suffix>_out=<flags>:<path></path></flags></tool_suffix>

pattern, for example:

--grpc-gateway\_out=logtostderr=true,repeated\_path\_param\_separator=ssv:. --swagger\_out=logtostderr=true,repeated\_path\_param\_separator=ssv:.
protoc-gen-grpc-gateway

supports custom mapping from Protobuf

import

to Golang import paths. They are compatible with[the parameters with the same names in

protoc-gen-go

](https://github.com/golang/protobuf#parameters).

In addition we also support the

request\_context

parameter in order to use the

http.Request

's Context (only for Go 1.7 and above). This parameter can be useful to pass the request-scoped context between the gateway and the gRPC service.

protoc-gen-grpc-gateway

also supports some more command line flags to control logging. You can give these flags together with parameters above. Run

protoc-gen-grpc-gateway --help

for more details about the flags.

Similarly,

protoc-gen-swagger

supports command-line flags to control Swagger output (for example,

json\_names\_for\_fields

to output JSON names for fields instead of protobuf names). Run

protoc-gen-swagger --help

for more flag details. Further Swagger customization is possible by annotating your

.proto

files with options fromopenapiv2.proto - seea_bit_of_everything.protofor examples.

More Examples

More examples are available under

examples

directory. *

proto/examplepb/echo\_service.proto

,

proto/examplepb/a\_bit\_of\_everything.proto

,

proto/examplepb/unannotated\_echo\_service.proto

: service definition *

proto/examplepb/echo\_service.pb.go

,

proto/examplepb/a\_bit\_of\_everything.pb.go

,

proto/examplepb/unannotated\_echo\_service.pb.go

: [generated] stub of the service *

proto/examplepb/echo\_service.pb.gw.go

,

proto/examplepb/a\_bit\_of\_everything.pb.gw.go

,

proto/examplepb/uannotated\_echo\_service.pb.gw.go

: [generated] reverse proxy for the service *

proto/examplepb/unannotated\_echo\_service.yaml

: gRPC API Configuration for

unannotated\_echo\_service.proto

*

server/main.go

: service implementation *

main.go

: entrypoint of the generated reverse proxy

To use the same port for custom HTTP handlers (e.g. serving

swagger.json

), gRPC-gateway, and a gRPC server, seethis example by CoreOS(and its accompanying blog post).

Features

Supported

  • Generating JSON API handlers.
  • Method parameters in the request body.
  • Method parameters in the request path.
  • Method parameters in query string.
  • Enum fields in the path parameter (including repeated enum fields).
  • Mapping streaming APIs to newline-delimited JSON streams.
  • Mapping HTTP headers with
    Grpc-Metadata-
    prefix to gRPC metadata (prefixed with
    grpcgateway-
    )
  • Optionally emitting API definitions forOpenAPI (Swagger) v2.
  • Setting gRPC timeoutsthrough inbound HTTP
    Grpc-Timeout
    header.
  • Partial support for gRPC API Configurationfiles as an alternative to annotation.
  • Automatically translating PATCH requests into Field Mask gRPC requests. Seethe docsfor more information.

No plan to support

But patch is welcome. * Method parameters in HTTP headers. * Handling trailer metadata. * Encoding request/response body in XML. * True bi-directional streaming.

Mapping gRPC to HTTP

  • How gRPC error codes map to HTTP status codes in the response.
  • HTTP request source IP is added as
    X-Forwarded-For
    gRPC request header.
  • HTTP request host is added as
    X-Forwarded-Host
    gRPC request header.
  • HTTP
    Authorization
    header is added as
    authorization
    gRPC request header.
  • Remaining Permanent HTTP header keys (as specified by the IANAhereare prefixed with
    grpcgateway-
    and added with their values to gRPC request header.
  • HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata (prefixed with
    grpcgateway-
    ).
  • While configurable, the default {un,}marshaling usesjsonpb with
    OrigName: true
    .

Contribution

See CONTRIBUTING.md.

License

grpc-gateway is licensed under the BSD 3-Clause License. See LICENSE.txt for more details.

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.