### Install protoc-gen-connect-openapi with Go Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Installs the protoc-gen-connect-openapi plugin directly using Go. This method is not recommended but is provided for completeness. ```shell go install github.com/sudorandom/protoc-gen-connect-openapi@latest protoc-gen-connect-openapi --version ``` -------------------------------- ### Install protoc-gen-connect-openapi with asdf Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Installs the protoc-gen-connect-openapi plugin using the asdf version manager. This is a recommended method for managing toolchain versions. ```shell $ asdf plugin add protoc-gen-connect-openapi https://github.com/sudorandom/asdf-protoc-gen-connect-openapi.git $ asdf list all protoc-gen-connect-openapi $ asdf install protoc-gen-connect-openapi latest $ asdf global protoc-gen-connect-openapi latest ``` -------------------------------- ### Install protoc-gen-connect-openapi with Go Tool Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Installs the protoc-gen-connect-openapi plugin using Go's 'go tool' support, available from Go 1.24 onwards. This integrates the plugin with your existing Go toolchain. ```shell go get -tool github.com/sudorandom/protoc-gen-connect-openapi@latest go tool protoc-gen-connect-openapi --version ``` -------------------------------- ### Example GET Request for Connect RPC Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Demonstrates the structure of a GET request for a Connect RPC method that is marked as idempotent. Note the query parameters for encoding and message payload. ```http > GET /connectrpc.greet.v1.GreetService/Greet?encoding=json&message=%7B%22name%22%3A%22Buf%22%7D HTTP/1.1 > Host: demo.connectrpc.com < HTTP/1.1 200 OK < Content-Type: application/json < < {"greeting": "Hello, Buf!"} ``` -------------------------------- ### Example Protobuf with Gnostic Annotations Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/06-features-validation-visibility.md This example demonstrates how to use Gnostic annotations within a protobuf message and service definition to provide OpenAPI schema and operation metadata. ```protobuf import "google/protobuf/descriptor.proto"; import "google/openapi/v3/annotations.proto"; message User { option (google.openapi.v3.schema) = { json_schema: { title: "User Object" description: "Represents a user account" examples: "{\"id\": \"123\", \"name\": \"John\"}" } }; string id = 1; string name = 2; } service UserService { rpc GetUser(GetUserRequest) returns (User) { option (google.openapi.v3.operation) = { external_docs: { url: "https://example.com/docs/users" description: "User API Documentation" } }; } } ``` -------------------------------- ### Twirp Example Path Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/04-protocol-implementations.md An example of a generated OpenAPI path for a Twirp RPC method. ```text /twirp/connectrpc.greet.v1.GreetService/Greet ``` -------------------------------- ### Basic Connect RPC Generation Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Generate OpenAPI specifications from Connect protocol services using the default settings. This is the most basic command to get started. ```bash protoc \ --connect-openapi_out=gen \ service.proto ``` -------------------------------- ### Generate OpenAPI from Specific Files Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md This example shows how to generate an OpenAPI specification by loading protobuf files into a registry. The output is saved as 'api.openapi.json'. ```go package main import ( "log" "os" "github.com/sudorandom/protoc-gen-connect-openapi/converter" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/descriptorpb" ) func main() { // Load your protobuf files into a registry // In real code, you'd load from compiled descriptors registry := protoregistry.GlobalFiles content, err := converter.GenerateSingle( converter.WithFiles(registry), ) if err != nil { log.Fatal(err) } os.WriteFile("api.openapi.json", content, 0644) } ``` -------------------------------- ### Allow GET for Idempotent Methods Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Use `WithAllowGET` to enable documenting methods with `idempotency_level = NO_SIDE_EFFECTS` as HTTP GET requests instead of POST. Set the `allowGet` parameter to `true` to enable this behavior. ```go converter.GenerateSingle( converter.WithGlobal(), converter.WithAllowGET(true), ) ``` -------------------------------- ### Build Protobuf Plugin Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/08-plugin-architecture.md Builds the protoc-gen-connect-openapi plugin executable. Ensure you have Go installed and the necessary dependencies. ```bash go build -o bin/protoc-gen-connect-openapi ``` -------------------------------- ### ConnectRPC Example Path Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/04-protocol-implementations.md Illustrates the standard path format for ConnectRPC services and methods. ```text /connectrpc.greet.v1.GreetService/Greet ``` -------------------------------- ### Create New Options with Defaults Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/02-configuration-options.md Creates a new Options struct initialized with sensible default values. Use this as a starting point for custom configurations. ```go opts := converter.NewOptions() opts.Format = "json" opts.AllowGET = true ``` -------------------------------- ### Apply Custom Configuration Options Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md This example demonstrates applying various custom configuration options to tailor the OpenAPI generation, such as format, content types, and path prefixes. The output is saved as 'api.openapi.yaml'. ```go package main import ( "log" "os" "github.com/sudorandom/protoc-gen-connect-openapi/converter" ) func main() { content, err := converter.GenerateSingle( converter.WithGlobal(), converter.WithFormat("yaml"), converter.WithContentTypes("json", "proto"), converter.WithAllowGET(true), converter.WithProtoNames(false), converter.WithTrimUnusedTypes(true), converter.WithShortServiceTags(true), converter.WithFullyQualifiedMessageNames(false), converter.WithPathPrefix("/api/v1"), ) if err != nil { log.Fatal(err) } os.WriteFile("api.openapi.yaml", content, 0644) } ``` -------------------------------- ### Example of Gnostic Annotations in Protobuf Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/remote-plugin.md This example demonstrates how to use gnostic annotations within a .proto file to define top-level OpenAPI document information, such as API title, version, and contact details. This approach is compatible with remote plugins. ```protobuf syntax = "proto3"; package my.service.v1; import "gnostic/openapi/v3/annotations.proto"; option (gnostic.openapi.v3.document) = { info: { title: "My Awesome API"; version: "1.0.0"; description: "This is a sample server for a pet store."; contact: { name: "API Support"; url: "http://www.example.com/support"; email: "support@example.com"; } license: { name: "Apache 2.0"; url: "http://www.apache.org/licenses/LICENSE-2.0.html"; } } }; service MyService { // ... } ``` -------------------------------- ### Custom Annotator Implementation Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/08-plugin-architecture.md Example of a custom implementation for schema annotation. Allows for adding custom metadata. ```go type CustomAnnotator struct{} func (ca *CustomAnnotator) AnnotateMessage(...) *Schema { // Add custom metadata } ``` -------------------------------- ### Enable GET Requests for Idempotent Methods Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Allow the generation of GET HTTP methods for idempotent Connect RPC methods. This can be enabled using the 'allow-get' option. ```bash protoc \ --connect-openapi_out=gen \ --connect-openapi_opt=allow-get \ service.proto ``` -------------------------------- ### gRPC-Gateway Annotations in Protobuf Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/grpcgateway.md Example Protobuf service definition using gRPC-Gateway annotations to map HTTP methods and paths to gRPC RPCs. This includes options for GET, POST, PUT, DELETE requests, specifying request bodies, and response bodies. ```protobuf syntax = "proto3"; package io.swagger.petstore.v2; import "google/api/annotations.proto"; import "google/protobuf/empty.proto"; service PetService { rpc GetPetByID(PetID) returns (Pet) { option (google.api.http).get = "/pet/{pet_id}"; option idempotency_level = NO_SIDE_EFFECTS; } rpc UpdatePetWithForm(UpdatePetWithFormReq) returns (google.protobuf.Empty) { option (google.api.http).post = "/pet/{pet_id}"; option (google.api.http).body = "*"; } rpc DeletePet(PetID) returns (google.protobuf.Empty) { option (google.api.http).delete = "/pet/{pet_id}"; } rpc UploadFile(UploadFileReq) returns (ApiResponse) { option (google.api.http).post = "/pet/{pet_id}/uploadImage"; option (google.api.http).body = "*"; } rpc AddPet(Pet) returns (Pet) { option (google.api.http).post = "/pet"; option (google.api.http).body = "*"; } rpc UpdatePet(Pet) returns (Pet) { option (google.api.http).put = "/pet"; option (google.api.http).body = "*"; } rpc FindPetsByTag(TagReq) returns (Pets) { option deprecated = true; option (google.api.http).get = "/pet/findByTags"; option (google.api.http).response_body = "pets"; option idempotency_level = NO_SIDE_EFFECTS; } rpc FindPetsByStatus(StatusReq) returns (Pets) { option (google.api.http).get = "/pet/findByStatus"; option (google.api.http).response_body = "pets"; option idempotency_level = NO_SIDE_EFFECTS; } } ``` -------------------------------- ### Generate Multiple Output Files Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md This example demonstrates generating multiple OpenAPI files, specifying the output format as JSON. The generated files are placed in the 'gen' directory. ```go package main import ( "log" "os" "path/filepath" "github.com/sudorandom/protoc-gen-connect-openapi/converter" ) func main() { files, err := converter.Generate( converter.WithGlobal(), converter.WithFormat("json"), ) if err != nil { log.Fatal(err) } // Create output directory os.MkdirAll("gen", 0755) // Write each file for _, file := range files { path := filepath.Join("gen", *file.Name) if err := os.WriteFile(path, []byte(file.GetContent()), 0644); err != nil { log.Fatal(err) } log.Printf("Generated: %s", path) } } ``` -------------------------------- ### Example Protobuf with Visibility Annotations Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/06-features-validation-visibility.md This protobuf definition demonstrates how to apply visibility restrictions to messages, fields, and services using google.api.visibility options. ```protobuf import "google/api/client.proto"; message User { option (google.api.api_visibility).restriction = "PUBLIC"; string id = 1 [(google.api.visibility).restriction = "PUBLIC"]; string email = 2 [(google.api.visibility).restriction = "INTERNAL"]; } service UserService { option (google.api.api_visibility).restriction = "PUBLIC"; rpc GetUser(GetUserRequest) returns (User) { option (google.api.method_visibility).restriction = "PUBLIC"; } } ``` -------------------------------- ### Go Example for Visibility Filtering Logic Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/06-features-validation-visibility.md This Go code snippet shows how to configure allowed visibilities and demonstrates the filtering logic based on element restrictions. Elements with 'PUBLIC' or 'BETA' restrictions are not filtered, while 'INTERNAL' elements are. ```go opts := converter.Options{} opts.AllowedVisibilities = map[string]bool{ "PUBLIC": true, "BETA": true, } // Element with restriction="PUBLIC" → Not filtered // Element with restriction="INTERNAL" → Filtered // Element with no visibility rule → Not filtered // Element with restriction="PUBLIC,BETA" → Not filtered (at least one matches) ``` -------------------------------- ### Filter by Visibility Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md This example demonstrates how to filter elements based on their visibility level, including only 'PUBLIC' and 'BETA' elements in the generated OpenAPI. The output is saved to 'api.openapi.yaml'. ```go package main import ( "log" "os" "github.com/sudorandom/protoc-gen-connect-openapi/converter" ) func main() { content, err := converter.GenerateSingle( converter.WithGlobal(), // Only include PUBLIC and BETA elements converter.WithAllowedVisibilities("PUBLIC", "BETA"), ) if err != nil { log.Fatal(err) } os.WriteFile("api.openapi.yaml", content, 0644) } ``` -------------------------------- ### Convert: Primary Protoc Plugin Entrypoint Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/03-internal-converter.md The Convert function serves as the main entrypoint for the protoc plugin, converting a CodeGeneratorRequest to a CodeGeneratorResponse. It handles parameter parsing and logger setup before calling ConvertWithOptions. ```Go resp, err := converter.Convert(req) if err != nil { // Handle error } ``` -------------------------------- ### Buf Local Plugin Configuration Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Configure protoc-gen-connect-openapi as a local plugin in Buf using this YAML. This requires the plugin to be installed locally before running 'buf generate'. ```yaml version: v2 plugins: - local: protoc-gen-connect-openapi out: gen opt: - base=example.base.yaml ``` -------------------------------- ### Parse Options from String Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/02-configuration-options.md Parses a comma-separated string of command-line options into an Options struct. Handles various configuration settings like format, GET request enablement, and content types. ```go opts, err := converter.FromString("format=json,allow-get,trim-unused-types") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Public API Configuration Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Configure the generator for public APIs, specifying visibility, service patterns, path prefix, and enabling GET requests. ```go converter.GenerateSingle( converter.WithGlobal(), converter.WithAllowedVisibilities("PUBLIC"), converter.WithServicePatterns([]string{"company.public.**"}), converter.WithPathPrefix("/api/v1"), converter.WithAllowGET(true), ) ``` -------------------------------- ### Buf Remote Plugin Configuration Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Use this YAML configuration to integrate protoc-gen-connect-openapi as a remote plugin within Buf. Ensure the version and path are correct for your setup. ```yaml version: v2 plugins: - remote: buf.build/community/sudorandom-connect-openapi:v0.19.1 out: gen opt: - base=example.base.yaml ``` -------------------------------- ### Protobuf Message with Protovalidate Constraints Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/06-features-validation-visibility.md Example Protobuf message demonstrating various field-level Protovalidate constraints for email, string length, unsigned integer ranges, and repeated field item counts. ```protobuf import "buf/validate/validate.proto"; message User { string email = 1 [(buf.validate.field).string.email = true]; string name = 2 [(buf.validate.field).string = { min_len: 1, max_len: 100 }]; uint32 age = 3 [(buf.validate.field).uint32 = { gte: 0, lte: 150 }]; repeated string tags = 4 [(buf.validate.field).repeated = { min_items: 0, max_items: 10 }]; } ``` -------------------------------- ### Generate Single OpenAPI File Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Use `GenerateSingle` to create a single, merged OpenAPI specification file. Configure output format (YAML/JSON) and allow GET requests using functional options. Assumes protobuf files are loaded into the global registry. ```go package main import ( "log" "github.com/sudorandom/protoc-gen-connect-openapi/converter" "google.golang.org/protobuf/reflect/protoregistry" ) func main() { // Assuming you have loaded protobuf files into the global registry content, err := converter.GenerateSingle( converter.WithGlobal(), converter.WithFormat("yaml"), converter.WithAllowGET(true), ) if err != nil { log.Fatalf("generation failed: %v", err) } // content contains the OpenAPI specification } ``` -------------------------------- ### Read Build Information Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/08-plugin-architecture.md Retrieves build information at runtime, including version, commit hash, and build date. Access settings like VCS revision and time. ```go debug.ReadBuildInfo() // Access settings: vcs.revision, vcs.time ``` -------------------------------- ### Initialize OpenAPI Document Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/03-internal-converter.md Initializes an OpenAPI document with default structures like version, Info, Paths, and Components if they are not already present. It also sets up internal indexing for spec parsing. ```go func initializeDoc(opts options.Options, doc *v3.Document) error { // Implementation details omitted for brevity return nil } ``` -------------------------------- ### Configure protoc-gen-connect-openapi with buf.gen.yaml (Go Tool) Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Configures the protoc-gen-connect-openapi plugin to be run using 'go tool' within a buf.gen.yaml file. This leverages Go 1.24+ features for plugin execution. ```yaml version: v2 plugins: - local: ["go", "tool", "protoc-gen-connect-openapi"] out: gen ``` -------------------------------- ### Generate Test DescriptorSets Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/08-plugin-architecture.md Generates DescriptorSets from test proto files located in internal/converter/testdata. This is part of the testing setup. ```bash go generate ./internal/converter/testdata ``` -------------------------------- ### Using buf for Generation with Options Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Configure protoc-gen-connect-openapi within a buf.gen.yaml file to manage generation options like output format, allowed HTTP methods, and path prefixes. Run 'buf generate' to execute. ```yaml version: v2 plugins: - remote: buf.build/community/sudorandom-connect-openapi:v0.19.1 out: gen opt: - format=json - allow-get - path-prefix=/api/v1 ``` ```bash buf generate ``` -------------------------------- ### Enable Service Descriptions in OpenAPI Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Use WithServiceDescriptions to include service names and comments in the OpenAPI info description. Set enabled to true to include them. ```go converter.GenerateSingle( converter.WithGlobal(), converter.WithServiceDescriptions(true), ) ``` -------------------------------- ### Configure protoc-gen-connect-openapi with buf.gen.yaml (Go) Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Configures the protoc-gen-connect-openapi plugin to be run directly using 'go run' within a buf.gen.yaml file. This is useful if you are using buf for protobuf generation. ```yaml version: v2 plugins: - local: ["go", "run", "github.com/sudorandom/protoc-gen-connect-openapi@latest"] out: gen ``` -------------------------------- ### WithAllowGET Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Allows methods with `idempotency_level = NO_SIDE_EFFECTS` to be documented as HTTP GET requests instead of POST. This can be used to enable more RESTful API designs where appropriate. ```APIDOC ## WithAllowGET ### Description Allows methods with `idempotency_level = NO_SIDE_EFFECTS` to be documented as HTTP GET requests instead of POST. ### Method func WithAllowGET(allowGet bool) Option ### Parameters #### Path Parameters - **allowGet** (`bool`) - Required - Enable GET support for idempotent methods ### Request Example ```go converter.GenerateSingle( converter.WithGlobal(), converter.WithAllowGET(true), ) ``` ``` -------------------------------- ### Get Extension Type Resolver Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/02-configuration-options.md Retrieves the configured extension type resolver. If none is explicitly set, it falls back to using the global registry. ```go func (opts Options) GetExtensionTypeResolver() protoregistry.ExtensionTypeResolver { // ... implementation details ... } ``` -------------------------------- ### Parameter String Parsing Pipeline Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/08-plugin-architecture.md Illustrates the step-by-step process of parsing a parameter string into usable options. ```text Parameter String ↓ FromString() ↓ Split by comma ↓ Foreach param: ├ Switch on param name ├ Validate value └ Update Options field ↓ Return Options or error ``` -------------------------------- ### Get Override Components Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/03-internal-converter.md Parses an override OpenAPI document (YAML or JSON) specified in the options and extracts its components. Returns nil if no override is configured. ```go func getOverrideComponents(opts options.Options) (*v3.Components, error) { // ... implementation details ... return nil, nil } ``` -------------------------------- ### Development Configuration Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Configure the generator for a development environment with debugging and service descriptions enabled. ```go converter.GenerateSingle( converter.WithGlobal(), converter.WithDebug(true), converter.WithServiceDescriptions(true), converter.WithProtoAnnotations(true), converter.WithLogger(logger), ) ``` -------------------------------- ### Main Plugin Entry Point Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/08-plugin-architecture.md The main function serves as the entry point for the protoc plugin. It reads a CodeGeneratorRequest from stdin, processes it using the converter, and writes a CodeGeneratorResponse to stdout. Handles errors during conversion by rendering an error response and exiting. ```go func main() { resp, err := converter.ConvertFrom(os.Stdin) if err != nil { renderResponse(&pluginpb.CodeGeneratorResponse{ Error: &message, }) os.Exit(1) } renderResponse(resp) } ``` -------------------------------- ### Protoc Plugin Integration Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/00-index.md Use this command to integrate protoc-gen-connect-openapi as a protoc plugin. Ensure the plugin executable is in your PATH or specified with its full path. ```bash protoc --plugin=protoc-gen-connect-openapi=./bin/protoc-gen-connect-openapi ``` -------------------------------- ### Visibility Filtering for OpenAPI Elements Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Control which elements are included in the OpenAPI specification based on their visibility. Use the 'allowed-visibilities' option to filter, for example, to only include PUBLIC elements. ```bash protoc \ --connect-openapi_out=gen \ --connect-openapi_opt=allowed-visibilities=PUBLIC \ service.proto ``` -------------------------------- ### Programmatic OpenAPI Generation (Go) Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/00-index.md This Go program demonstrates how to programmatically generate an OpenAPI specification with custom options for format and HTTP methods. ```go package main import ( "os" "github.com/sudorandom/protoc-gen-connect-openapi/converter" ) func main() { content, err := converter.GenerateSingle( converter.WithGlobal(), converter.WithFormat("yaml"), converter.WithAllowGET(true), ) if err != nil { panic(err) } os.WriteFile("api.openapi.yaml", content, 0644) } ``` -------------------------------- ### Define Protobuf Message with Validation Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/00-index.md Define Protobuf messages with validation rules using buf.validate.proto. This example shows email format validation and minimum string length for a name field. ```protobuf import "buf/validate/validate.proto"; message User { string email = 1 [(buf.validate.field).string.email = true]; string name = 2 [(buf.validate.field).string.min_len = 1]; } ``` -------------------------------- ### Generate OpenAPI with Options (CLI) Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/00-index.md This command demonstrates how to generate an OpenAPI specification with specific options like format and HTTP method. ```bash # With options protoc \ --connect-openapi_out=gen \ --connect-openapi_opt=format=json,allow-get \ service.proto ``` -------------------------------- ### Buf Configuration for Protoc-Gen-Connect-OpenAPI Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/00-index.md Configure Buf to use the protoc-gen-connect-openapi plugin by specifying its remote location and output directory in buf.gen.yaml. ```yaml # buf.gen.yaml plugins: - remote: buf.build/community/sudorandom-connect-openapi:v0.19.1 out: gen ``` -------------------------------- ### Generate OpenAPI from Protobuf Files Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Use `WithFiles` to generate OpenAPI specifications from a given set of protobuf files. Ensure the `protoregistry.Files` object is correctly populated. ```go content, err := converter.GenerateSingle( converter.WithFiles(myRegistry), ) ``` -------------------------------- ### Protobuf with Gnostic OpenAPI v3 Annotations Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/gnostic.md This protobuf file demonstrates the use of gnostic's OpenAPI v3 annotations to define document information, components, services, and messages. ```protobuf syntax = "proto3"; package example_with_gnostic; import "gnostic/openapi/v3/annotations.proto"; option (gnostic.openapi.v3.document) = { info: { title: "Title from annotation"; version: "Version from annotation"; description: "Description from annotation"; contact: { name: "Contact Name"; url: "https://github.com/sudorandom/protoc-gen-connect-openapi"; email: "hello@sudorandom.com"; } license: { name: "MIT License"; url: "https://github.com/sudorandom/protoc-gen-connect-openapi/blob/master/LICENSE"; } } components: { security_schemes: { additional_properties: [ { name: "BasicAuth"; value: { security_scheme: { type: "http"; scheme: "basic"; } } } ] } } }; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello(HelloRequest) returns (HelloReply) { option idempotency_level = NO_SIDE_EFFECTS; option (gnostic.openapi.v3.operation) = { deprecated: true, security: [ { additional_properties: [ { name: "BasicAuth"; value: { value: [] } } ] } ] }; } } // The request message containing the user's name. message HelloRequest { option (gnostic.openapi.v3.schema) = {title: "Custom title for a message"}; string name = 1 [(gnostic.openapi.v3.property) = {title: "Custom title for a field"}]; } // The response message containing the greetings message HelloReply { string message = 1; } ``` -------------------------------- ### Run All Tests Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Execute all tests using standard Go tooling. This command runs tests across all packages. ```shell go test ./... ``` -------------------------------- ### Generated OpenAPI Schema from Protobuf with Protovalidate Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/06-features-validation-visibility.md The OpenAPI schema generated from the example Protobuf message, reflecting the Protovalidate constraints as OpenAPI schema properties like format, minLength, maxLength, minimum, maximum, minItems, and maxItems. ```yaml User: type: object properties: email: type: string format: email name: type: string minLength: 1 maxLength: 100 age: type: integer minimum: 0 maximum: 150 tags: type: array minItems: 0 maxItems: 10 items: type: string ``` -------------------------------- ### Basic Protoc Usage Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Compile a proto file using protoc with the connect-openapi plugin. This is the simplest way to generate OpenAPI definitions from your protobuf services. ```shell protoc internal/converter/fixtures/helloworld.proto --connect-openapi_out=gen ``` -------------------------------- ### HTTP Method Annotations for RESTful Mappings Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/06-features-validation-visibility.md Defines standard REST methods (GET, POST, PATCH, DELETE) using google.api.http annotations within Protobuf service definitions. Specifies resource paths and request bodies. ```protobuf import "google/api/annotations.proto"; service Users { rpc GetUser(GetUserRequest) returns (User) { option (google.api.http) = { get: "/v1/users/{user_id}" }; } rpc CreateUser(CreateUserRequest) returns (User) { option (google.api.http) = { post: "/v1/users" body: "*" }; } rpc UpdateUser(UpdateUserRequest) returns (User) { option (google.api.http) = { patch: "/v1/users/{user_id}" body: "user" }; } rpc DeleteUser(DeleteUserRequest) returns (Empty) { option (google.api.http) = { delete: "/v1/users/{user_id}" }; } } ``` -------------------------------- ### Add Dependency Source Files Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Use `WithSourceFiles` to add protobuf files as dependencies without generating OpenAPI for them. This is useful for managing complex project structures. ```go converter.GenerateSingle( converter.WithSourceFiles(dependencyRegistry), converter.WithFiles(mainRegistry), ) ``` -------------------------------- ### Generate OpenAPI using buf (CLI) Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/00-index.md This command shows how to use buf, a popular Protocol Buffers development tool, to generate OpenAPI specifications. ```bash # Using buf buf generate ``` -------------------------------- ### Append Service Documentation Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/03-internal-converter.md Appends documentation for services within a protobuf file to the info description of an OpenAPI document. This function only runs if service descriptions are enabled. ```go func appendServiceDocs(opts options.Options, spec *v3.Document, fd protoreflect.FileDescriptor) error { // ... implementation details ... return nil } ``` -------------------------------- ### Add Path Items from Protobuf File Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/03-internal-converter.md Generates HTTP path items for all services within a protobuf file. It prioritizes google.api.http annotations, falls back to ConnectRPC, and optionally supports Twirp. ```go func addPathItemsFromFile(opts options.Options, fd protoreflect.FileDescriptor, doc *v3.Document) error { // Implementation details omitted for brevity return nil } ``` -------------------------------- ### Basic Service Definition Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md A fundamental Protobuf service definition for user management, including messages and RPC methods. ```protobuf syntax = "proto3"; package company.users.v1; // User represents a user account message User { // User ID (unique) string id = 1; // User's email address string email = 2; // User's display name string name = 3; } // Request to get a user message GetUserRequest { // User ID to fetch string user_id = 1; } // UserService provides user management operations service UserService { // Get a user by ID rpc GetUser(GetUserRequest) returns (User) {} // Create a new user rpc CreateUser(User) returns (User) {} // Update an existing user rpc UpdateUser(User) returns (User) {} // Delete a user rpc DeleteUser(GetUserRequest) returns (Empty) {} } ``` -------------------------------- ### Combine Multiple Options Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Apply multiple configuration options simultaneously by separating them with commas. This allows for flexible customization of the OpenAPI generation. ```bash protoc \ --connect-openapi_out=gen \ --connect-openapi_opt=format=json,allow-get,path-prefix=/api/v2 \ service.proto ``` -------------------------------- ### Protoc Usage with Base File and Content Types Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Generate OpenAPI definitions using a base file and specifying allowed content types. This allows for customization and control over the generated OpenAPI output. ```shell protoc internal/converter/fixtures/helloworld.proto \ --connect-openapi_out=gen \ --connect-openapi_opt=base=example.base.yaml,content-types=json ``` -------------------------------- ### Service Definition with Visibility Annotations Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md A Protobuf service definition demonstrating visibility controls using google.api.visibility annotations for fields and methods. ```protobuf syntax = "proto3"; package company.users.v1; import "google/api/visibility.proto"; import "google/api/client.proto"; message User { option (google.api.api_visibility).restriction = "PUBLIC"; string id = 1 [(google.api.visibility).restriction = "PUBLIC"]; string email = 2 [(google.api.visibility).restriction = "PUBLIC"]; string internal_notes = 3 [(google.api.visibility).restriction = "INTERNAL"]; } service UserService { option (google.api.api_visibility).restriction = "PUBLIC"; rpc GetUser(GetUserRequest) returns (User) { option (google.api.method_visibility).restriction = "PUBLIC"; } rpc AdminGetUser(GetUserRequest) returns (User) { option (google.api.method_visibility).restriction = "INTERNAL"; } } ``` -------------------------------- ### Generate OpenAPI from Connect Services Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/00-index.md Use this workflow to generate a single OpenAPI specification file from your Connect services. Ensure the output path and OpenAPI file name are specified. ```bash protoc \ --connect-openapi_out=gen \ --connect-openapi_opt=path=api.openapi.yaml \ --connect-openapi_opt=allow-get \ api/v1/*.proto ``` -------------------------------- ### Programmatic Integration with Go Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/00-index.md Import the converter package to use protoc-gen-connect-openapi programmatically within your Go applications. This allows for custom generation logic. ```go import "github.com/sudorandom/protoc-gen-connect-openapi/converter" ``` -------------------------------- ### NewOptions Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/02-configuration-options.md Creates a new Options struct with sensible defaults. The defaults include format, content types, enabled features, and logger settings. ```APIDOC ## NewOptions ### Description Creates a new Options struct with sensible defaults. ### Signature ```go func NewOptions() Options ``` ### Returns - `Options` — Initialized with default values ### Defaults - Format: "yaml" - ContentTypes: {"json": {}} - EnabledFeatures: ConnectRPC, GoogleAPIHTTP, Gnostic, Protovalidate - Logger: Discard handler ### Example ```go opts := converter.NewOptions() opts.Format = "json" opts.AllowGET = true ``` ``` -------------------------------- ### ConvertFrom Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/03-internal-converter.md Reads a protoc plugin request from a reader and converts it to an OpenAPI specification. This is the primary entrypoint for reading input from stdin. ```APIDOC ## ConvertFrom ### Description Reads a protoc plugin request from a reader and converts it to an OpenAPI specification. ### Signature ```go func ConvertFrom(rd io.Reader) (*pluginpb.CodeGeneratorResponse, error) ``` ### Parameters #### Path Parameters - **rd** (io.Reader) - Required - Reader containing protobuf-encoded CodeGeneratorRequest ### Returns - `*pluginpb.CodeGeneratorResponse` — Generated OpenAPI files - `error` — Parsing or conversion error ### Behavior - Reads all data from reader - Unmarshals as protobuf CodeGeneratorRequest - Calls Convert() with parsed request - Uses default logger (slog.Default) ### Example ```go import ( "os" "github.com/sudorandom/protoc-gen-connect-openapi/internal/converter" ) func main() { resp, err := converter.ConvertFrom(os.Stdin) if err != nil { log.Fatal(err) } // Use resp.File to output OpenAPI files } ``` ``` -------------------------------- ### Generate OpenAPI from Global Registry Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Use `WithGlobal` as a shortcut to generate OpenAPI specs for all services in the global protobuf registry. This option requires no parameters. ```go content, err := converter.GenerateSingle( converter.WithGlobal(), ) ``` -------------------------------- ### Production Configuration Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Configure the generator for a production environment with JSON output format and trimmed unused types. ```go converter.GenerateSingle( converter.WithGlobal(), converter.WithFormat("json"), converter.WithTrimUnusedTypes(true), converter.WithShortServiceTags(true), converter.WithShortOperationIds(true), converter.WithPathPrefix("/api/v1"), ) ``` -------------------------------- ### WithGlobal Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Generates OpenAPI specs for all services in the protobuf global registry. This is a convenient shortcut for including all globally registered Protobuf files. ```APIDOC ## WithGlobal ### Description Generates OpenAPI specs for all services in the protobuf global registry. Shortcut for `WithFiles(protoregistry.GlobalFiles)`. ### Method func WithGlobal() Option ### Request Example ```go content, err := converter.GenerateSingle( converter.WithGlobal(), ) ``` ``` -------------------------------- ### Run Tests with Just Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md An alternative command to run all tests using the 'just' task runner. This provides a convenient way to execute the test suite. ```shell just test ``` -------------------------------- ### Prepend Path Prefix to OpenAPI Paths Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Use WithPathPrefix to add a specified string to the beginning of all HTTP paths in the generated OpenAPI specification. ```go converter.GenerateSingle( converter.WithGlobal(), converter.WithPathPrefix("/api/v1"), ) ``` -------------------------------- ### Initialize OpenAPI Components Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/03-internal-converter.md Ensures all component collections within an OpenAPI document are initialized. This function creates ordered maps for various component types. ```go func initializeComponents(opts options.Options, components *v3.Components) error { // ... implementation details ... return nil } ``` -------------------------------- ### Generate OpenAPI from Global Registry Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Use this to generate an OpenAPI specification from the global protobuf registry. The output is written to 'api.openapi.yaml'. ```go package main import ( "log" "os" "github.com/sudorandom/protoc-gen-connect-openapi/converter" ) func main() { content, err := converter.GenerateSingle( converter.WithGlobal(), ) if err != nil { log.Fatal(err) } // Write to file if err := os.WriteFile("api.openapi.yaml", content, 0644); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Generate Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Generates OpenAPI files for the provided protobuf files. By default, it creates one file per input proto file, but can merge into a single file if a path is specified. It returns generated files in the protobuf plugin format. ```APIDOC ## Generate ### Description Generates OpenAPI files for the provided protobuf files. By default, it creates one file per input proto file, but can merge into a single file if a path is specified. It returns generated files in the protobuf plugin format. ### Signature ```go func Generate(opts ...Option) ([]*pluginpb.CodeGeneratorResponse_File, error) ``` ### Parameters #### Options - `opts` (...Option) - Variable number of configuration options. These options configure the generation behavior, such as format, content types, and output path. ### Return Type - `[]*pluginpb.CodeGeneratorResponse_File` — List of generated files, where each file contains its name and content in protobuf plugin format. - `error` — Error if generation fails. ### Behavior - Creates multiple output files by default (one per input proto file). - Use `WithPath` option to merge into a single file. - Returns files in protobuf plugin format suitable for use in protoc plugins. ### Example ```go package main import ( "fmt" "github.com/sudorandom/protoc-gen-connect-openapi/converter" "google.golang.org/protobuf/reflect/protoregistry" ) func main() { files, err := converter.Generate( converter.WithGlobal(), converter.WithFormat("json"), converter.WithContentTypes("json", "proto"), ) if err != nil { fmt.Println("Error:", err) return } for _, file := range files { fmt.Printf("Generated: %s\n", *file.Name) // Use file.Content to write to disk } } ``` ``` -------------------------------- ### Generate OpenAPI from Protobuf (CLI) Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/00-index.md Use this command to generate an OpenAPI specification from a protobuf file using the protoc compiler. ```bash # Generate from protobuf protoc --connect-openapi_out=gen service.proto ``` -------------------------------- ### Enable All Features Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/README.md Use this feature to enable all available features, including ConnectRPC, google.api.http, Twirp, Gnostic, and Protovalidate. This provides comprehensive support for various RPC styles and OpenAPI annotations. ```yaml opt: - features=connectrpc;google.api.http;twirp;gnostic;protovalidate ``` -------------------------------- ### Generate OpenAPI with Base and Override Documents Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Combine a base OpenAPI document with an override document for generation. This allows for pre-existing definitions to be merged with generated ones. The result is saved to 'api.openapi.yaml'. ```go package main import ( "log" "os" "github.com/sudorandom/protoc-gen-connect-openapi/converter" ) func main() { baseContent, err := os.ReadFile("base.yaml") if err != nil { log.Fatal(err) } overrideContent, err := os.ReadFile("override.yaml") if err != nil { log.Fatal(err) } content, err := converter.GenerateSingle( converter.WithGlobal(), converter.WithBaseOpenAPI(baseContent), converter.WithOverrideOpenAPI(overrideContent), ) if err != nil { log.Fatal(err) } os.WriteFile("api.openapi.yaml", content, 0644) } ``` -------------------------------- ### Go Function for Path Item Annotations Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/06-features-validation-visibility.md Applies Gnostic method-level annotations to OpenAPI path items, including external documentation, responses, security, and callbacks. ```go func PathItemWithMethodAnnotations(opts options.Options, item *v3.PathItem, method protoreflect.MethodDescriptor) *v3.PathItem ``` -------------------------------- ### Enable Specific Features Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/06-features-validation-visibility.md Use the `WithFeatures` option to enable specific features like `FeatureProtovalidate` and `FeatureGnostic`. This allows granular control over the generated code. ```go converter.GenerateSingle( converter.WithGlobal(), converter.WithFeatures( options.FeatureProtovalidate, options.FeatureGnostic, ), ) ``` -------------------------------- ### Enable Streaming Support in Schema Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Use WithStreaming to include content types and schemas related to streaming RPC calls. Be aware that enabling this can lead to verbose OpenAPI output. This option is disabled by default. ```go converter.GenerateSingle( converter.WithGlobal(), converter.WithStreaming(true), ) ``` -------------------------------- ### Merge Multiple Services into a Single Output File Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/07-usage-examples.md Consolidate OpenAPI specifications from multiple service definition files into a single output file. Specify the desired output path using the 'path' option. ```bash protoc \ --connect-openapi_out=gen \ --connect-openapi_opt=path=api.openapi.yaml \ service1.proto service2.proto service3.proto ``` -------------------------------- ### Generate Multiple OpenAPI Files Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Use `Generate` to create OpenAPI specification files for provided protobuf definitions. By default, it generates one file per input proto. Configure output format (JSON/YAML) and content types using functional options. The output is in protobuf plugin format. ```go package main import ( "fmt" "github.com/sudorandom/protoc-gen-connect-openapi/converter" "google.golang.org/protobuf/reflect/protoregistry" ) func main() { files, err := converter.Generate( converter.WithGlobal(), converter.WithFormat("json"), converter.WithContentTypes("json", "proto"), ) if err != nil { fmt.Println("Error:", err) return } for _, file := range files { fmt.Printf("Generated: %s\n", *file.Name) // Use file.Content to write to disk } } ``` -------------------------------- ### WithFiles Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Generates OpenAPI specs for the given protobuf files and their dependencies. This is the primary option for specifying which Protobuf files should be processed for OpenAPI generation. ```APIDOC ## WithFiles ### Description Generates OpenAPI specs for the given protobuf files and their dependencies. ### Method func WithFiles(files *protoregistry.Files) Option ### Parameters #### Path Parameters - **files** (`*protoregistry.Files`) - Required - Protobuf file registry to generate from ### Request Example ```go content, err := converter.GenerateSingle( converter.WithFiles(myRegistry), ) ``` ``` -------------------------------- ### Enable Google Error Details in Responses Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/01-public-api-converter.md Use WithGoogleErrorDetail to enable the generation of error details using google.rpc error_details.proto in error responses. ```go converter.GenerateSingle( converter.WithGlobal(), converter.WithGoogleErrorDetail(true), ) ``` -------------------------------- ### Generate Field Description with Type Annotations Source: https://github.com/sudorandom/protoc-gen-connect-openapi/blob/main/_autodocs/05-utility-functions.md Creates a field description including comments and optional protobuf type annotations (for messages, enums, or scalars) based on configuration. ```go desc := util.TypeFieldDescription(opts, field) // Result: "User ID (proto uint64)" ```