Consider the following example:
create new user
POST request for this url : www.example.com/accounts/checking/users
GET user detail
GET request for this url : www.example.com/accounts/checking/user/1
return resource for user with id 1.
Now my question is when I post to www.example.com/accounts/checking/users for a new user creation, a new user is created and its resource uri must be returned in the location header. I am having trouble building this uri using getAbsoluteURIbuilder method.
Here is what I have
@Path("/accounts)
public class AccountResourceService {
@Context
UriInfo uriInfo
//here 'type' can be checking or saving account
@GET
@PATH("{type}/user/{id}")
@Produces(MediaType.APPLICATION_JSON)
public class getUserInfo(final @PathParam("type") String type, @PathParam("id"), int id)
{
//return user-specific resource for the given id
}
@POST
@PATH("{type}/users")
@Produces(MediaType.APPLICATION_JSON)
public class CreateUser(final @PathParam("type") String type, AccountCreateRequest request)
{
if type.equals("checking"){
User user = createAccount(request);
URI uri = uriInfo.getAbsolutePathBuilder().path(user.getId().toString()).build();
System.out.println("created uri is " + uri.toString);
return Response.created(uri).build();
}
else {
//do something else
}
}
}
The uri I am returning in POST method above is
http://localhost:8080/accounts/checking/users/1 //note users
But the expected uri is
http://localhost:8080/accounts/checking/user/1 //not user
how can I get this to work?
Just to put all the comments into an answer
From a design perspective, I say you just get rid of the user resource path, and make it users/{id}. This is common and an accepted way. users is a collection resource. When you go to /users, you get the collection of users. When you go to users/234, you get the user with id 234, in that collection of users.
But sine you can change this, you can just build the uri with some string manipulation. Get the getAbsolutePath()
from the UriInfo
, then just remove the s
. Then you can create a new UriBuilder
with that string. As seen in the below example
@Path("/accounts")
public class AccountsResource {
@POST
@Path("/{type}/users")
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(@PathParam("type") String type,
@Context UriInfo uriInfo) {
String newUri = uriInfo.getAbsolutePath().toString();
newUri = newUri.substring(0, newUri.length() - 1);
UriBuilder builder = UriBuilder.fromPath(newUri);
URI uri = builder.path("1234").build();
return Response.created(uri).build();
}
}
This will return /accounts/checking/user/1234