Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code java jersey REST API with multi-leveled resources?

Tags:

java

rest

jax-rs

I want to code a REST API that is multileveled like:

/country
/country/state/
/country/state/{Virginia}
/country/state/Virginia/city
/country/state/Virginia/city/Richmond

I have a single java class that is a Country resource with @Path("country")

How do I create a StateResource.java and CityResource.java so that my Countryresource can use the StateResource in the way I am planning to use it? Any useful links on how to construct this kind of thing in Java?

like image 452
Rolando Avatar asked Nov 29 '11 21:11

Rolando


1 Answers

The CountryResource class needs to have a method annotated with the @Path to the sub-resource CityResource. By default, you are responsible for creating the instance of CityResource e.g.

@Path("country/state/{stateName}")
class CountryResouce {

    @PathParam("stateName")
    private String stateName;

    @Path("city/{cityName}")
    public CityResource city(@PathParam("cityName") String cityName) {
        State state = getStateByName(stateName);

        City city = state.getCityByName(cityName);

        return new CityResource(city);
    }

}

class CityResource {

    private City city;

    public CityResource(City city) {
        this.city = city;
    }

    @GET
    public Response get() {
        // Replace with whatever you would normally do to represent this resource
        // using the City object as needed
        return Response.ok().build();
    }
}

CityResource provides the methods that handle the HTTP verbs (GET in this case).

You should look at the Jersey documentation regarding sub-resource locators for more info.

Also note that Jersey provides a ResourceContext to get it to instantiate the sub-resource. If you're going to use @PathParam or @QueryParam in the sub-resource I believe you need to use this as the runtime doesn't touch sub-resources when created yourself via new.

like image 92
Doug Moscrop Avatar answered Nov 15 '22 05:11

Doug Moscrop