dongtan9066 2017-02-28 08:47
浏览 51
已采纳

REST API设计的GET方法中的HTTP状态代码

I am learning about the best practices involved in REST API design and wrote a function which handles the GET /cities HTTP/1.1 query.

This function contains cities which is a struct array that holds the cityname, citycode of multiple cities.

Below is the code

func FindCitiesHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json;charset=UTF-8")

    if len(cities) == 0 {
            w.WriteHeader(404)
            return
    }

    if err := json.NewEncoder(w).Encode(cities); err != nil {
            /* what to do here? */
    }

    w.WriteHeader(200)    

}

Now when I started thinking about the possible outcomes of this function. I found these situations.

  1. It returns all the cities properly as JSON response successfully. So I return 200 http status.

  2. The list of cities is empty. So there is nothing to return. So I return 404 (resource not found)

  3. It is about to return JSON response of all cities, but something gone wrong during JSON encoding. Now I am confused here, how do I deal with this situation.

I mean how do you convey message properly to user, if

  1. If your business/application logic had some error/exception.
  2. If data access logic found some issues. (say connection to database is not reachable)

Could you guys please help me to suggest best practices you followed in these situations?

  • 写回答

1条回答 默认 最新

  • douci2015 2017-02-28 11:53
    关注
    1. 200 is correct
    2. 404 is probably not correct; A list of cities can be empty, and still exist. (Think: A 0-length array is still an array.) You should probably return 200. You would only return 404 if the list of cities doesn't exist on your server (in other words, that should probably never happen with your API).
    3. If you experience an internal server error, such as with marshaling JSON, you should return an Internal Server Error, status 500.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大