Skip to main content

Crate tonic_rest_openapi

Crate tonic_rest_openapi 

Source
Expand description

§tonic-rest-openapi

Crates.io docs.rs License: MIT MSRV

OpenAPI 3.1 spec generation and patching from protobuf descriptors for Tonic gRPC services.

Part of the tonic-rest ecosystem — define your API once in proto files, get gRPC, REST, and OpenAPI 3.1.

Reads compiled protobuf FileDescriptorSet bytes and a gnostic-generated OpenAPI YAML spec, then applies a configurable pipeline of transforms to produce a clean OpenAPI 3.1 spec that matches the runtime REST behavior.

§Key Features

  • Proto as single source of truth — OpenAPI spec derived from the same proto files that drive gRPC and REST
  • 12-phase transform pipeline — produces a clean OpenAPI 3.1 spec with security, validation constraints, and SSE annotations
  • Google error model — injects structured error schemas matching runtime RestError JSON responses
  • Security built-in — auto-generates Bearer JWT security scheme with public endpoint overrides
  • Library + CLI — use programmatically in your build pipeline or as a standalone CI tool

§Pipeline

The 12-phase transform pipeline:

PhaseTransform
1Structural (3.0 → 3.1 upgrade, server/info injection)
2SSE streaming annotations + Last-Event-ID header
3Response fixes (empty→204, plain text, redirects, error schemas, 201 Created)
4Enum value rewrites (strip UNSPECIFIED, normalize values)
5Unimplemented (501) and deprecated operation markers
6Security (Bearer JWT, public endpoint overrides)
7Cleanup (tags, empty bodies, unused schemas, format: enum removal)
8UUID wrapper flattening (path templates, $ref inlining, query params)
9Validation constraints + field access annotation + Duration rewriting
10Path field stripping + path parameter enrichment
11Request body inlining + orphan removal
12CRLF → LF normalization

Each phase can be individually enabled/disabled via PatchConfig or ProjectConfig.

§Usage

§As a Library

use tonic_rest_openapi::{PatchConfig, ProjectConfig, discover, patch};

// From a config file
let project = ProjectConfig::load(Path::new("api/openapi/config.yaml"))?;
let metadata = discover(&descriptor_bytes)?;
let config = PatchConfig::new(&metadata).with_project_config(&project);
let patched_yaml = patch(&input_yaml, &config)?;

Or configure programmatically:

let config = PatchConfig::new(&metadata)
    .unimplemented_methods(&["SetupMfa", "DisableMfa"])
    .public_methods(&["Login", "SignUp"])
    .bearer_description("JWT access token")
    .error_schema_ref("#/components/schemas/ErrorResponse");

let patched_yaml = patch(&input_yaml, &config)?;

§As a CLI

# Full pipeline: lint → generate → patch
tonic-rest-openapi generate --config api/openapi/config.yaml --cargo-toml Cargo.toml

# Standalone patch
tonic-rest-openapi patch --config api/openapi/config.yaml --input spec.yaml --output patched.yaml

# Discover proto metadata
tonic-rest-openapi discover --descriptor file_descriptor_set.bin

Enable the cli feature for the binary:

[dependencies]
tonic-rest-openapi = { version = "0.1", features = ["cli"] }

§Feature Flags

FeatureDefaultDescription
clioffCLI binary with generate, patch, discover, inject-version subcommands (adds clap, toml, anyhow)

§Project Config File

# api/openapi/config.yaml
error_schema_ref: "#/components/schemas/ErrorResponse"

unimplemented_methods:
  - SetupMfa

public_methods:
  - Login
  - SignUp

plain_text_endpoints:
  - path: /health/live
    example: "OK"

metrics_path: /metrics
readiness_path: /health/ready

transforms:
  upgrade_to_3_1: true
  annotate_sse: true
  inject_validation: true
  add_security: true

For a complete end-to-end example with proto files, build.rs, REST handlers, and OpenAPI generation, see auth-service-rs.

§Companion Crates

CratePurposeCargo section
tonic-rest-coreShared descriptor typesinternal
tonic-restRuntime types[dependencies]
tonic-rest-buildBuild-time codegen[build-dependencies]
tonic-rest-openapi (this)OpenAPI 3.1 generationCLI / CI

§Dependencies

This crate uses serde_yaml_ng for YAML parsing and serialization. serde_yaml_ng is a maintained fork of the archived serde_yaml crate. While it is the best available option today, be aware that its ecosystem adoption is narrower than serde_json. If a more widely-adopted YAML serde library emerges in the future, migration may be warranted.

§Compatibility

tonic-rest-openapitonic-rest-coreprostMSRV
0.1.x0.10.141.82

§License

MIT


§API Reference

Structs§

ContactInfo
Contact information for the OpenAPI info.contact block.
EnumRewrite
Enum value rewrite for a schema field whose runtime serde strips prefixes.
ExternalDocsInfo
External documentation link for externalDocs.
FieldConstraint
A single field’s validation constraints, mapped to JSON Schema.
InfoOverrides
Overrides for the OpenAPI info block.
LicenseInfo
License information for the OpenAPI info.license block.
OperationEntry
Maps a short proto method name to its gnostic operation ID.
PatchConfig
Configuration for the OpenAPI patch pipeline.
PathParamConstraint
Constraint for a single path parameter.
PathParamInfo
Path parameter constraint info for a specific HTTP endpoint.
PlainTextEndpoint
An endpoint that returns plain text instead of JSON.
ProjectConfig
Project-level OpenAPI generation config.
ProtoMetadata
All RPC metadata extracted from proto descriptors.
SchemaConstraints
Validation constraints for all fields in one schema.
ServerEntry
A server entry for the OpenAPI servers block.
StreamingOp
A streaming operation: (HTTP method, path).
TransformConfig
Individual transform on/off switches (all default to true).

Enums§

Error
Errors produced by tonic-rest-openapi library operations.

Constants§

DEFAULT_ERROR_SCHEMA_REF
Default $ref path for the REST error response schema.

Functions§

discover
Parse proto descriptor bytes and extract all RPC metadata.
patch
Apply the configured transform pipeline to an OpenAPI YAML spec.

Type Aliases§

Result
Convenience alias used throughout the library’s public API.