grpc-gateway README

The project's README from github.com/grpc-ecosystem/grpc-gateway. As one markdown file: README.md.

gRPC-Gateway

gRPC to JSON proxy generator following the gRPC HTTP spec

About

The gRPC-Gateway is a plugin of the Google protocol buffers compiler protoc. 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 annotations in your service definitions.

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

Docs

You can read our docs at:

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

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

Compile from source

The following instructions assume you are using Go Modules for dependency management. Use a tool dependency to track the versions of the following executable packages:

For Go 1.24 and later, prefer the tool directive in go.mod described in the "Tracking Tools in go.mod" section. The following blank-import pattern is mainly useful for projects that are not using Go 1.24 yet.

// +build tools

package tools

import (
    _ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway"
    _ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2"
    _ "google.golang.org/grpc/cmd/protoc-gen-go-grpc"
    _ "google.golang.org/protobuf/cmd/protoc-gen-go"
)

Run go mod tidy to resolve the versions. Install by running

go install \
    github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway \
    github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2 \
    google.golang.org/protobuf/cmd/protoc-gen-go \
    google.golang.org/grpc/cmd/protoc-gen-go-grpc

This will place four binaries in your $GOBIN;

Make sure that your $GOBIN is in your $PATH.

If you want to emit OpenAPI 3.1 instead of (or in addition to) Swagger 2.0, install protoc-gen-openapiv3 as well:

go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv3

⚠️ Alpha. protoc-gen-openapiv3 is new and its output is not yet stable — the emitted JSON shape for oneofs, wrappers, enums, and similar constructs may change in response to real-world feedback before the plugin graduates. Don't rely on the exact spec bytes being stable across minor releases; the proto-to-OpenAPI mapping rules are likely to tighten, and tooling-compatibility compromises (documented in the generator source) may be revisited as consumer OpenAPI 3.1 support matures. protoc-gen-openapiv2 is the production-stable option.

See OpenAPI 3.1 Output for what it supports and how it differs from protoc-gen-openapiv2.

Using the tool Directive in Go 1.24

Starting from Go 1.24, the tool directive in go.mod provides a structured way to track and manage executable dependencies. This replaces the previous workaround of using a separate tools.go file with blank imports.

Tracking Tools in go.mod

Instead of manually importing tool dependencies in a Go source file, you can now use the tool directive in go.mod to declare the tools your project depends on. For example:

module tools

go 1.24

tool (
	github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway
	github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2
	google.golang.org/grpc/cmd/protoc-gen-go-grpc
	google.golang.org/protobuf/cmd/protoc-gen-go
)

Managing Tool Dependencies

To add tools to your module, use the -tool flag with go get:

go get -tool github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway
go get -tool github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2
go get -tool google.golang.org/protobuf/cmd/protoc-gen-go
go get -tool google.golang.org/grpc/cmd/protoc-gen-go-grpc

This automatically updates go.mod, adding the tools under the tool directive along with require statements to ensure version tracking.

Install Tools

Once the tool dependencies are properly recorded in the go.mod file, simply execute the following command in the root directory of your project:

go install tool

This will place four binaries in your $GOBIN;

Make sure that your $GOBIN is in your $PATH.

Download the binaries

You may alternatively download the binaries from the GitHub releases page. We generate SLSA3 signatures using the OpenSSF's slsa-framework/slsa-github-generator during the release process. To verify a release binary:

  1. Install the verification tool from slsa-framework/slsa-verifier#installation.
  2. Download the provenance file attestation.intoto.jsonl from the GitHub releases page.
  3. Run the verifier:
slsa-verifier -artifact-path <the-binary> -provenance attestation.intoto.jsonl -source github.com/grpc-ecosystem/grpc-gateway -tag <the-tag>

Alternatively, see the section on remotely managed plugin versions below.

Usage

1.Define your gRPC service using protocol buffers

your_service.proto:

 syntax = "proto3";
 package your.service.v1;
 option go_package = "github.com/yourorg/yourprotos/gen/go/your/service/v1";

 message StringMessage {
   string value = 1;
 }

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

2. Generate gRPC stubs

This step generates the gRPC stubs that you can use to implement the service and consume from clients:

Here's an example buf.gen.yaml you can use to generate the stubs with buf:

version: v2
plugins:
  - local: protoc-gen-go
    out: gen/go
    opt:
      - paths=source_relative
  - local: protoc-gen-go-grpc
    out: gen/go
    opt:
      - paths=source_relative

With this file in place, you can generate your files using buf generate.

For a complete example of using buf generate to generate protobuf stubs, see the boilerplate repo. For more information on generating the stubs with buf, see the official documentation.

If you are using protoc to generate stubs, here's an example of what a command might look like:

protoc -I . \
    --go_out ./gen/go/ --go_opt paths=source_relative \
    --go-grpc_out ./gen/go/ --go-grpc_opt paths=source_relative \
    your/service/v1/your_service.proto

3. Implement your service in gRPC as usual.

4. Generate reverse-proxy using protoc-gen-grpc-gateway

At this point, you have 3 options:

1. Using the default mapping

This requires no additional modification to the .proto file but does require enabling a specific option when executing the plugin. The generate_unbound_methods should be enabled.

Here's what a buf.gen.yaml file might look like with this option enabled:

version: v2
plugins:
  - local: protoc-gen-go
    out: gen/go
    opt:
      - paths=source_relative
  - local: protoc-gen-go-grpc
    out: gen/go
    opt:
      - paths=source_relative
  - local: protoc-gen-grpc-gateway
    out: gen/go
    opt:
      - paths=source_relative
      - generate_unbound_methods=true

With protoc (just the grpc-gateway stubs):

protoc -I . --grpc-gateway_out ./gen/go \
    --grpc-gateway_opt paths=source_relative \
    --grpc-gateway_opt generate_unbound_methods=true \
    your/service/v1/your_service.proto

2. With custom annotations

Add a google.api.http annotation to your .proto file

your_service.proto:

 syntax = "proto3";
 package your.service.v1;
 option go_package = "github.com/yourorg/yourprotos/gen/go/your/service/v1";
+
+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 protobuf compiler. If you are using buf, this dependency can be added to the deps array in your buf.yaml under the name buf.build/googleapis/googleapis:

version: v2
name: buf.build/yourorg/myprotos
deps:
  - buf.build/googleapis/googleapis

Always run buf dep update after adding a dependency to your buf.yaml.

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

Here's what a buf.gen.yaml file might look like:

version: v2
plugins:
  - local: protoc-gen-go
    out: gen/go
    opt:
      - paths=source_relative
  - local: protoc-gen-go-grpc
    out: gen/go
    opt:
      - paths=source_relative
  - local: protoc-gen-grpc-gateway
    out: gen/go
    opt:
      - paths=source_relative

If you are using protoc to generate stubs, you need to ensure the required dependencies are available to the compiler at compile time. These can be found by manually cloning and copying the relevant files from the googleapis repository, and providing them to protoc when running. The files you will need are:

google/api/annotations.proto
google/api/field_behavior.proto
google/api/http.proto
google/api/httpbody.proto

Here's what a protoc execution might look like:

protoc -I . --grpc-gateway_out ./gen/go \
    --grpc-gateway_opt paths=source_relative \
    your/service/v1/your_service.proto

3. External configuration

If you do not want to (or cannot) 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. This is best combined with the standalone=true option to generate a file that can live in its own package, separate from the files generated by the source protobuf file.

Here's what a buf.gen.yaml file might look like with this option enabled:

version: v2
plugins:
  - local: protoc-gen-go
    out: gen/go
    opt:
      - paths=source_relative
  - local: protoc-gen-go-grpc
    out: gen/go
    opt:
      - paths=source_relative
  - local: protoc-gen-grpc-gateway
    out: gen/go
    opt:
      - paths=source_relative
      - grpc_api_configuration=path/to/config.yaml
      - standalone=true

With protoc (just the grpc-gateway stubs):

protoc -I . --grpc-gateway_out ./gen/go \
    --grpc-gateway_opt paths=source_relative \
    --grpc-gateway_opt grpc_api_configuration=path/to/config.yaml \
    --grpc-gateway_opt standalone=true \
    your/service/v1/your_service.proto

5. Write an entrypoint for the HTTP reverse-proxy server

package main

import (
  "context"
  "flag"
  "net/http"

  "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
  "google.golang.org/grpc"
  "google.golang.org/grpc/credentials/insecure"
  "google.golang.org/grpc/grpclog"

  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.WithTransportCredentials(insecure.NewCredentials())}
  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()

  if err := run(); err != nil {
    grpclog.Fatal(err)
  }
}

6. (Optional) Generate OpenAPI definitions using protoc-gen-openapiv2

Here's what a buf.gen.yaml file might look like:

version: v2
plugins:
  - local: protoc-gen-go
    out: gen/go
    opt:
      - paths=source_relative
  - local: protoc-gen-go-grpc
    out: gen/go
    opt:
      - paths=source_relative
  - local: protoc-gen-grpc-gateway
    out: gen/go
    opt:
      - paths=source_relative
      - generate_unbound_methods=true
  - local: protoc-gen-openapiv2
    out: gen/go

To use the custom protobuf annotations supported by protoc-gen-openapiv2, we need another dependency added to our protobuf generation step. If you are using buf, you can add the buf.build/grpc-ecosystem/grpc-gateway dependency to your deps array:

version: v2
name: buf.build/yourorg/myprotos
deps:
  - buf.build/googleapis/googleapis
  - buf.build/grpc-ecosystem/grpc-gateway

With protoc (just the swagger file):

protoc -I . --openapiv2_out ./gen/openapiv2 \
    your/service/v1/your_service.proto

If you are using protoc to generate stubs, you will need to copy the protobuf files from the protoc-gen-openapiv2/options directory of this repository, and providing them to protoc when running.

Note that this plugin also supports generating OpenAPI definitions for unannotated methods; use the generate_unbound_methods option to enable this.

It is possible with the HTTP mapping for a gRPC service method to create duplicate mappings with the only difference being constraints on the path parameter.

/v1/{name=projects/*} and /v1/{name=organizations/*} both become /v1/{name}. When this occurs the plugin will rename the path parameter with a "_1" (or "_2" etc) suffix to differentiate the different operations. So in the above example, the 2nd path would become /v1/{name_1=organizations/*}. This can also cause OpenAPI clients to URL encode the "/" that is part of the path parameter as that is what OpenAPI defines in the specification. To allow gRPC gateway to accept the URL encoded slash and still route the request, use the UnescapingModeAllCharacters or UnescapingModeLegacy (which is the default currently though may change in future versions). See Customizing Your Gateway for more information.

Alternative: OpenAPI 3.1 with protoc-gen-openapiv3

⚠️ Alpha. protoc-gen-openapiv3 is new and its output is not yet stable. Expect breaking changes to the emitted JSON shape (oneof encodings, wrapper types, enum form, path-template expansion, etc.) between minor releases while the mapping rules settle in response to real-world feedback. Use it if you want to follow that evolution; otherwise protoc-gen-openapiv2 remains the stable choice.

protoc-gen-openapiv3 is a separate generator that emits OpenAPI 3.1.0 JSON directly from google.api.http annotations. It's a good choice when your downstream tooling requires 3.1, when you want the richer JSON Schema 2020-12 constructs (proper oneOf encoding for proto oneofs, spec-accurate literal expansion of constrained path templates like {name=shelves/*/books/*}, etc.).

Add it to your buf.gen.yaml alongside (or instead of) protoc-gen-openapiv2:

version: v2
plugins:
  - local: protoc-gen-openapiv3
    out: gen/openapiv3

Or invoke it directly with protoc:

protoc -I. --openapiv3_out=./gen/openapiv3 your/service/v1/your_service.proto

A .openapi.json file appears next to each proto file that declares HTTP bindings; files with no HTTP-bound services produce no output. See OpenAPI 3.1 Output for more information about the capabilities of protoc-gen-openapiv3.

Usage with remote plugins

As an alternative to all of the above, you can use buf with remote plugins to manage plugin versions and generation. An example buf.gen.yaml using remote plugin generation looks like this:

version: v2
plugins:
  - remote: buf.build/protocolbuffers/go:v1.31.0
    out: gen/go
    opt:
      - paths=source_relative
  - remote: buf.build/grpc/go:v1.3.0
    out: gen/go
    opt:
      - paths=source_relative
  - remote: buf.build/grpc-ecosystem/gateway:v2.16.2
    out: gen/go
    opt:
      - paths=source_relative
  - remote: buf.build/grpc-ecosystem/openapiv2:v2.16.2
    out: gen/openapiv2

This requires no local installation of any plugins. Be careful to use the same version of the generator as the runtime library, i.e. if using v2.16.2, run

$ go get github.com/grpc-ecosystem/grpc-gateway/[email protected]

To get the same version of the runtime in your go.mod.

Note that usage of remote plugins is incompatible with usage of external configuration files like grpc_api_configuration.

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.

Parameters and flags

When using buf to generate stubs, flags and parameters are passed through the opt field in your buf.gen.yaml file, for example:

version: v2
plugins:
  - local: protoc-gen-grpc-gateway
    out: gen/go
    opt:
      - paths=source_relative
      - grpc_api_configuration=path/to/config.yaml
      - standalone=true

During code generation with protoc, flags to gRPC-Gateway tools must be passed through protoc using one of 2 patterns:

--grpc-gateway_out=repeated_path_param_separator=ssv:.
--openapiv2_out=repeated_path_param_separator=ssv:.
--grpc-gateway_opt repeated_path_param_separator=ssv
--openapiv2_opt repeated_path_param_separator=ssv

More examples

More examples are available under the examples directory.

To use the same port for custom HTTP handlers (e.g. serving swagger.json), gRPC-Gateway, and a gRPC server, see this example by CoreOS (and its accompanying blog post).

This example by neiro.ai (and its accompanying blog post) shows how mediafiles using multipart/form-data can be integrated into rpc messages using a middleware.

Features

Supported

No plan to support

But patches are welcome.

Mapping gRPC to HTTP

Contribution

See CONTRIBUTING.md.

License

gRPC-Gateway is licensed under the BSD 3-Clause License. See LICENSE for more details.

grpc-gateway (grpc-ecosystem/grpc-gateway)

Searching Database…

这是什么?gRPC-Gateway 是一个 protoc 插件,它会读取你的 protobuf 服务定义,生成一个反向代理服务器,把 RESTful HTTP API 转换成 gRPC,这样一个服务就能同时为 gRPC 客户端和 RESTful JSON 客户端提供服务。
那它是我要导入的库,还是构建时要运行的工具?两者都是:protoc-gen-grpc-gateway 是构建时运行的代码生成插件,而生成的代理还要链接一个 Go 运行时库,这个库的版本必须和生成器版本一致。
我怎么把它跑起来?先安装插件,让四个二进制文件(protoc-gen-grpc-gateway、protoc-gen-openapiv2、protoc-gen-go、protoc-gen-go-grpc)装到 $GOBIN,然后用 protoc 或 buf 从你带注解的 .proto 文件生成网关代码,最后写一个小的入口程序来启动这个代理。
在它能用之前,我需要装好哪些东西?需要一个 Go 工具链来编译插件,再加上 protoc 或 buf 来驱动代码生成;如果用 buf 远程插件,本地什么都不用装。
有没有哪些地方比较粗糙或不稳定?较新的 OpenAPI 3.1 生成器 protoc-gen-openapiv3 还处于 alpha 阶段,它的输出结构在各个小版本之间可能还会变化;另外 buf 远程插件与外部配置文件不兼容。protoc-gen-openapiv2 才是稳定的选择。
我是不是得给所有的 proto 文件都加上 HTTP 注解?不用——有三种方式:通过 generateunboundmethods 选项启用默认映射(对任何 .proto 文件都有效),为自定义路径添加 google.api.http 注解,或者干脆不动 proto 文件,改用外部配置文件来配置映射。
它还能生成 OpenAPI 文档吗?可以——protoc-gen-openapiv2 会根据你的注解生成 Swagger 2.0,甚至连没加注解的方法也能覆盖;而独立的 protoc-gen-openapiv3 会生成 OpenAPI 3.1 JSON,支持更丰富的 JSON Schema 2020-12 结构(仍是 alpha 阶段)。
为什么要在 gRPC 旁边同时提供 REST?README 里提到的理由包括:向后兼容、支持 gRPC 支持不佳的语言或客户端,以及保留 RESTful JSON 架构的工具链和风格——网关在不重写服务的情况下,给它加上了 HTTP+JSON 这一面。
它在生产环境里经受过考验吗?README 里的一条用户反馈说,从 2018 年起就用它每天处理数百万次 API 请求,从没出过问题;这个项目从 2015 年就有了,在 GitHub 上有大约 2 万颗星。
Size
15.2 MB
Stars
20K
Age
11y
Commits · 90 Days