REST响应-我应该将新资源的URL放在标头,正文还是在两者中? [英] REST response - should I put the URL of the new resource in the header, body, or both?

查看:64
本文介绍了REST响应-我应该将新资源的URL放在标头,正文还是在两者中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整理了一个API,该API通过将新资源的内容放在响应正文中并将新资源的URL放在Location HTTP响应标头中来响应POST请求.

I have put together an API that responds to a POST request by putting the content of the new resource in the response body, and the URL of the new resource in the Location HTTP response header.

样品请求:

POST /api/v1/widgets HTTP/1.1
Content-type: application/json;
Accept: application/json;

{
    "name": "hugo@example.com",
    "price": "10",
}

示例响应:

HTTP 201 Created
Location: http://example.com/api/v1/widgets/123456

{
    'widget': 
    {
        'id': "123456",
        'created': "2012-06-22T12:43:37+0100",
        'name': "hugo@example.com",
        'price': "10",
    },
}

有人提出了一个问题,即URL也应包含在响应的正文中.在这方面有最佳实践吗?

Someone has raised an issue that the URL should also be in the body of the response. Is there a best practice on this?

推荐答案

我将其放在标题中(作为位置: http://blah.blah.com/blah ).如果需要的话,也可以将它放在体内(以您要发送的任何适当格式),并且不会不合适.

I would put it in the header (as Location: http://blah.blah.com/blah). You could put it in your body as well if you want (in whatever appropriate format you are sending), and it wouldn't be improper.

atompub REST API 通常是良好REST API的良好参考.他们把两者都放了.

The atompub REST API is usually a good reference for a good REST API. They put it in both.

HTTP/1.1 201 Created
Date: Fri, 7 Oct 2005 17:17:11 GMT
Content-Length: nnn
Content-Type: application/atom+xml;type=entry;charset="utf-8"
Location: http://example.org/edit/first-post.atom
ETag: "c180de84f991g8"  

<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <title>Atom-Powered Robots Run Amok</title>
  <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
  <updated>2003-12-13T18:30:02Z</updated>
  <author><name>John Doe</name></author>
  <content>Some text.</content>
  <link rel="edit"
      href="http://example.org/edit/first-post.atom"/>
</entry>

这篇关于REST响应-我应该将新资源的URL放在标头,正文还是在两者中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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