user1438150
user1438150

Reputation: 175

JSON response redirect

An Employee has many PartyInvites and a Party has many PartyInvites. I would like a controller method to accept a party invite. If controller PartyInvites has this (update) method that assigns an Employee to a Party, which controller is responsible for returning the Party Object?

Maybe I misinterpreted JSON REST API's but if you are working with a specific resource (in this case PartyInvite) then could we return something that the client isn't expecting (a Party). Maybe I'm overthinking this all. But is this what a redirect should be used for to redirect the PartyInvite controller to a Party controller when the PartyInvite has been accepted?

Upvotes: 1

Views: 1149

Answers (2)

Tobias
Tobias

Reputation: 4653

I wouldn't recommend you to create redirects in a RESTful API since it wouldn't be a conventional REST API anymore.

The client should always get the requested resource with the proper status code back.

However it's possible to redirect the client even in an API. You just have to provide a 3xx Status Code and a Location in your response header. Then the client has to create a new request to the API.

I see only two issues there:

  • Normally you would return a 201 status if a resource was created in a RESTful API. But since the client was redirected this status can't be used. (This information can be of course also in the body of the response).

  • Every client has to be able to handle redirects. If this API is public you should explicitly say in your Documentation that the API redirects to other locations.

The better solution is to embed the Party in the PartyInvite:

Example:

{
  "id": 12425124,
  "invitee_count": 15,
  "party": {
    "id": 1252,
    "location": "Wallstreet 10",
    "and_so_on": "..."
  }
}

This is the RESTful way to return nested resources.

But of course you can also use 3xx HTTP Status Codes to redirect the client to another resource, but be sure that the client understands the response.

Upvotes: 2

TheGeorgeous
TheGeorgeous

Reputation: 4061

Yes. Party Invite update can redirect to the specific Party's show controller and return a Party matching the Invite. Of course you can do this with the PartyInvite itself, and the client using the API can adjust accordingly. However, that undermines the RESTfulness of the API

Upvotes: 0

Related Questions