Top Related Projects
gRPC Web implementation for Golang and TypeScript
A simple RPC framework with protobuf service definitions
Like cURL, but for gRPC: Command-line tool for interacting with gRPC servers
Public interface definitions of Google APIs.
Quick Overview
gRPC-Gateway is an open-source project that generates a reverse-proxy server which translates a RESTful JSON API into gRPC. It allows you to provide your APIs in both gRPC and RESTful styles at the same time, leveraging Protocol Buffers for efficient data serialization and gRPC for high-performance communication.
Pros
- Seamless integration of gRPC and REST APIs
- Automatic generation of Swagger/OpenAPI documentation
- Supports streaming APIs
- Reduces boilerplate code for API development
Cons
- Learning curve for developers new to gRPC and Protocol Buffers
- Potential performance overhead due to translation layer
- Limited customization options for complex use cases
- Dependency on Protocol Buffers for API definition
Code Examples
- Defining a simple gRPC service:
syntax = "proto3";
package example;
import "google/api/annotations.proto";
service EchoService {
rpc Echo(StringMessage) returns (StringMessage) {
option (google.api.http) = {
post: "/v1/example/echo"
body: "*"
};
}
}
message StringMessage {
string value = 1;
}
- Generating gRPC-Gateway code:
protoc -I/usr/local/include -I. \
-I$GOPATH/src \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--go_out=plugins=grpc:. \
--grpc-gateway_out=logtostderr=true:. \
path/to/your_service.proto
- Implementing the gRPC server:
type server struct{}
func (s *server) Echo(ctx context.Context, msg *pb.StringMessage) (*pb.StringMessage, error) {
return &pb.StringMessage{Value: msg.Value}, nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("Failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterEchoServiceServer(s, &server{})
log.Println("Serving gRPC on 0.0.0.0:50051")
s.Serve(lis)
}
Getting Started
-
Install Protocol Buffers compiler:
brew install protobuf
-
Install gRPC-Gateway and dependencies:
go get -u github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway go get -u github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2 go get -u google.golang.org/protobuf/cmd/protoc-gen-go go get -u google.golang.org/grpc/cmd/protoc-gen-go-grpc
-
Define your gRPC service in a .proto file
-
Generate gRPC and gRPC-Gateway code using protoc
-
Implement your gRPC server
-
Set up the gRPC-Gateway reverse-proxy server
For detailed instructions, refer to the project's official documentation.
Competitor Comparisons
gRPC Web implementation for Golang and TypeScript
Pros of grpc-web
- Direct browser-to-gRPC server communication without an intermediate proxy
- Supports streaming responses from the server
- Provides TypeScript definitions for generated code
Cons of grpc-web
- Requires server-side support for the gRPC-Web protocol
- Limited to unary and server-streaming RPCs (no client streaming or bidirectional streaming)
- May have performance overhead due to HTTP/1.1 limitations
Code Comparison
grpc-gateway:
mux := runtime.NewServeMux()
err := pb.RegisterYourServiceHandlerFromEndpoint(ctx, mux, "localhost:50051", opts)
http.ListenAndServe(":8080", mux)
grpc-web:
const client = new YourServiceClient('http://localhost:8080');
client.yourMethod(request, {}, (err, response) => {
// Handle response
});
grpc-gateway generates a RESTful API from gRPC service definitions, while grpc-web allows direct gRPC communication from browsers. grpc-gateway is more suitable for creating REST APIs from existing gRPC services, while grpc-web is better for web applications that need to interact directly with gRPC services. The choice between them depends on specific project requirements and architecture preferences.
A simple RPC framework with protobuf service definitions
Pros of Twirp
- Simpler and more lightweight than grpc-gateway
- Easier to set up and use, with less configuration required
- Better support for JSON-based APIs and REST-like semantics
Cons of Twirp
- Less feature-rich compared to grpc-gateway
- Limited support for advanced gRPC features and streaming
- Smaller ecosystem and community support
Code Comparison
grpc-gateway:
syntax = "proto3";
package example;
import "google/api/annotations.proto";
service ExampleService {
rpc GetExample(GetExampleRequest) returns (Example) {
option (google.api.http) = {
get: "/v1/examples/{id}"
};
}
}
Twirp:
syntax = "proto3";
package example;
service ExampleService {
rpc GetExample(GetExampleRequest) returns (Example);
}
The grpc-gateway example shows how to define HTTP endpoints using annotations, while Twirp uses a simpler approach without additional annotations. grpc-gateway provides more control over HTTP routing, while Twirp follows conventions for generating HTTP endpoints.
Both projects aim to bridge gRPC and HTTP/JSON APIs, but they differ in complexity and feature set. grpc-gateway offers more flexibility and advanced features, while Twirp focuses on simplicity and ease of use.
Like cURL, but for gRPC: Command-line tool for interacting with gRPC servers
Pros of grpcurl
- Lightweight command-line tool for interacting with gRPC servers
- Supports dynamic service reflection, allowing exploration of gRPC services without prior knowledge
- Can be used for quick testing and debugging of gRPC services
Cons of grpcurl
- Limited to command-line interface, not suitable for integrating gRPC services with web applications
- Doesn't provide automatic REST API generation from gRPC services
- Lacks built-in support for transcoding between gRPC and HTTP/JSON
Code Comparison
grpc-gateway example:
mux := runtime.NewServeMux()
err := pb.RegisterYourServiceHandlerFromEndpoint(ctx, mux, "localhost:50051", opts)
http.ListenAndServe(":8080", mux)
grpcurl example:
grpcurl -plaintext localhost:50051 list
grpcurl -plaintext -d '{"name": "World"}' localhost:50051 helloworld.Greeter/SayHello
grpc-gateway focuses on generating RESTful APIs from gRPC services, providing a seamless integration between gRPC and HTTP/JSON. It's ideal for creating web-friendly APIs from existing gRPC services.
grpcurl, on the other hand, is a command-line tool for interacting with gRPC services directly. It's useful for testing and debugging but doesn't provide the same level of integration capabilities as grpc-gateway.
Choose grpc-gateway for building RESTful APIs from gRPC services, and grpcurl for quick testing and exploration of gRPC services during development.
Public interface definitions of Google APIs.
Pros of googleapis
- Comprehensive collection of Google API definitions
- Official repository maintained by Google
- Includes API definitions for various Google services
Cons of googleapis
- Focused primarily on Google-specific APIs
- May require additional tools for gRPC-REST translation
- Less flexibility for custom API implementations
Code Comparison
googleapis:
syntax = "proto3";
package google.pubsub.v1;
message Topic {
string name = 1;
}
grpc-gateway:
syntax = "proto3";
import "google/api/annotations.proto";
service EchoService {
rpc Echo(StringMessage) returns (StringMessage) {
option (google.api.http) = {
post: "/v1/example/echo"
body: "*"
};
}
}
Key Differences
- googleapis focuses on defining Google's APIs, while grpc-gateway provides tools for gRPC-REST translation
- grpc-gateway offers more flexibility for custom API implementations
- googleapis is more suitable for projects heavily relying on Google services
- grpc-gateway is better for projects requiring REST API exposure of gRPC services
Use Cases
- Use googleapis when working extensively with Google Cloud services
- Choose grpc-gateway for projects needing to expose gRPC services as REST APIs
- Consider combining both for projects using Google APIs and requiring gRPC-REST translation
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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:
// +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
;
protoc-gen-grpc-gateway
protoc-gen-openapiv2
protoc-gen-go
protoc-gen-go-grpc
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:
- Install the verification tool from slsa-framework/slsa-verifier#installation.
- Download the provenance file
attestation.intoto.jsonl
from the GitHub releases page. - 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: v1
plugins:
- plugin: go
out: gen/go
opt:
- paths=source_relative
- plugin: 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:
- no further modifications, use the default mapping to HTTP semantics (method, path, etc.)
- this will work on any
.proto
file, but will not allow setting HTTP paths, request parameters or similar
- this will work on any
- additional
.proto
modifications to use a custom mapping- relies on parameters in the
.proto
file to set custom HTTP mappings
- relies on parameters in the
- no
.proto
modifications, but use an external configuration file- relies on an external configuration file to set custom HTTP mappings
- mostly useful when the source proto file isn't under your control
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: v1
plugins:
- plugin: go
out: gen/go
opt:
- paths=source_relative
- plugin: go-grpc
out: gen/go
opt:
- paths=source_relative
- plugin: 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 yourbuf.yaml
under the namebuf.build/googleapis/googleapis
:version: v1 name: buf.build/yourorg/myprotos deps: - buf.build/googleapis/googleapis
Always run
buf mod update
after adding a dependency to yourbuf.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: v1
plugins:
- plugin: go
out: gen/go
opt:
- paths=source_relative
- plugin: go-grpc
out: gen/go
opt:
- paths=source_relative
- plugin: 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: v1
plugins:
- plugin: go
out: gen/go
opt:
- paths=source_relative
- plugin: go-grpc
out: gen/go
opt:
- paths=source_relative
- plugin: 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: v1
plugins:
- plugin: go
out: gen/go
opt:
- paths=source_relative
- plugin: go-grpc
out: gen/go
opt:
- paths=source_relative
- plugin: grpc-gateway
out: gen/go
opt:
- paths=source_relative
- plugin: openapiv2
out: gen/openapiv2
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: v1
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.
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: v1
plugins:
- plugin: buf.build/protocolbuffers/go:v1.31.0
out: gen/go
opt:
- paths=source_relative
- plugin: buf.build/grpc/go:v1.3.0
out: gen/go
opt:
- paths=source_relative
- plugin: buf.build/grpc-ecosystem/gateway:v2.16.2
out: gen/go
opt:
- paths=source_relative
- plugin: 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/v2@v2.16.2
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: v1
plugins:
- plugin: 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:
- as part of the
--<tool_suffix>_out
protoc
parameter:--<tool_suffix>_out=<flags>:<path>
--grpc-gateway_out=repeated_path_param_separator=ssv:.
--openapiv2_out=repeated_path_param_separator=ssv:.
- using additional
--<tool_suffix>_opt
parameters:--<tool_suffix>_opt=<flag>[,<flag>]*
--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.
proto/examplepb/echo_service.proto
,proto/examplepb/a_bit_of_everything.proto
,proto/examplepb/unannotated_echo_service.proto
: service definitionproto/examplepb/echo_service.pb.go
,proto/examplepb/a_bit_of_everything.pb.go
,proto/examplepb/unannotated_echo_service.pb.go
: [generated] stub of the serviceproto/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 serviceproto/examplepb/unannotated_echo_service.yaml
: gRPC API Configuration forunannotated_echo_service.proto
server/main.go
: service implementationmain.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, 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
- Generating JSON API handlers.
- Method parameters in the request body.
- Method parameters in the request path.
- Method parameters in the 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 withgrpcgateway-
) - Optionally emitting API definitions for OpenAPI (Swagger) v2.
- Setting gRPC timeouts
through inbound HTTP
Grpc-Timeout
header. - Partial support for gRPC API Configuration files as an alternative to annotation.
- Automatically translating PATCH requests into Field Mask gRPC requests. See the docs for more information.
No plan to support
But patches are 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 asauthorization
gRPC request header. - Remaining Permanent HTTP header keys (as specified by the IANA
here)
are 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 uses protojson.
- The path template used to map gRPC service methods to HTTP endpoints supports the google.api.http
path template syntax. For example,
/api/v1/{name=projects/*/topics/*}
or/prefix/{path=organizations/**}
.
Contribution
See CONTRIBUTING.md.
License
gRPC-Gateway is licensed under the BSD 3-Clause License. See LICENSE for more details.
Top Related Projects
gRPC Web implementation for Golang and TypeScript
A simple RPC framework with protobuf service definitions
Like cURL, but for gRPC: Command-line tool for interacting with gRPC servers
Public interface definitions of Google APIs.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot