在查询字符串或请求正文中包含数据的 Restful URL? [英] Restful URLs with data in query string or request body?

查看:35
本文介绍了在查询字符串或请求正文中包含数据的 Restful URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查询字符串与请求正文中的 REST URL 中传递数据的经验法则是什么?

What's the rule of thumb for passing data in a REST URL in the query string vs. the body of a request?

即:您正在创建一项服务来添加曲棍球运动员.你可以去:

Ie: You're creating a service to add hockey players. You could go with:

PUT /players 
{ "name": Gretzky }

PUT /players?name=Gretzky

如果您要传递大量数据,则需要使用选项 #1,因为 URL 长度有限制.但除此之外,为什么不直接使用查询字符串来传递数据呢?

If you're passing a lot of data, you would need to go with option #1 as there is a limit on the URL length. But other than this, why not just use the query string to pass data?

更新:删除了您可以在浏览器中测试选项 #2 的评论.意识到(废话)你只能在浏览器中执行 GET-s.

Update: Removed comment that you could test option #2 in a browser. Realized (duh) that you can only do GET-s in your browser.

推荐答案

根据 HTTP 对 PUT 的定义,您的第一个请求是用仅包含一个玩家名称的新列表覆盖玩家列表.它不会添加到玩家列表中.

Based on HTTP's definition of PUT, your first request is overwriting the list of players with a new list that contains just one player name. It is not adding to the list of players.

第二个选项对我来说没有多大意义.做没有body的PUT真的不符合PUT的意思.

The second option does not really make much sense to me. Doing PUT without a body is not really consistent with the meaning of PUT.

考虑到 POST 的标准定义之一是附加到现有资源,我不确定您为什么不这样做

Considering that one of the standard definitions of POST is to append to an existing resource, I'm not sure why you wouldn't do

POST /players 
{ "name": Gretzky }

如果您确定所有玩家名称都是唯一的,那么您可以像这样使用 PUT:

If you are sure that all you player names are going to be unique then you could use PUT like this:

PUT /player/Gretzky
{ "name": Gretzky }

当您决定在 HTTP 上执行 REST 时,您同意按照 RFC2616 中定义的方式使用 HTTP.这就是统一接口约束的含义.只是为了迂腐,没有 REST URL 这样的东西,你不能在浏览器中测试任何一个选项,因为没有 javascript,你不能在浏览器中执行 PUT.

When you decide to do REST on HTTP you are agreeing to use HTTP in the way that is defined in RFC2616. That's what the uniform interface constraint means. And just to be pedantic, there is no such thing as a REST URL and you can't test either option in a browser because without javascript, you can't do a PUT in a browser.

这篇关于在查询字符串或请求正文中包含数据的 Restful URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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