JAX-RS @PathParam with Example – RESTful Web Services Tutorial

4 months ago codedestine 0

In JAX-RS @PathParam annotation is used to bind parameter value defined in the @Path ( URL ) expression to the method arguments. 

Let’s try to understand it with an example.

Example 1 :-

In this example, we will send one parameter ( book id ) in the @Path expression books/{id}. If we hit this URL <base URL>/books/1, The value 1 will get copy into @PathParam(“id”) String bookId variable.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("books")
public class PathParamExample {
 
   @GET
   @Produces(MediaType.TEXT_PLAIN)
   @Path("/{id}")
   public Response getBookById(@PathParam("id") String bookId){
       return Response.status(200)
                      .entity("Book id is : " + bookId).build();
   }
   
}

Result :-

JAX-RS @PathParam

Example 2 :-

In this example, we will send two parameters ( book name and chapter id ) in the @Path expression books/{name}/chapters/{id}. If we hit this URL <base URL>/books/JerseyBook/chapters/1, The value JerseyBook and 1 will get copy into @PathParam(“name”) String bookName variable and @PathParam(“id”) String chapterId variable respectively.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("books")
public class PathParamExample {
 
   @GET
   @Produces(MediaType.TEXT_PLAIN)
   @Path("/{name}/chapters/{id}")
   public Response getChapterOfBookById(@PathParam("name") String bookName,
                                        @PathParam("id") String chapterId){
	return Response.status(200)
               .entity("Book name is : " + bookName + " and chapter id is : " + chapterId).build();
   }
   
}

Result :-

JAX-RS @PathParam

References :-

  1. @PathParam Java Docs

That’s all for JAX-RS @PathParam with Example. If you liked it, please share your thoughts in comments section and share it with others too.