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

Pep*_*zza 4 rest http http-status-codes

可能重复:
无效数据的REST响应代码

拥有以下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响应代码是什么?

非常感谢!

小智 11

  1. 创建用户的代码201,非常明显
  2. 400个不正确的输入参数是最合适的,谷歌API使用它
  3. 对于像你这样的冲突局面来说,这似乎是最好的

我只建议分开创建和编辑,并为它们使用不同的方法 - POST创建,PUT更新.如果用户要修改某些内容但输入错误怎么办?最好显示错误


CAb*_*ott 6

这是一个很好的RESTful操作的"典型" HTTP响应表.

从该表中,这是推荐用于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
Run Code Online (Sandbox Code Playgroud)