Reputation: 413
I have a REST route to create a resource that uses path parameters.
The answer given here: https://stackoverflow.com/a/26094619/2436002 shows how to easily create a proper location header for the response using the UriInfo Context.
@Path("/resource/{type}")
public class Resource {
@POST
public Response createResource(@PathParam("type") String type, @Context UriInfo uriInfo)
{
UUID createdUUID = client.createResource(type);
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(createdUUID.toString());
return Response.created(builder.build()).build();
}
}
However, this includes the path parameters in the received URI, which will not lead to the proper resource.
POST: http://localhost/api/resource/{type} with pathparam type = "system"
will return http://localhost/api/resource/system/123 (123 being the generated id) while the proper URI would be http://localhost/api/resource/123
So, how can I get the proper resource location to return?
Upvotes: 1
Views: 1181
Reputation: 209072
Yeah, doing it the way in the link, you assume a parent child relationship, where you are posting to a collection endpoint and a child single resource is created. With your use case, this isn't the case. One way you can make it work is to just use UriBuilder.fromResource()
. Then just call resolveTemplate()
to put in the value for "type"
.
URI createdUri = UriBuilder.fromResource(Resource.class)
.resolveTemplate("type", createdUUID.toString()).build();
return Response.created(uri).build();
This will give you http://localhost/api/resource/123
Upvotes: 2