janpio
janpio

Reputation: 10922

RESTful API: How to model JSON representation?

I am designing a RESTful API for a booking application. You can request a list of accommodations. And that's where I don't really know how to design the JSON represenation. This is my XML representation:

<?xml version="1.0" encoding="utf-8"?>
<accommodations>
    <accommodation>
        <name>...</name>
        <category>couch</category>
    </accommodation>
    <accommodation>
        <name>...</name>
        <category>room</category>
    </accommodation>
<accommodations>

My first try to convert this to JSON resulted in this output (1):

{
    "0": {
        "name": "...",
        "category": "couch"
    },
    "1": {
        "name": "...",
        "category": "room"
    }
}

But as I looked how others APIs did it, I found something looking more like this (2):

[
    {
        "name": "...",
        "category": "couch" 
    },
    {
        "name": "...",
        "category": "room" 
    }
]

I know version 1 is an object, and version 2 an array.

But which one is better in this case?

Upvotes: 3

Views: 2522

Answers (3)

Localist
Localist

Reputation: 1124

Stick with number 2.

Don't model your JSON output after your XML version.

Every major API out there uses representations with Arrays. Most parsing libraries will return List-like instances that make it very easy to manipulate all the objects they contain.

Number 1 is valid JSON but, it's not what the vast majority of your developers will be expecting.

Upvotes: 0

dafmetal
dafmetal

Reputation: 785

You could model the JSON as follows:

{
  "accomodations" : [
    {
      "accomodation" : {
        "name": "...",
        "category": "couch",
        "uri": "http://example.org/accomodations/accomodation_1"
      }
    },
    {
      "accomodation": {
        "name": "...",
        "category": "room",
        "uri": "http://example.org/accomodations/accomodation_2"
      }
    }
  ]
}

and you could return this on a GET http://example.org/accomodations Creating a new accomodation could then be done through a POST http://example.org/accomodations with something like the following in the body:

{
  "accomodation": {
    "name": "...",
    "category": "room"
  }
}

Upvotes: 2

extraneon
extraneon

Reputation: 23980

If you are going to use the key (1, 2, ...) as the identifier in communications back to the server the dictionary is better, otherwise I'd go for the array. The unique id then is probably a field in an entry.

Upvotes: 0

Related Questions