user4296472
user4296472

Reputation:

How exactly works the @ResponseStatus Spring annotation for RESTful application?

I am studying for the Spring Core certification and I have some doubts about how Spring handles REST requests.

I know that with REST the resources are exposed as name and that the actions on these resources are the HTTP methods, such as GET, PUT, POST, and DELETE.

And I know that requests are handled by the use of @RequestMapping annotations over the method that handles the operation on the resource.

From what I have understood, both standard web applications and RESTful applications use some codes to communicate with their clients (the RESTful application have an expanded set of codes) that I think represent the status of the request (for example 200 is the request is a successful GET returning content, etc.).

Now the documentation shows the use of the @ResponseStatus annotation as in this example:

@RequestMapping(value="/orders", method=RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED) // 201
public void createOrder(HttpServletRequest request, HttpServletResponse response) {
    Order order = createOrder(request);
    // determine full URI for newly created Order based on request
    response.addHeader("Location",
    getLocationForChildResource(request, order.getId()));
}

So looking at the previous method I know that it handles HttpRequest POST requests towards the resource named /orders (using REST the resource is seen as an URL, is that correct?).

But what exactly does the annotation below do:

@ResponseStatus(HttpStatus.CREATED) // 201

I know that the 201 status code means that a new resource was created on POST.

And looking at the official documentation I can read:

Marks a method or exception class with the status code and reason that should be returned. The status code is applied to the HTTP response when the handler method is invoked, or whenever said exception is thrown.

So what exactly it means? I think that as is done in the previous example it sets the 201 status that says that the resource is correctly created by the POST request. If this is correct I have 2 questions:

  1. The resource is the /orders URI. So what is created? a file named orders (I think that this assertion is false) or what?

  2. Where the 201 status is put?

Upvotes: 10

Views: 13306

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279960

201 is an HTTP status code. It indicates that the

request has been fulfilled and resulted in a new resource being created.

If your server is returning such a status code, then the client understands that some (conceptual) resource was created. What that resource is is your responsibility, you're the server.

A status code is part of the HTTP response status line.

Upvotes: 4

Related Questions