Create a correct 201 Created response with JAX-RS

@POST
@Path("project")
public Response createProject(@Context UriInfo uriInfo, JsonObject json) {
        Project project = projectConverter.fromJson(json);
        project.setWorkspace(getCurrentWorkspace());
        project = em.merge(project);

        URI uri = uriInfo.getBaseUriBuilder()
                .path(ProjectResource.class)
                .resolveTemplate(PathExpressions.workspaceId, getCurrentWorkspace().getId())
                .resolveTemplate(PathExpressions.projectId, project.getId())
                .build();

        return Response.created(uri).build();
The @Context UriInfo uriInfo provides information about the current URI. 
The .path(ProjectResource.class)  call will return the path used for the ProjectResource.class. 
The .resolveTemplate("{workspaceId:\\d+}", getCurrentWorkspace().getId())  will replace the workspaceId template variable for the actual wokspace id.

Once the whole path has been created, it is only needed to put it into a created response.

Leave a Reply