REST API-PUT DELETE POST GET을 사용하는 이유는 무엇입니까?
그래서 REST API 작성에 대한 기사를 살펴 보았습니다. 그리고 그들 중 일부는 모든 유형의 HTTP 요청을 사용하도록 제안합니다 PUT
DELETE
POST
GET
. 예를 들어 index.php를 만들고 API를 다음과 같이 작성합니다.
$method = $_SERVER['REQUEST_METHOD'];
$request = split("/", substr(@$_SERVER['PATH_INFO'], 1));
switch ($method) {
case 'PUT':
....some put action....
break;
case 'POST':
....some post action....
break;
case 'GET':
....some get action....
break;
case 'DELETE':
....some delete action....
break;
}
물론, 웹 서비스에 대해서는 잘 모르겠습니다 (아직). 그러나 일반 또는 메소드 이름과 모든 매개 변수를 포함하는 JSON 객체를 수락 한 다음 JSON으로 응답 하는 것이 쉽지 않을 것 입니다. 우리는 쉽게 직렬화 / 역 직렬화 PHP의를 통해 수 및 다른 HTTP 요청 방법으로 처리 할 필요없이 우리가 그 데이터를 원하는대로 할.POST
GET
json_encode()
json_decode()
뭔가 빠졌습니까?
업데이트 1 :
Ok-다양한 API를 파고 XML-RPC , JSON-RPC , SOAP , REST 에 대해 많이 배운 후에이 유형의 API가 적합하다는 결론에 도달했습니다. 실제로 스택 교환은 사이트에서이 접근 방식을 거의 사용하고 있으며 이러한 사람들은 Stack Exchange API를 수행하는 작업을 알고 있다고 생각합니다 .
의 아이디어 RE 표상 S 탓에 T 를 ransfer하지 않음을 가능한 한 가장 간단한 방법으로 데이터를 액세스하는 방법에 대한.
게시 요청을 사용하여 JSON에 액세스 할 것을 제안했습니다. 이는 데이터에 액세스 / 조작하는 데 유효한 방법입니다.
REST는 의미있는 데이터 액세스를 위한 방법입니다 . REST에 요청이 표시되면 데이터에서 발생하는 상황에 즉시 대응해야합니다.
예를 들면 다음과 같습니다.
GET: /cars/make/chevrolet
시보레 자동차 목록을 반환 할 가능성이 높습니다. 좋은 REST API는 쿼리 문자열에 일부 출력 옵션을 통합 ?output=json
하거나 ?output=html
접근자가 정보를 인코딩해야하는 형식을 결정할 수 있도록합니다.
어떻게 REST API를에 합리적 법인 (法人) 데이터 유형에 대한 생각을 조금 후에, 나는 가장 좋은 방법은 같은 이미 존재하는 파일 확장자를 통해 것 명시 적으로 데이터의 유형을 지정하는 것으로 결론을했습니다 .js
, .json
, .html
, 또는 .xml
. 누락 된 파일 확장자는 기본적으로 모든 형식 (예 : JSON)으로 설정됩니다. 지원되지 않는 파일 확장자는 501 Not Implemented
상태 코드를 반환 할 수 있습니다 .
또 다른 예:
POST: /cars/
{ make:chevrolet, model:malibu, colors:[red, green, blue, grey] }
관련 색상으로 db에 새로운 시보레 말리부를 만들 것입니다. 내가 말할 가능성이 나머지 API를 직접 데이터베이스 구조와 관련 될 필요가 없기 때문에. 실제 데이터가 보호되도록 마스킹 인터페이스 일뿐입니다 (데이터베이스 구조에 대한 접근 자 및 변경자와 같은 것으로 생각하십시오).
이제 우리는 dem 등분 문제로 넘어 가야 합니다. 일반적으로 REST는 CRUD over HTTP를 구현 합니다. HTTP를 사용 GET
, PUT
, POST
및 DELETE
요청합니다.
매우 간단한 REST 구현은 다음 CRUD 맵핑을 사용할 수 있습니다.
Create -> Post
Read -> Get
Update -> Put
Delete -> Delete
이 구현에는 문제가 있습니다. Post는 비등 전성 메서드로 정의됩니다. 같은 Post 메소드의 후속 호출이 발생할 것으로이 방법 다른 서버 상태. Get, Put 및 Delete는 dem 등원입니다. 즉, 여러 번 호출하면 동일한 서버 상태가됩니다.
이는 다음과 같은 요청을 의미합니다.
Delete: /cars/oldest
실제로 다음과 같이 구현할 수 있습니다.
Post: /cars/oldest?action=delete
이므로
Delete: /cars/id/123456
한 번 호출하거나 1000 번 호출하면 동일한 서버 상태가됩니다.
A better way of handling the removal of the oldest
item would be to request:
Get: /cars/oldest
and use the ID
from the resulting data to make a delete
request:
Delete: /cars/id/[oldest id]
An issue with this method would be if another /cars
item was added between when /oldest
was requested and when the delete
was issued.
This is a security and maintainability question.
safe methods
Whenever possible, you should use 'safe' (unidirectional) methods such as GET and HEAD in order to limit potential vulnerability.
idempotent methods
Whenever possible, you should use 'idempotent' methods such as GET, HEAD, PUT and DELETE, which can't have side effects and are therefore less error prone/easier to control.
In short, REST emphasizes nouns over verbs. As your API becomes more complex, you add more things, rather than more commands.
You asked:
wouldn't it be easier to just accept JSON object through normal $_POST and then respond in JSON as well
From the Wikipedia on REST:
RESTful applications maximize the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimize the addition of new application-specific features on top of it
From what (little) I've seen, I believe this is usually accomplished by maximizing the use of existing HTTP verbs, and designing a URL scheme for your service that is as powerful and self-evident as possible.
Custom data protocols (even if they are built on top of standard ones, such as SOAP or JSON) are discouraged, and should be minimized to best conform to the REST ideology.
SOAP RPC over HTTP, on the other hand, encourages each application designer to define a new and arbitrary vocabulary of nouns and verbs (for example getUsers(), savePurchaseOrder(...)), usually overlaid onto the HTTP 'POST' verb. This disregards many of HTTP's existing capabilities such as authentication, caching and content type negotiation, and may leave the application designer re-inventing many of these features within the new vocabulary.
The actual objects you are working with can be in any format. The idea is to reuse as much of HTTP as possible to expose your operations the user wants to perform on those resource (queries, state management/mutation, deletion).
You asked:
Am I missing something?
There is a lot more to know about REST and the URI syntax/HTTP verbs themselves. For example, some of the verbs are idempotent, others aren't. I didn't see anything about this in your question, so I didn't bother trying to dive into it. The other answers and Wikipedia both have a lot of good information.
Also, there is a lot to learn about the various network technologies built on top of HTTP that you can take advantage of if you're using a truly restful API. I'd start with authentication.
In regards to using extension to define data type. I noticed that MailChimp API is doing it, but I don't think this is a good idea.
GET /zzz/cars.json/1
GET /zzz/cars.xml/1
My sound like a good idea, but I think "older" approach is better - using HTTP headers
GET /xxx/cars/1
Accept: application/json
Also HTTP headers are much better for cross data type communication (if ever someone would need it)
POST /zzz/cars
Content-Type: application/xml <--- indicates we sent XML to server
Accept: application/json <--- indicates we want get data back in JSON format
Am I missing something?
Yes. ;-)
This phenomenon exists because of the uniform interface constraint. REST likes using already existing standards instead of reinventing the wheel. The HTTP standard has already proven to be highly scalable (the web is working for a while). Why should we fix something which is not broken?!
note: The uniform interface constraint is important if you want to decouple the clients from the service. It is similar to defining interfaces for classes in order to decouple them from each other. Ofc. in here the uniform interface consists of standards like HTTP, MIME types, URI, RDF, linked data vocabs, hydra vocab, etc...
Good Semantics is important in programming.
Utilizing more methods besides GET/POST will be helpful because it will increase the readability of your code and make it easier to maintain.
Why?
Because you know GET will retrieve data from your api. You know POST will add new data to your system. You know PUT will make updates. DELETE will delete rows etc, etc,
I normally structure my RESTFUL Web Services so that I have a function callback named the same thing as the method.
I use PHP, so I use function_exists (I think its called). If the function doesn't exist, I throw a 405 (METHOD NOT ALLOWED).
Bill Venners: In your blog post entitled "Why REST Failed," you said that we need all four HTTP verbs—GET, POST, PUT, and DELETE— and lamented that browser vendors only GET and POST." Why do we need all four verbs? Why aren't GET and POST enough?
Elliotte Rusty Harold: There are four basic methods in HTTP: GET, POST, PUT, and DELETE. GET is used most of the time. It is used for anything that's safe, that doesn't cause any side effects. GET is able to be bookmarked, cached, linked to, passed through a proxy server. It is a very powerful operation, a very useful operation.
POST by contrast is perhaps the most powerful operation. It can do anything. There are no limits as to what can happen, and as a result, you have to be very careful with it. You don't bookmark it. You don't cache it. You don't pre-fetch it. You don't do anything with a POST without asking the user. Do you want to do this? If the user presses the button, you can POST some content. But you're not going to look at all the buttons on a page, and start randomly pressing them. By contrast browsers might look at all the links on the page and pre-fetch them, or pre-fetch the ones they think are most likely to be followed next. And in fact some browsers and Firefox extensions and various other tools have tried to do that at one point or another.
PUT and DELETE are in the middle between GET and POST. The difference between PUT or DELETE and POST is that PUT and DELETE are *idempotent, whereas POST is not. PUT and DELETE can be repeated if necessary. Let's say you're trying to upload a new page to a site. Say you want to create a new page at http://www.example.com/foo.html, so you type your content and you PUT it at that URL. The server creates that page at that URL that you supply. Now, let's suppose for some reason your network connection goes down. You aren't sure, did the request get through or not? Maybe the network is slow. Maybe there was a proxy server problem. So it's perfectly OK to try it again, or again—as many times as you like. Because PUTTING the same document to the same URL ten times won't be any different than putting it once. The same is true for DELETE. You can DELETE something ten times, and that's the same as deleting it once.
By contrast, POST, may cause something different to happen each time. Imagine you are checking out of an online store by pressing the buy button. If you send that POST request again, you could end up buying everything in your cart a second time. If you send it again, you've bought it a third time. That's why browsers have to be very careful about repeating POST operations without explicit user consent, because POST may cause two things to happen if you do it twice, three things if you do it three times. With PUT and DELETE, there's a big difference between zero requests and one, but there's no difference between one request and ten.
Please visit the url for more details. http://www.artima.com/lejava/articles/why_put_and_delete.html
Update:
Idempotent methods An idempotent HTTP method is a HTTP method that can be called many times without different outcomes. It would not matter if the method is called only once, or ten times over. The result should be the same. Again, this only applies to the result, not the resource itself. This still can be manipulated (like an update-timestamp, provided this information is not shared in the (current) resource representation.
Consider the following examples:
a = 4;
a++;
The first example is idempotent: no matter how many times we execute this statement, a will always be 4. The second example is not idempotent. Executing this 10 times will result in a different outcome as when running 5 times. Since both examples are changing the value of a, both are non-safe methods.
Basically REST is (wiki):
- Client–server architecture
- Statelessness
- Cacheability
- Layered system
- Code on demand (optional)
- Uniform interface
REST is not protocol, it is principles. Different uris and methods - somebody so called best practices.
참고URL : https://stackoverflow.com/questions/4573305/rest-api-why-use-put-delete-post-get
'IT story' 카테고리의 다른 글
C #에서 프로세스를 시작하려면 어떻게합니까? (0) | 2020.06.13 |
---|---|
ASP.NET MVC 1의 HttpContextBase에서 HttpContext 개체를 얻는 방법은 무엇입니까? (0) | 2020.06.13 |
bash 스크립트에서 정규 표현식으로 테스트를 어떻게 부정합니까? (0) | 2020.06.12 |
오염 된 캔버스는 내보낼 수 없습니다 (0) | 2020.06.12 |
Android LocationClient 클래스는 더 이상 사용되지 않지만 설명서에서 사용됩니다. (0) | 2020.06.12 |