Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST Java web service using protobuf [closed]

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!

like image 794
Mike Avatar asked Jan 10 '12 07:01

Mike


People also ask

Can Protobuf be used in REST API?

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.

Is gRPC better than REST API?

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.

Does gRPC work over HTTP?

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.

Does Protobuf use HTTP?

Protobufs work fine over HTTP in their native binary format.


2 Answers

The below two article shows you exactly this

  1. Using JAX-RS with Protocol Buffers for high-performance REST APIs
  2. RESTful Representation with Google Protocol Buffers and Jersey
like image 93
Aravind Yarram Avatar answered Oct 20 '22 01:10

Aravind Yarram


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.

like image 35
Amir Qayyum Khan Avatar answered Oct 20 '22 01:10

Amir Qayyum Khan