JSON 响应重定向 [英] JSON response redirect

查看:69
本文介绍了JSON 响应重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个Employee有很多PartyInvites,一个Party有很多PartyInvites.我想要一个控制器方法来接受派对邀请.如果控制器 PartyInvites 有这个(更新)方法将 Employee 分配给 Party,哪个控制器负责返回 Party 对象?>

也许我误解了 JSON REST API,但如果您正在使用特定资源(在本例中为 PartyInvite),那么我们是否可以返回客户端不期望的内容(派对).也许这一切都是我多虑了.但是,当 PartyInvite 被接受时,重定向是否应该用于将 PartyInvite 控制器重定向到 Party 控制器?

解决方案

我不建议您在 RESTful API 中创建重定向,因为它不再是传统的 REST API.

客户端应该总是以正确的状态码取回请求的资源.

但是,即使在 API 中也可以重定向客户端.您只需要提供一个3xx 状态代码和一个位置在您的响应标头中.然后客户端必须创建一个对 API 的新请求.

我只看到两个问题:

  • 如果资源是在 RESTful API 中创建的,通常您会返回 201 状态.但是由于客户端被重定向,因此无法使用此状态.(此信息当然也可以在响应正文中).

  • 每个客户端都必须能够处理重定向.如果此 API 是公开的,您应该明确在文档中说明 API 重定向到其他位置.

更好的解决方案是在PartyInvite中嵌入Party:

示例:

<代码>{身份证":12425124,"invitee_count": 15,派对": {身份证":1252,"location": "华尔街 10",等等": "..."}}

这是返回嵌套资源的RESTful方式.

但当然你也可以使用 3xx HTTP Status Codes 将客户端重定向到另一个资源,但要确保客户端理解响应.

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?

解决方案

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.

这篇关于JSON 响应重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆