You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于protoc-gen-openapi插件处理annotations.proto注解的技术问询

protoc-gen-openapi 对 annotations.proto 注解的支持

protoc-gen-openapi 完全支持识别并处理 annotations.proto(通常指谷歌官方的 google/api/annotations.proto)中定义的自定义注解,能将这些注解转换为符合 OpenAPI v3 规范的文档内容。具体操作步骤如下:

  • 引入依赖 proto 文件
    在自定义 proto 文件顶部引入必要的依赖:

    syntax = "proto3";
    
    import "google/api/annotations.proto";
    import "google/api/http.proto";
    
    package your.package;
    
  • 在 proto 中使用注解
    直接使用 annotations.proto 里的自定义选项,比如给 RPC 方法绑定 HTTP 规则、标记字段必填性:

    service YourService {
      rpc GetItem(GetItemRequest) returns (GetItemResponse) {
        option (google.api.http) = {
          get: "/v1/items/{item_id}"
        };
        option (google.api.method_signature) = "item_id";
      }
    }
    
    message GetItemRequest {
      string item_id = 1 [(google.api.field_behavior) = REQUIRED];
    }
    
    message GetItemResponse {
      string id = 1;
      string name = 2;
      string description = 3;
    }
    
  • 生成 OpenAPI 文档
    执行 protoc 命令时指定 openapi 插件,示例命令:

    protoc --openapi_out=./openapi \
           --proto_path=./proto \
           ./proto/your_service.proto
    

    生成的 JSON/YAML 文件会自动映射注解到 OpenAPI 规范对应的字段,比如 HTTP 方法、路径、必填参数标识等。

注意事项:

  • 确保使用较新版本的 protoc-gen-openapi,旧版本可能对部分注解支持不足。
  • 插件核心支持谷歌官方 annotations.proto 定义的注解,第三方扩展注解需看插件是否适配。

内容的提问来源于stack exchange,提问作者shrekish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 02:42:04