chrusty / protoc-gen-jsonschema

Protobuf to JSON-Schema compiler
Apache License 2.0
496 stars 101 forks source link

Generating json schema for nested message #166

Closed pativa closed 9 months ago

pativa commented 1 year ago

Hi,

Thank you for this project. I've been using it to generate json schema and then from this generating a form for testing rpc services.

I'm wondering if there is any way to generate the schema for a proto that looks like this:

syntax = "proto3";

service ExampleService {
        rpc ExampleRpc (Namespace.ExampleRequest) returns (Namespace.ExampleResponse) {}
}

message Namespace {
        message ExampleRequest {
                string payload = 1;
        }

        message ExampleResponse {
                string payload = 1;
        }
}

My issue is that I can only get the following schema from this file:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "$ref": "#/definitions/Namespace",
    "definitions": {
        "Namespace": {
            "additionalProperties": true,
            "type": "object",
            "title": "Namespace"
        }
    }
}

Ideally, I would like to be able to run the command like this:

protoc --plugin=${HOME}/go/bin/protoc-gen-jsonschema --jsonschema_out="messages=[Namespace.ExampleRequest]:." example.proto

in order to generate the schema for Context.ExampleRequest, but this does not work.

Is there any way to generate the schema for a proto file formatted like this? Changing the original protofile is unfortunately not an option for me.

chrusty commented 9 months ago

Hello @pativa.

I'm fairly sure this would work if you included a package name, and made use of the nested schemas. At the moment your "Namespace" message just defines two nested messages, but doesn't make use of them. This converter will only create schemas for messages that are actually used. This example works:

syntax = "proto3";
package example;

service ExampleService {
        rpc ExampleRpc (Namespace.ExampleRequest) returns (Namespace.ExampleResponse) {}
}

message Namespace {
        message ExampleRequest {
                string payload = 1;
        }

        message ExampleResponse {
                string payload = 1;
        }

        ExampleRequest request = 1;
        ExampleResponse response = 2;
        string something_else = 3;
}