Wednesday, April 27, 2016

Handling query parameters in microservices

For a quick introduction on how to write a microservice you could follow https://docs.wso2.com/display/MSF4J100/Creating+a+Microservice+as+an+OSGi+Bundle.

In this blog what i'm focusing is on how to handle/access query parameters of a request in terms on msf4j. For this you could use  io.netty.handler.codec.http.QueryStringDecoder of netty.

Suppose you have a method like below, in your micro service. This method will be called from a request like  .../serviceA/services?name=abc&id=123...
So you would need to extract those query parameter values, in order to retrieve the relevant services.

   @GET
    @Path("/")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response getQueriedResponse(@Context HttpRequest request) {
       
          QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());

       
          String id = decoder.parameters().get("id").get(0);
         String name = decoder.parameters().get("name").get(0);


       ........ Rest of the code...............................
}

As you can see above, you can pass the request's uri to QueryStringDecoder of netty. From there you could access the relevant query parameter values. Basically you could access any query parameter value by passing its name.

 String value = decoder.parameters().get(propertyName).get(0);