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条)

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上