A HTTP PUT is handled by a method that is annotated with @PUT
.
@PUT
@Path("/foo/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response putAFoo(@PathParam("id") int theId, Foo theFoo) {
// Save theFoo which has theId or do what you want with it.
if (fooWasCreated) {
return Response.created("/foo/" + theId).build();
} else {
return Response.ok().build();
}
}
Why use PUT? Usually PUT is used to change the server side state of a known resource. If you can address a resource by the comple URI, you can use this URI to GET a representation of it. You can also PUT to this URL with a new representation of the resource.
PUT is also used to create a new resource if the ID is controlled by the server. A request
PUT /foo/123
can be used to
- overwrite
/foo/123
or - create
/foo/123
.
That is different from POST which is usually requested on the collection resource.
POST /foo/
with the representation of a new resource would cause the server to assign an ID to the new resource. The server would then return a response like this:
201 Created
Location: /foo/456