1

我对网络开发还是很陌生,所以如果这个问题真的很愚蠢,请多多包涵。

我正在尝试遵循 REST 原则,但是,我真的很欣赏 JSON 如何与 Ruby 以及任何通过 API 进行外部连接的东西一起流动。我知道在 REST 中将参数直接输入到 URL 中是非常标准的,如下所示:myurl.com/ExampleModel/MyIDParameter 并将 JSON(如果有)发送到该 URI,对吗?

我想知道的是:从 URI 中删除参数(以及如果我永远不会使用它的路由)并将参数包含在 JSON 中是否违反 REST 原则?

例如,而不是调用这个:

myurl.com/ExampleModel/id
{
    "name" : "My Name",
    "anotherParameter" : "A random string"
}

你可以这样称呼:

myurl.com/ExampleModel
{
    "id" : 512,
    "name" : "My Name",
    "anotherParameter" : "A random string"
}
4

4 回答 4

4

如果myurl.com/ExampleModel标识一个唯一资源,您可以将其用作 URI。但我对此表示怀疑。

您的应用程序也可以像这样具有不同的资源表示吗?

{
    "id" : 513,
    "name" : "Some Other Name",
    "anotherParameter" : "A differnet random string"
}

如果是,它的 URI 是什么?

我建议使用第一种形式来处理这样的资源表示:

GET http://myurl.com/ExampleModel/513

注意:您的 JSON 无效,因为它缺少双引号和逗号。

于 2012-11-02T14:43:26.617 回答
3

我不认为数据交换的格式与 REST 是什么或不是什么有关。

去吧。

于 2012-11-02T14:37:05.073 回答
2

首先,免责声明:我不会用 Ruby 编程,所以我不能回答关于 Ruby 的具体问题。但我的回答是针对您关于 REST 原则的问题。

最后,答案是:这是您的应用程序如何运行的问题。我将首先解释开发人员使用的一种常用方法。我提到了常见的,并不是金科玉律。

When you specify myurl.com/ExampleModel/id. A common meaning of such a pattern is used in with GET or PUT operation. GET in the sense that I want information on some object of ID value id. PUT in the sense that I have some request body attached with the request to be Updated to the Data Store whose Object have a ID of id.

Your second URL when you mentioned just myurl.com/ExampleModel, A common interpretation is to show me all the records from the ExampleModel collection. This is pretty much the default behaviour used by developers who write APIs.

So, does it break REST principles when you want to do things, the answer is NO. But if you hand your API to other people, the might get a bit confused over it.

So there you have it. Now it's upto you to decide what is best suited for your application.

于 2012-11-02T14:45:34.060 回答
1

REST is really more of a concept than a strictly designed protocol. Most people equate REST to simply using all of the HTTP verbs to do different things on the same URL, and there's some validity to that way of thinking.

But, if you want some information about how to use the original intent behind REST to actually make a good API:

http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http

http://blog.steveklabnik.com/posts/2011-08-07-some-people-understand-rest-and-http

So if you follow the principles from the blog, it's pretty important to refer to resources by their ID, in the URL. But it's your API and there's no strict rules on how things must be done, just recommendations on how to make your API more discoverable.

于 2012-11-02T14:47:32.550 回答