Reputation: 34207
I have a REST API service i maintain in java (over jersey, JAX-RS)
I want to support the following route in my service:
/api/v1/users/{userId}/cars
however, it concatinates to the class's @Path
annotation. e.g.
/api/v1/cars/api/v1/users/{userId}/cars
This is my service class:
@Path("api/v1/cars")
public class CarsService {
@GET
@Path("/api/v1/users/{userId}/cars")
public Response getUserCars(@PathParam("userId") Long userId) {
// ...
}
@GET
public Response getCars() {
// ...
}
}
Is there any way to override it?
Upvotes: 1
Views: 4521
Reputation: 130907
Note the following:
@Path
annotation in a class designates a root resource.@Path
annotation in a method designates a sub-resource of a root resource.When placed on methods, the @Path
annotation does not override the @Path
annotation of the class. JAX-RS/Jersey performs a hierarchical matching using the @Path
annotations.
So, you can try:
@Path("api/v1")
public class CarsService {
@GET
@Path("/cars")
public Response getCars() {
...
}
@GET
@Path("/users/{userId}/cars")
public Response getUserCars(@PathParam("userId") Long userId) {
...
}
}
However, have you considered using different resource classes?
@Path("api/v1/cars")
public class CarsService {
@GET
public Response getCars() {
...
}
}
@Path("api/v1/users")
public class UsersService {
@GET
@Path("{userId}/cars")
public Response getUserCars(@PathParam("userId") Long userId) {
...
}
}
For more details on resources, have a look at the documentation.
Upvotes: 6
Reputation: 400
You just should change the @Path annotation of the method to:
@Path("users/{userId}/cars")
In this way, the resulting path of concatenating the class and the method @Path annotations will produce your desired path.
Upvotes: -1