【问题标题】:Identify the correct HTTP method识别正确的 HTTP 方法
【发布时间】:2017-05-12 12:02:28
【问题描述】:
我使用 springboot 创建了一个 REST Web 服务。它有以下网址的用户资源
/users => get the users in system.(GET)
/adduser => Post a new user.(POST)
/addFriend/{friendID} => this method is to add the friendID into the current logged-in friend(the user resource has friend list) now my doubt its Its a POST request of a GET request. Currently GET method has solved my problem. But I am not sure about the correct method which is right one logically.
【问题讨论】:
标签:
web-services
restful-url
【解决方案1】:
不,Restful API 以资源为目标,在 URI 中不包含操作。
示例:
获取/用户
=> 获取用户列表
GET /users/:userid
=> 通过用户 ID 获取用户信息
发布/用户
=> 创建一个新用户
删除 /users/:userid
=> 通过用户 ID 删除用户
POST /users/:userid/friends
=>建立友谊,您可以发送包含另一个用户 ID 的正文。(JSON/XML)
GET /users/:userid/friends/:friendid
=> 检查两个用户之间的好友可能返回friendshipID 或true/false
【解决方案2】:
这是一个 POST 请求。
根据Wikipedia:
GET 方法请求指定资源的表示。使用 GET 的请求应该只检索数据并且应该没有其他效果。
和
POST 方法请求服务器接受请求中包含的实体作为 URI 标识的 Web 资源的新下级。例如,发布的数据可能是现有资源的注释;公告板、新闻组、邮件列表或评论线程的消息;将 Web 表单提交给数据处理过程的结果的数据块;或要添加到数据库的项目。