Passing parameters to a RESTful web service

You successfully connected to that RESTful web service and already got a couple of data from it. But now you want to send some parameters to your service.

Here I’ll describe how RESTful web services receive parameters, so you can better undestand how to send them from your application.

RESTful web services are quite flexible when it comes to parameters passing. You just need to know, from the web service API, how it is expecting to receive the parameters.

So lets cut to the chase and list the possible ways of doing it!

Query Parameters

The web service extracts query parameters from the Query component of the request URL.

As calling a RESTful web service is just a call to a URL, you just need to add parameters to the URL as you would normally do for a Servlet.

Example:

Calling the web service:  http://www.myserver.com/rest/myservice/query?param1=value1&param2=value2…

How the web service will get the parameters:

@GET
@Path("/query")
@Produces(MediaType.TEXT_HTML)
public Response getMessageQueryParam(@QueryParam("param1") String param1,
        @QueryParam("param2") String param2,
        @QueryParam("param3") String param3){

    // Store the message

}

Path Parameters

The web service extracts the parameters from the Path component of the URL.

This one can be tricky because it needs to obay exactly what was defined by the web service implementation.

You will have the default web service path, then you can pass parameters separated by a slash.

Example:

Calling the web service: http://www.myserver.com/rest/myservice/param1/param2/param3

How the web service will get the parameters:

@GET
@Path("{param1}/{param2}/{param3}")
@Produces(MediaType.TEXT_HTML
public Response getMessagePathParam(@PathParam("param1") String param1,
        @PathParam("param2") String param2,
        @PathParam("param3") String param3){

    // Store the message

}

Matrix Parameters

The web service extracts information from URL path segments.

Example:

Calling the web service: http://www.myserver.com/rest/myservice/matrix;param1=value1;param2=value2…

How the web service will get the parameters:

@GET
@Path("/matrix")
@Produces(MediaType.TEXT_HTML)
public Response getMessageMatrixParam(@MatrixParam("param1") String param1,
        @MatrixParam("param2") String param2,
        @MatrixParam("param3") String param3){

    // Store the message

}

Header Parameters

The web service extracts information from the HTTP headers.

Example:

Calling the web service: http://www.myserver.com/rest/myservice/header

How the web service will get the parameters:

@GET
@Path("/header")
@Produces(MediaType.TEXT_HTML)
public Response getMessageHeaderParam(@HeaderParam("user-agent") String userAgent){

    // Store the message

}

Note that I’m getting the header parameter by the same name it appears in the header itself.

Cookie Parameters

The web service extracts information from the cookies declared in cookie related HTTP headers.

Example:

Calling the web service: http://www.myserver.com/rest/myservice/cookie

How the web service will get the parameters:

@GET
@Path("/cookie")
@Produces(MediaType.TEXT_HTML)
public Response getMessageCookieParam(@CookieParam("Last-Accessed") String lastAccessed){

    // Store the message

}

Form Parameters

The Form Parameter is slightly special because it extracts information from a request representation that is of the MIME media type “application/x-www-form-urlencoded” and conforms to the encoding specified by HTML forms, as described here. This parameter is very useful for extracting information that is POSTed by HTML forms, for example the following extracts the form parameter named “name” from the POSTed form data:

Calling the web service from your form:


  
	<h1>JAX-RS @FormQuery Testing</h1>

	
		<p>
			Name : 
		</p>
		<p>
			Age : 
		</p>
		
	

  

Example: Processing POSTed HTML form

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name){

    // Store the message

}

If it is necessary to obtain a general map of parameter name to values then, for query and path parameters it is possible to do the following:

Example: Obtaining general map of URI path and/or query parameters

@GET
public String get(@Context UriInfo ui) {

    MultivaluedMap queryParams = ui.getQueryParameters();
    MultivaluedMap pathParams = ui.getPathParameters();

}

For header and cookie parameters the following:

Example: Obtaining general map of header parameters

@GET
public String get(@Context HttpHeaders hh) {

    MultivaluedMap headerParams = hh.getRequestHeaders();
    Map pathParams = hh.getCookies();

}

In general @Context can be used to obtain contextual Java types related to the request or response.

Because form parameters (unlike others) are part of the message entity, it is possible to do the following:

Example: Obtaining general map of form parameters

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(MultivaluedMap formParams) {

// Store the message

}

I.e. you don’t need to use the @Context annotation.

Another kind of injection is the @BeanParam which allows to inject the parameters described above into a single bean. A bean annotated with @BeanParam containing any fields and appropriate *param annotation(like @PathParam) will be initialized with corresponding request values in expected way as if these fields were in the resource class. Then instead of injecting request values like path param into a constructor parameters or class fields the @BeanParam can be used to inject such a bean into a resource or resource method. The @BeanParam is used this way to aggregate more request parameters into a single bean.

Example: Example of the bean which will be used as @BeanParam

public class MyBeanParam {
    @PathParam("p")
    private String pathParam;

    @MatrixParam("m")
    @Encoded
    @DefaultValue("default")
    private String matrixParam;

    @HeaderParam("header")
    private String headerParam;

    private String queryParam;

    public MyBeanParam(@QueryParam("q") String queryParam) {
        this.queryParam = queryParam;
    }

    public String getPathParam() {
        return pathParam;
    }
    ...
}

Example: Injection of MyBeanParam as a method parameter:

@POST
public void post(@BeanParam MyBeanParam beanParam, String entity) {

    final String pathParam = beanParam.getPathParam(); // contains injected path parameter "p"
    ...
}

The example shows aggregation of injections @PathParam, @QueryParam @MatrixParam and @HeaderParam into one single bean. The rules for injections inside the bean are the same as described above for these injections. The @DefaultValue is used to define the default value for matrix parameter matrixParam. Also the @Encodedannotation has the same behaviour as if it were used for injection in the resource method directly. Injecting the bean parameter into @Singleton resource class fields is not allowed (injections into method parameter must be used instead).

@BeanParam can contain all parameters injections injections (@PathParam, @QueryParam, @MatrixParam, @HeaderParam, @CookieParam, @FormParam). More beans can be injected into one resource or method parameters even if they inject the same request values. For example the following is possible:

Example: Injection of more beans into one resource methods:

@POST
public void post(@BeanParam MyBeanParam beanParam, @BeanParam AnotherBean anotherBean,
        @PathParam("p") pathParam, String entity) {

    // beanParam.getPathParam() == pathParam
    ...
}

Hope it helps!

Thanks!

Advertisements

12 thoughts on “Passing parameters to a RESTful web service”

    1. Hi Shawn,

      I did not understand your question, you want to send a URL inside a JSON or do you want to pass json on the url as a parameter?
      If you mean the latter you probably can do that but that doesn mean you should. eEther choose path or query parameters for passing data through the URL or use form parameters.
      Hope I could help.

      Thank you for reading!

      1. Thanks for the quick reply:

        I’m trying to submit (Infopath2013 form) to a webservice that is in JSON format. The problem is that InfoPath is submitting in XML format and I’m getting an error that it can’t find the Media Type – so I’m assuming it’s because of the format. So I was thinking I could do something like this:

        http://www.myservice.com/rest/test?$format=JSON

      2. I see, you should not do that, are you using any specific framework? It is usually very simple to send the JSON through the request body.

  1. Hello Dear Vrsbrazil.. I am very new in REST Webservices. I am a bit stuck in passing two int parameter to a webservice as matrix sizes. The webservice will generate to random matrices of that size and then will multiply both. The resulted matrix need to return back to client. My quesiton is , How cani pass two int parameters by getting text from my EditTexts in android prototype. What should be the URL=”?” i mean how to add these two parameters at the end of URL which will be getting from EditText. And while the webservice is going to return a JSON or XML format back, then how should I parse them to a plain_text? Is XMLParser or JsonParser necessary? Thanks

  2. Can I use @BeanParam for same object twice in a method ?
    For example :
    @BeanParam TimeOfDayInfo startTime;
    @BeanParam TimeOfDayInfo endTime;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s