Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting with a 201 created

Is there a way to redirect through a 201 answer?

The RFC specifies that the newly created resource must be specified in the Location header, and I do specify it. I assumed that the browser would redirect but it doesn't, even if the page has no content.

I want the user, after the POST action, to get redirected to the new resource. I'm therefore tempted to use 303 See Other but a 201 seems more appropriate.

So, is there any way to automatically redirect popular browsers without user intervention and without relying on Javascript?

like image 805
Thomas Bonini Avatar asked Jan 03 '11 13:01

Thomas Bonini


People also ask

What is a 201 redirect?

It is primarily used to allow the output of a POST action to redirect the user agent to a selected resource, since doing so provides the information corresponding to the POST response in a form that can be separately identified, bookmarked, and cached, independent of the original request.

What does HTTP Status 201 created indicate in restful API?

The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource.

What is a 201 status code?

What Is a 201 Status Code? The request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI.


2 Answers

I think you're confusing two different semantic responses - one is telling the client that you successfully created a resource, and where it is. Whether the client goes to fetch it or not is a different story.

The second is telling the client that it has sent the wrong location URI for a resource it's requesting - and that it should try again, but with a different URI.

A 303 is appropriate in this case - in fact, it's explicitly recommended for this:

(from rfc)

It is primarily used to allow the output of a POST action to redirect the user agent to a selected resource, since doing so provides the information corresponding to the POST response in a form that can be separately identified, bookmarked, and cached, independent of the original request.

like image 176
Kylar Avatar answered Sep 21 '22 21:09

Kylar


The browser will enact a redirect action through one of the 3xx status codes, the specification doesn't define that a user agent must redirect with a 201. You could try sending a refresh header to see if it forces a redirect to the Location header, but I wouldn't count on it. Why not stick with a 3xx response?

like image 43
Matthew Abbott Avatar answered Sep 18 '22 21:09

Matthew Abbott