dongqiya9552 2012-11-18 13:42
浏览 6
已采纳

HTTP JSON API响应的模式

I have a HTTP JSON API, which runs on php, on a small framework. This API is a wrapper for a databases pgsql functions. Php framework returns responses in such way:

{
  code: 200,
  data: []
} 

Codes are HTTP code responses (such as 200, 301, 302, etc). pgsql functions returns their own code (negative values for errors, positive for success results), message (meaning of code) and result data:

{
  code: -1,
  message: 'Wrong data',
  data: []
}

So, my packages from API are:

{
  code: 200,
  data: {
    code: 1
    message: 'Succeed'
    data: []
  }
}

Isn't it messy? Occur some confusions when writing client code, that requests this API. Maybe there are some standard patterns for making some kind of packages of API.

  • 写回答

2条回答 默认 最新

  • dongtan5555 2012-11-18 13:50
    关注

    Your API layout is not messy. As Botond suggested, it is actually pretty logical. The only change I would make to it would be to move your status codes into HTTP headers rather than in the JSON data, to reduce the format a bit. This will also allow you to easily differentiate between successful calls and errors.

    Suppose your API can answer with 4 different codes: 200, 201, 403, 404. Respectively: done, not changed, forbidden, not found. Instead of passing this as a JSON variable, you could easily bind it into the HTTP response header, as the values already exist and are well understood. This, as in this question, is a pretty well-accepted method of providing status codes, provided that you are not using this specific header for anything else.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?