Http响应代码无效数据和数据冲突

时间:2013-01-02 18:44:15

标签: http rest http-status-codes

  

可能重复:
  REST response code for invalid data

拥有以下REST资源:

POST /user/{primary_key}

该资源旨在像“ADD / UPDATE”操作一样工作。这意味着它可以用于:

  • 创建新用户
  • 更新现有用户的信息

如果客户想要创建新用户,则需要一些信息:

POST user/{pimary_key}
Paylod:
 - Username - (must be unique)
 - Password

如果客户想要简单地更新现有用户,则该呼叫只需要包括主键和新/更改的信息。例如:

POST user/{pimary_key}
Paylod:
 - favorite hamburger type

这种情况可能会导致客户端的多个请求无效:

  • CONFLICT - 客户端更新现有用户,尝试将username更改为已由其他用户使用的值。
  • 缺少信息 - 客户端尝试创建新用户,但不包含用户名和密码等必要信息。

在这些情况下,要返回的HTTP响应代码是什么?

非常感谢!

2 个答案:

答案 0 :(得分:11)

  1. 创建用户的代码201,非常明显
  2. 400用于错误的输入参数是最合适的,谷歌API使用它
  3. 对于像你这样的冲突情况来说似乎是最好的
  4. 我只建议分开创建和编辑,并为它们使用不同的方法 - POST创建,PUT更新。如果用户要修改某些内容但输入错误怎么办?最好显示错误

答案 1 :(得分:6)

这是一张很好的“典型”HTTP responses to RESTful operations表。

从该表中,这是推荐用于POST操作的内容:

200 (OK) - if an existing resource has been updated
201 (created) - if a new resource is created
202 (accepted) - accepted for processing but not been completed (Async processing)

301 (Moved Permanently) - the resource URI has been updated
303 (See Other) - e.g. load balancing

400 (bad request) - indicates a bad request
404 (not found) - the resource does not exits
406 (not acceptable) - the server does not support the required representation
409 (conflict) - general conflict     
412 (Precondition Failed) e.g. conflict by performing conditional update
415 (unsupported media type) - received representation is not supported

500 (internal server error) - generic error response
503 (Service Unavailable) - The server is currently unable to handle the request