85

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?

Shoham
  • 7,014
  • 8
  • 40
  • 40

1 Answers1

146

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;
}
Shoham
  • 7,014
  • 8
  • 40
  • 40
  • 4
    I'm late for the party, but: Does option 2 have any advantages over option 1 or vice versa? – LuMa Sep 25 '17 at 09:08
  • 31
    Option 1 is a stream, it means you are returning an iterator and that means you can start processing the Items on client even before the server has finished sending all of them. Option 2 is a response object which contains a list of your Items. You can add some other properties to your ItemResponse (some metadata etc)... – Shoham Sep 26 '17 at 08:23
  • 1
    Hi, Is there anyway we can return a key less array response as the response in gRPC? I tried stream, but it doesn't help. – Jaward Sally May 24 '21 at 14:02
  • 1
    Works wine with: ```message GetChannelsResponse {repeated string channel_name = 1;}``` – Vladimir Jul 02 '21 at 09:18
  • Is there a way to return an array instead of an array wrapped by an object? i.e. [{},{}] instead of {[{}]}. – emeraldhieu Jul 03 '23 at 05:33