Skip to main content

Crate rest_over_grpc

Crate rest_over_grpc 

Source
Expand description

Automatically transcode gRPC services to REST/JSON endpoints.

rest_over_grpc generates REST routes from google.api.http annotations in your .proto files. The generated REST surface runs in the same process as the gRPC service, so you can reuse the same handlers without a separate gateway hop.

§Three layers

The crate is organized around three layers:

  • Serving: adapt network I/O to the transcoder and back.
  • Transcoding: match routes, decode JSON into protobuf messages, and encode replies or Status errors.
  • Handling: implement the generated service trait directly or bridge an existing gRPC stack into it.

§Serving

Pick the integration that fits your stack:

§Transcoding

Generated transcoders support unary and server-streaming RPCs. Unary calls return a buffered HttpResponse; server-streaming calls return a StreamingResponse whose frames are forwarded as they are produced.

Server-streaming response encoding is negotiated from Accept: JSON array (application/json, */*, or absent), NDJSON (application/x-ndjson), or Server-Sent Events (text/event-stream).

Use transcode when unmatched routes should become 404; use try_transcode when you want to fall back to custom routing.

§Handling

The generated <Service> trait has one method per RPC, each taking the decoded request plus a mutable Context.

  • tonic: the build module emits a guarded bridge so a tonic implementation can serve REST with an explicit authorization policy.
  • direct implementation: implement the generated trait yourself.
  • other gRPC stacks: write a small bridge that forwards into the generated trait.

Server-streaming methods return a ResponseStream, and handlers report failures with Status. Use Context for request metadata and to set response headers.

§Quick start: bridge an existing tonic service

The normal setup generates protobuf messages, proto3-JSON serde implementations, and the REST layer from the same descriptor set.

  1. Annotate the service:
syntax = "proto3";
package library;

import "google/api/annotations.proto";

service Library {
  rpc GetShelf(GetShelfRequest) returns (Shelf) {
    option (google.api.http) = {
      get: "/v1/shelves/{shelf}"
    };
  }
}

message GetShelfRequest {
  string shelf = 1;
}

message Shelf {
  string name = 1;
}
  1. In build.rs, compile one descriptor set through tonic-prost-build, pbjson-build, and rest_over_grpc. The REST generator does not generate message types or serde implementations itself:
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut compiler = protox::Compiler::new(["proto"])?;
    compiler.include_imports(true);
    compiler.include_source_info(true);
    compiler.open_file("library.proto")?;
    let descriptors = compiler.encode_file_descriptor_set();

    tonic_prost_build::configure()
        .build_client(false)
        .build_server(true)
        .build_transport(false)
        .compile_fds(compiler.file_descriptor_set())?;
    pbjson_build::Builder::new()
        .register_descriptors(&descriptors)?
        .build(&[".library"])?;
    rest_over_grpc::build::compile_fds(
        &descriptors,
        std::env::var("OUT_DIR")?,
    )?;
    Ok(())
}

Add rest_over_grpc with features build,tower plus protox, tonic-prost-build, and pbjson-build as build dependencies. Generated pbjson code also requires the corresponding serde/runtime dependencies. The worked example manifest lists a complete set.

  1. Include the generated files. Message, serde, and service-trait output belong in the proto package module; the top-level transcoder is included beside that module:
pub mod library {
    include!(concat!(env!("OUT_DIR"), "/library.rs"));
    include!(concat!(env!("OUT_DIR"), "/library.serde.rs"));
    include!(concat!(env!("OUT_DIR"), "/library.rest.rs"));
}

mod rest {
    use super::library;
    include!(concat!(env!("OUT_DIR"), "/transcoder.rest.rs"));
}
  1. Implement the generated tonic server trait as usual, then wrap that implementation in the generated transcoder:
ⓘ
#[derive(Clone)]
struct LibraryService;

#[tonic::async_trait]
impl library::library_server::Library for LibraryService {
    async fn get_shelf(
        &self,
        request: tonic::Request<library::GetShelfRequest>,
    ) -> Result<tonic::Response<library::Shelf>, tonic::Status> {
        let shelf = request.into_inner().shelf;
        Ok(tonic::Response::new(library::Shelf {
            name: format!("shelves/{shelf}"),
        }))
    }
}

let bridge = library::__rest_over_grpc_bridge_Library::LibraryRestBridge::with_guard(LibraryService, authorize_rest_metadata);
let transcoder = rest::Transcoder::new(bridge);
let service = rest_over_grpc::serving::RestService::new(transcoder)
    .with_max_body_bytes(1 << 20);

authorize_rest_metadata is an application-provided guard that checks the REST request’s metadata before the tonic handler runs. Tonic transport interceptors do not execute on REST calls. If an upstream HTTP layer guarantees the same authorization, use the deliberately named LibraryRestBridge::externally_authenticated constructor on the namespaced bridge instead. The tonic bridge is emitted by default; call Generator::builder with emit_tonic_bridge(false) when implementing the generated REST trait directly. See the complete build script, generated includes, and tonic handler for versions that compile.

§Examples

The example index maps common tasks to runnable examples. It covers end-to-end generation, serving, direct transcoding, custom fallback, streaming, OpenAPI, direct handlers, tonic bridging, and non-tonic bridges. generate_service.rs demonstrates the lower-level manual HttpRule API; annotation-driven generation is shown in the complete build script.

§Limitations

The crate supports unary and server-streaming RPCs only. Client-streaming and bidirectional RPCs have no google.api.http mapping and are rejected by build.

Requests are buffered and parsed as JSON, so there is no incremental request body path and binary payloads must fit JSON-friendly encoding.

Query parameter field paths are limited to 64 levels of nesting. A dotted key such as ?a.b.c=1 builds one level per segment, so a path deeper than the limit is rejected as an invalid request rather than decoded, truncated, or allowed to exhaust the stack. The limit is fixed and not configurable: it bounds the recursion an untrusted request can drive, and a bound a caller could raise would not bound anything. It stays far above the nesting any real proto message uses. Query inputs also have a fixed aggregate pair and byte budget.

§Cargo features

tower and layered imply serving. The axum feature only adds IntoResponse; enable tower as well to mount RestService as an Axum fallback service.

Modules§

buildbuild
REST-layer code generation for services behind the build feature.
handling
Handling layer: the value types your service handlers deal in.
servingserving
Adapters between generated transcoders and the http/http-body ecosystem.
transcoding
Transcoding layer: the Transcode contract and the values it produces.