Обсуждение:REST

Последнее сообщение: 3 года назад от Mihail Haritonov в теме ««REST является альтернативой RPC»»

«из-за чего количество отдельных ресурсов должно быть большим» править

Возможно, здесь подразумевалось «может быть большим», а не «должно быть»? --Aleks Revo 00:26, 14 ноября 2010 (UTC)Ответить

Спасибо, исправил. — Tetromino 01:56, 27 октября 2012 (UTC)Ответить

«REST является альтернативой RPC» править

Сомнительное утверждение.

Разве REST - это не удаленный вызов? REST - это RPC по HTTP. REST - это не стандарт. Это сам подход, что RPC можно делать по HTTP.

Думаю, не ошибусь, если скажу, что REST - это не "RPC по HTTP". И, думаю, также не ошибусь, если скажу, что:
  1. REST - это, когда возвращается ресурс (например, html страница) с каким-то содержимым и ссылками на другие ресурсы, и из содержимого данного ресурса клиент (как правило, человек) может понять что это за содержимое и по каким ссылкам ему нужно переходить.
  2. В REST клиент заранее не знает всех возвращаемых ресурсом url адресов, а знает только url самого ресурса (ну и знает, что возвращаемый ответ является гипертекстом, т.к. что там будут ссылки по поторым можно переходить). Т.е. при каждом новом запросе ресурс как бы возвращает новую спецификацию своего API в свободном формате. Так, например, при каждом новом заходе на web-страницу может загрузиться совершенно новый html код, ссылающийся на совершенно новые url адреса (и клиент, с помощью своего интеллекта, должен догадаться, что ссылка с текстом "Оформить заказ" является именно тем, что ему сейчас нужно).
  3. Хорошим примером REST является html страница с формой, в которой уже прописан url адрес (<form action="http://example.com/abc">) и клиент узнаёт о существовании http://example.com/abc лишь после запроса страницы (а не заранее, как в случае RPC).
  4. REST - это не о жестко/статически закодированном взаимодействии машина-машина (для чего используется RPC с заранее согласованным обоими сторонами вреобъемлющим API), а о взаимодействии человек-машина (которое, после обращения к некоторому заранее известному url адресу ресурса, развивается динамически).
  5. REST - это скорее о том, что будет возвращать RPC метод и как клиент будет обрабатывать этот ответ.
  6. URL http://example.com/abc из примера выше, по сути, является RPC методом, реализованным на базе протокола HTTP. И для реализации REST всё равно понадобится RPC (который будет чем-то вроде названия технологии физического воплощения запросов к ресурсам и получения от них ответов), но как только RPC метод внутри ресурса станет публичным с заранее оговоренной детальной структурой ответа (т.е. он будет известен заранее, а не из ответа на запрос к ресурсу), такое приложение/ресурс некорректно будет называть RESTful (и, собственно, и не нужно, т.к. у них разные назначения).
Но, несмотря на то, что REST - это не RPC, я тоже считаю, что фраза "REST является альтернативой RPC" является некорректной, т.к. это разные технологии (точнее, REST - это стиль, а RPC - это технология, которая может применяться для его реализации). По сути, то, что часто называют "REST/RESTful API", нужно называть "RPC over HTTP API". И о том, что API вида "GET /people/{userId}/{groupId}" является RPC и его нельзя называть REST/RESTful ясно сказал Roy Fielding (автот диссертации про REST) в своей статье в 2008 году (где подверг критике некий SocialSite FinalizeRESTAPI).
По-хорошему, конечно, нужно вычитать ту дессиртацию и все статьи про REST от Roy Fielding, чтобы доработать статью (добавить информацию о неправильном использовании термина, о "RPC over HTTP" и т.п.).
Вот несколько цитат из той статьи:

I am getting frustrated by the number of people calling any HTTP-based interface a REST API. Today’s example is the SocialSite REST API. That is RPC. It screams RPC. There is so much coupling on display that it should be given an X rating. What needs to be done to make the REST architectural style clear on the notion that hypertext is a constraint? In other words, if the engine of application state (and hence the API) is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period. Is there some broken manual somewhere that needs to be fixed?

...

A REST API must not define fixed resource names or hierarchies (an obvious coupling of client and server). Servers must have the freedom to control their own namespace. Instead, allow servers to instruct clients on how to construct appropriate URIs, such as is done in HTML forms and URI templates, by defining those instructions within media types and link relations.

...

A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) ...

...

There are probably other rules that I am forgetting, but the above are the rules related to the hypertext constraint that are most often violated within so-called REST APIs. Please try to adhere to them or choose some other buzzword for your API.

И в комментариях к статье он тоже написал интересные пояснения. Вот несколько цитат, показавшихся мне наиболее интересными:

When I say hypertext, I mean the simultaneous presentation of information and controls such that the information becomes the affordance through which the user (or automaton) obtains choices and selects actions.

...

A truly RESTful API looks like hypertext. ... Think of it in terms of the Web. How many Web browsers are aware of the distinction between an online-banking resource and a Wiki resource? None of them. They don’t need to be aware of the resource types. What they need to be aware of is the potential state transitions — the links and forms — and what semantics/actions are implied by traversing those links. A browser represents them as distinct UI controls so that a user can see potential transitions and anticipate the effect of chosen actions.

...

To some extent, people get REST wrong because I failed to include enough detail on media type design within my dissertation. That’s because I ran out of time, not because I thought it was any less important than the other aspects of REST. Likewise, I suspect a lot of people get it wrong because they read only the Wikipedia entry on the subject, which is not based on authoritative sources.

...

The interface doesn’t need to be discovered. It is defined right there in the hypertext. The representation tells the client how to compose all transitions to the next application state.

...

You should not be building clients that are dependent on the resource naming structure.

...

No RESTful architecture needs type specifications.

...

Don’t confuse application state (the state of the user’s application of computing to a given task) with resource state (the state of the world as exposed by a given service). They are not the same thing.

...

However, if your client relies on the resource being a queue, then it certainly isn’t a RESTful API. Do you see the difference? Encoding knowledge within clients and servers of the other side’s implementation mechanism is what we are trying to avoid.


И вот в этой статье от другого автора еще интересная теория о происхождении неправильного использования термина REST:

So, given that Fielding’s dissertation was all about avoiding silver bullet software architectures, how did REST become a de facto standard for web services of every kind?

My theory is that, in the mid-2000s, the people who were sick of SOAP and wanted to do something else needed their own four-letter acronym.

I’m only half-joking here. SOAP, or the Simple Object Access Protocol, is a verbose and complicated protocol that you cannot use without first understanding a bunch of interrelated XML specifications. Early web services offered APIs based on SOAP, but, as more and more APIs started being offered in the mid-2000s, software developers burned by SOAP’s complexity migrated away en masse.

Among this crowd, SOAP inspired contempt. Ruby-on-Rails dropped SOAP support in 2007, leading to this emblematic comment from Rails creator David Heinemeier Hansson: “We feel that SOAP is overly complicated. It’s been taken over by the enterprise people, and when that happens, usually nothing good comes of it.”7 The “enterprise people” wanted everything to be formally specified, but the get-shit-done crowd saw that as a waste of time.

If the get-shit-done crowd wasn’t going to use SOAP, they still needed some standard way of doing things. Since everyone was using HTTP, and since everyone would keep using HTTP at least as a transport layer because of all the proxying and caching support, the simplest possible thing to do was just rely on HTTP’s existing semantics. So that’s what they did. They could have called their approach Fuck It, Overload HTTP (FIOH), and that would have been an accurate name, as anyone who has ever tried to decide what HTTP status code to return for a business logic error can attest. But that would have seemed recklessly blasé next to all the formal specification work that went into SOAP.

Luckily, there was this dissertation out there, written by a co-author of the HTTP/1.1 specification, that had something vaguely to do with extending HTTP and could offer FIOH a veneer of academic respectability. So REST was appropriated to give cover for what was really just FIOH.

I’m not saying that this is exactly how things happened, or that there was an actual conspiracy among irreverent startup types to misappropriate REST, but this story helps me understand how REST became a model for web service APIs when Fielding’s dissertation isn’t about web service APIs at all. Adopting REST’s constraints makes some sense, especially for public-facing APIs that do cross organizational boundaries and thus benefit from REST’s “uniform interface.” That link must have been the kernel of why REST first got mentioned in connection with building APIs on the web. But imagining a separate approach called “FIOH,” that borrowed the “REST” name partly just for marketing reasons, helps me account for the many disparities between what today we know as RESTful APIs and the REST architectural style that Fielding originally described.

--Mihail Haritonov (обс.) 15:43, 22 февраля 2021 (UTC)Ответить

Перевод править

Representational State Transfer, «передача представлений состояний» — А может всё-таки "Передача ... состояния" ? Потому что эта английская фраза эквивалентна данной: Transfer Of Representational State. Заметьте, здесь существительные — это Transfer и State, но никак не Representational! То есть можно (и нужно) перевести как "Передача репрезентативного состояния". Слово репрезентативный есть в русском языке. Если придумаете как его заменить — пожалуйста. Вот его значения: "репрезентация" в толковых словорях — по-моему оно соответствует требуемому. Но можно написать "Передача отображающего состояния", чтобы понятнее и более по-русски. Или "выражающего"... 94.179.16.19 23:42, 15 февраля 2013 (UTC)Ответить

Перевод слова "representational" править

Английское слово representational в некоторых контекстах можно перевести как «репрезентативный» — но никак не во фразе representational state transfer. Читайте диссертацию Филдинга, где он ввел термин REST:

The name “Representational State Transfer” is intended to evoke an image of how a well-designed Web application behaves: a network of Web pages forms a virtual state machine, allowing a user to progress through the application by selecting a link or submitting a short data-entry form, with each action resulting in a transition to the next state of the application by transferring a representation of that state to the user.

Иными словами, моделью веб-сервиса является абстрактный автомат (state machine), который при переходе в свое следующее состояние (next state) по комманде пользователя возвращает пользователю некое представление (representation) этого состояния.

Никакой речи о репрезентативности — то есть о том, что состояние является характерным примером чего бы то ни было — тут не идет. — Tetromino 01:35, 27 октября 2012 (UTC)Ответить

Еще раз о переводе править

Осмелюсь предложить еще один вариант перевода, на мой взгляд наиболее удачный «Передача представления о состоянии». Ведь весь смысл в том, что клиент не хранит состояние. 83.149.255.10 16:14, 27 сентября 2016 (UTC)Ответить

Основные составляющие править

Насколько я понимаю, и насколько об этом говорится в источниках, главными составляющими REST являются:

  • Адресуемость (ресурсов)
  • Связность
  • Единообразный (унифицированный) интерфейс
  • Отсутствие сохранения состояния

В разделе REST#Архитектура REST сейчас всё, что угодно, кроме этого (отсутствие состояния упомянуто). Кроме того, упор следует делать на вторичные источники, а не на произведения Филдинга (независимые АИ). РоманСузи 06:43, 15 декабря 2015 (UTC)Ответить

Все несколько сложнее. Пока брошу фрагмент сюда. По Филдингу он касается только интерфейса.

Центральными для REST являются следующие ограничения при проектировании гипермедиа-системы[1][2]:

  • Адресуемость ресурсов
  • Единообразный интерфейс
  • Самодостаточные сообщения
  • Гипермедийная связность ресурсов
  • Взаимодействие без сохранения состояния клиента на сервере

РоманСузи 12:39, 15 декабря 2015 (UTC)Ответить

  1. Wilde, Pautasso, 2011, REST Definition.
  2. Н. Л. Подколодный, А. В. Семенычев, Д. А. Рассказов, В. Г. Боровский, Е. А. Ананько, Е. В. Игнатьева, Н. Н. Подколодная, О. А. Подколодная, Н. А. Колчанов Распределённая система RESTful-web-сервисов для реконструкции и анализа генных сетей. Вавиловский журнал генетики и селекции, т. 16, N 4/1, 2012