developer tip

응답 코드 200 또는 201 및 내용 인 POST로 요청을 작성하십시오.

optionbox 2020. 8. 9. 10:20
반응형

응답 코드 200 또는 201 및 내용 인 POST로 요청을 작성하십시오.


시스템에 새 데이터 항목을 추가하는 것이 목적인 REST 서비스를 작성한다고 가정합니다.

게시 할 계획입니다.

http://myhost/serviceX/someResources

작동한다고 가정하면 어떤 응답 코드를 사용해야합니까? 그리고 어떤 콘텐츠를 반환 할 수 있습니까?

HTTP 응답 코드 정의 를 살펴보고 다음과 같은 가능성을 확인했습니다.

200 : 작업의 결과를 설명하거나 포함하는 엔티티를 반환 합니다.

201 : CREATED를 의미합니다. 의미 * 요청이 이행되어 새 리소스가 생성되었습니다. 새로 생성 된 리소스는 Location 헤더 필드에서 제공하는 리소스에 대한 가장 구체적인 URI를 사용하여 응답의 엔터티에서 반환 된 URI에 의해 참조 될 수 있습니다. 응답은 사용자 또는 사용자 에이전트가 가장 적절한 것을 선택할 수있는 자원 특성 및 위치 목록을 포함하는 엔티티를 포함해야합니다 (SHOULD). 엔티티 형식은 Content-Type 헤더 필드에 제공된 미디어 유형에 의해 지정됩니다. *

후자는 Http 사양과 더 일치하게 들리지만, 나는 무엇인지 전혀 명확하지 않습니다.

응답은 자원 특성 및 위치 목록을 포함하는 엔티티를 포함해야합니다 (SHOULD).

방법.

추천? 해석?


http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19

콜론으로 구분 된 키-값입니다.

ETag : "xyzzy"

모든 유형의 텍스트 데이터가 될 수 있습니다. 일반적으로 생성 된 항목의 식별자와 함께 JSON 문자열을 포함합니다. 테스트의 용이성만으로도 포함 할 가치가 있습니다.

ETag: "{ id: 1234, uri: 'http://domain.com/comments/1234', type: 'comment' }"

이 예에서 생성 된 항목의 식별자, URI 및 유형은 "자원 특성 및 위치"입니다.


나는 atompub REST API 가 편안한 서비스의 좋은 예 라고 생각 합니다. atompub 사양에서 아래 스 니펫을 참조하세요.

POST /edit/ HTTP/1.1
Host: example.org
User-Agent: Thingio/1.0
Authorization: Basic ZGFmZnk6c2VjZXJldA==
Content-Type: application/atom+xml;type=entry
Content-Length: nnn
Slug: First Post

<?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>
</entry>

서버는 상태 코드 201로 성공적인 생성을 알립니다. 응답에는 Atom 항목의 구성원 항목 URI를 나타내는 Location 헤더와 응답 본문에 해당 항목의 표현이 포함됩니다.

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>

The Entry created and returned by the Collection might not match the Entry POSTed by the client. A server MAY change the values of various elements in the Entry, such as the atom:id, atom:updated, and atom:author values, and MAY choose to remove or add other elements and attributes, or change element content and attribute values.


The idea is that the response body gives you a page that links you to the thing:

201 Created

The 201 (Created) status code indicates that 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.

This means that you would include a Location in the response header that gives the URL of where you can find the newly created thing:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597

Response body

They then go on to mention what you should include in the response body:

The 201 response payload typically describes and links to the resource(s) created.

For the human using the browser, you give them something they can look at, and click, to get to their newly created resource:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: text/html

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

If the page will only be used by a robot, the it makes sense to have the response be computer readable:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/xml

<createdResources>
   <questionID>1860645</questionID>
   <answerID>36373586</answerID>
   <primary>/a/36373586/12597</primary>
   <additional>
      <resource>http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586</resource>
      <resource>http://stackoverflow.com/a/1962757/12597</resource>
   </additional>
</createdResource>

Or, if you prefer:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/json

{ 
   "questionID": 1860645, 
   "answerID": 36373586,
   "primary": "/a/36373586/12597",
   "additional": [
      "http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586",
      "http://stackoverflow.com/a/36373586/12597"
   ]
}

The response is entirely up to you; it's arbitrarily what you'd like.

Cache friendly

Finally there's the optimization that i can pre-cache the created resource (because i already have the content; i just uploaded it). The server can return a date or ETag which i can store with the content i just uploaded:

See Section 7.2 for a discussion of the meaning and purpose of validator header fields, such as ETag and Last-Modified, in a 201 response.

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/23704283/12597
Content-Type: text/html
ETag: JF2CA53BOMQGU5LTOQQGC3RAMV4GC3LQNRSS4
Last-Modified: Sat, 02 Apr 2016 12:22:39 GMT 

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

And ETag s are purely arbitrary values. Having them be different when a resource changes (and caches need to be updated) is all that matters. The ETag is usually a hash (e.g. SHA2). But it can be a database rowversion, or an incrementing revision number. Anything that will change when the thing changes.


In a few words:

  • 200 when an object is created and returned
  • 201 when an object is created but only its reference is returned (such as an ID or a link)

Check out HTTP: Method Definitions: POST.

The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.

If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).


The output is actually dependent on the content type being requested. However, at minimum you should put the resource that was created in Location. Just like the Post-Redirect-Get pattern.

In my case I leave it blank until requested otherwise. Since that is the behavior of JAX-RS when using Response.created().

However, just note that browsers and frameworks like Angular do not follow 201's automatically. I have noted the behaviour in http://www.trajano.net/2013/05/201-created-with-angular-resource/


Another answer I would have for this would be to take a pragmatic approach and keep your REST API contract simple. In my case I had refactored my REST API to make things more testable without resorting to JavaScript or XHR, just simple HTML forms and links.

So to be more specific on your question above, I'd just use return code 200 and have the returned message contain a JSON message that your application can understand. Depending on your needs it may require the ID of the object that is newly created so the web application can get the data in another call.

One note, in my refactored API contract, POST responses should not contain any cacheable data as POSTs are not really cachable, so limit it to IDs that can be requested and cached using a GET request.

참고URL : https://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content

반응형