How to return an array in Protobuf service rpc

Protocol BuffersRpc

Protocol Buffers Problem Overview


I have the following schema in my .proto file:

service MyService {
    rpc GetItem (ItemQuery) returns (Item) {
    }
}

message ItemQuery {
    int id = 1;
}
message Item {
    int id = 1;
    string name = 2;
}

Now I want to add another rpc method to return multiple Items. Something like this:

rpc GetItems (ItemsQuery) returns (repeated Item) {
}

Is there a better way to do it than define an Items message?

Protocol Buffers Solutions


Solution 1 - Protocol Buffers

Option 1 - Use stream:

rpc GetItems (ItemsQuery) returns (stream Item) {
}

Option 2 - Set a response message which will use a repeated object:

service MyService {
    rpc GetItem (ItemQuery) returns (ItemResponse) {
    }
}

message ItemQuery {
    int id = 1;
}
message ItemResponse {
    repeated Item items = 1;
}
message Item {
    int id = 1;
    string name = 2;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShohamView Question on Stackoverflow
Solution 1 - Protocol BuffersShohamView Answer on Stackoverflow