Achithra Prasad Sachinthaka Achithra Prasad Sachinthaka - 2 months ago 27
reST (reStructuredText) Question

Change URL pattern of rest API

@Path("/ftocservice")
public class RestService {

@Path("{f}")
@GET
@Produces("application/json")

public Response convertFtoCfromInput(@PathParam("f") float f)
throws Exception {

DbCon db = new DbCon();
ArrayList<Student> students = db.getStudentList();
JSONArray jsonArray = new JSONArray(students);

String result = jsonArray.toString();

return Response.status(200).entity(result).build();
}

}


I'm using above source code to generate rest API and user is requesting through the API as follows.

http://localhost:8080/RestExample/RestService/ftocservice/23


I need to change the request URL as follows.

http://localhost:8080/RestExample/RestService/ftocservice?f=23


Please help to change the source code to change request URL as given. Thanks

Answer

Change to use @QueryParam instead:

@Path("/ftocservice")
public class RestService {


  @GET
  @Produces("application/json")
  public Response convertFtoCfromInput(@QueryParam("f") float f)
        throws Exception {

    DbCon db = new DbCon();
    ArrayList<Student> students = db.getStudentList();
    JSONArray jsonArray = new JSONArray(students);

    String result = jsonArray.toString();

    return Response.status(200).entity(result).build();
  }
}

See this link for more info on parameter types in JAX-RS.

This tutorial by Mkyong.com is also quite nice.

Comments