0

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.

Larry Foobar
  • 11,092
  • 15
  • 56
  • 89

2 Answers2

1

See you have to read the responses in Iterative manner. You can read the JSON response and then check if the data field has another object/array.

You have to assess the code and show error messages on all codes except 200.

Rahat Khanna
  • 4,570
  • 5
  • 20
  • 31
1

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.

Community
  • 1
  • 1
Sébastien Renauld
  • 19,203
  • 2
  • 46
  • 66
  • Do you mean, to move up `code` field from `data`, and rename it? For example `status` field? Then `data` field will have `message` and `data` fields... – Larry Foobar Nov 18 '12 at 14:01
  • No, to move it in the HTTP headers entirely. As you are using the same status codes as HTTP, you might as well go fully RESTful and remap them. I'll edit my answer for more clarity and formatting. – Sébastien Renauld Nov 18 '12 at 14:02
  • Understood. So, If I move `code` field into HTTP header, response consists only of data. – Larry Foobar Nov 18 '12 at 17:33
  • Pretty much. Add to that the fact that others highlighted - data should either be an object or an array, not switch between the two. Otherwise, you'll have to write a lot of extra JS to find out what exactly was returned, which will do your head in. – Sébastien Renauld Nov 18 '12 at 17:34
  • i think `data` should be always an array(with one or many objects). It's some kind of universal. – Larry Foobar Nov 18 '12 at 18:36