RESTful API返回正确的错误

时间:2015-06-04 15:06:49

标签: python api rest

我第一次作为一个类项目构建RESTful API,但令我困惑的是某些场景的错误处理。

当客户请求时:

https://localhost:8080/api/v1/user/<username>

我检查用户名变量有很多内容,例如:

  • 如果用户名为空或“空白”
  • 如果用户名是alphanumerical
  • 如果用户名的长度太短或太长

所以,我的代码目前看起来像这样,(它在Python中,但这是无关紧要的):

# We just grabbed the username variable

# if the username is blank, return 404
if not username:
    abort(404)
# if the username is not alphanumerical, return 404
if not alias.isalnum():
    abort(404)
# if the username length is less than 4 or greater than 25, return 404
if len(alias) < 4 or len(alias) > 25:
    abort(404)

在没有错误的情况下返回404错误“识​​别”对我来说似乎是错误的。

我是否应该返回显示错误的404错误代码(例如“给出的用户名不是字母数字”)?

我应该返回404以外的其他HTTP状态代码吗?

我非常困惑!

1 个答案:

答案 0 :(得分:1)

有许多类型的HTTP状态代码,您的REST API应返回该方案的正确代码。

这是一个很好的资源: http://www.restapitutorial.com/httpstatuscodes.html

此外,使用可为开发人员提供帮助的JSON有效内容进行响应。像这样简单:

{
    “kind”: “error#404”,
    “message”: string, // Give a short message about error
    “more-info”: string // Provide more detailed error report
}

希望有所帮助。

相关问题