I want to implement a REST web service using Java & protobuf.
Can anyone point me to where to start or how to implement it? Any good tutorial??
Thanks!
Yes, you can absolutely combine Protobuf and REST. Protbuf specifies a way to encode data. REST specifies a way to interact with resources, but does not require any particular encoding for the resource bodies.
REST APIs generally use JSON or XML message formats, while gRPC uses protocol buffers. To signal errors, REST APIs use HTTP status codes, while gRPC uses error codes. gRPC's message sizes tend to be dramatically smaller than those of REST APIs.
gRPC is designed for HTTP/2, a major revision of HTTP that provides significant performance benefits over HTTP 1. x: Binary framing and compression. HTTP/2 protocol is compact and efficient both in sending and receiving.
Protobufs work fine over HTTP in their native binary format.
The below two article shows you exactly this
You can see inside the post how we can create a JX-RS web service which is producing Google protocol Buffer in response. Source code is available at my blog
what I am doing is converting the protocol buffer object into byte array from server side and sending is array via service: Service code is below , populating object and putting it in response.
UserDTO.User user = UserDTO.User.newBuilder(). //protocol buffer object
setSessionId(id).
setName("l070020").
build();
return Response.ok(user.toByteArray(),MediaType.APPLICATION_OCTET_STREAM).status(200).build();
Protocol buffer object has ability to parse and populate populate the protocol buffer object via stream. So i am using by stream for data communication. On client side I am making connection to web service
HttpGet request = new HttpGet("http://localhost:8080/maven.work/service/mainServices/get_user");
request.addHeader("accept","application/octet-stream");
HttpResponse response = httpClient.execute(request);
Protocol buffer has built in method to parse stream, below I am parsing stream from the response
User user = User.parseFrom(response.getEntity().getContent());
Similarly you can send the protocol buffer object in the form of byte array to server and server can get it from HTTP Servlet Request stream and parse it same like the client is doing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With