RESTful API: how to model a JSON representation?

I am developing a RESTful API for a reservation request. You can request a list of numbers. And this is where I really don't know how to design a JSON representation. 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 attempt to convert this to JSON led to this conclusion (1):

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

But when I looked at how other APIs did it, I found something similar to this (2):

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

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

But which one is better in this case?

+3
source share
3 answers

You can simulate 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"
      }
    }
  ]
}

GET http://example.org/accomodations POST http://example.org/accomodations - :

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

(1, 2,...) , , . , , .

0

Stick with number 2.

Do not model your JSON output after your version of XML.

Each main API uses representations with arrays. Most parsing libraries return List-like instances, which make it easy to manage all the objects they contain.

Number 1 is valid JSON, but that is not what most developers expect.

0
source

Source: https://habr.com/ru/post/1743356/


All Articles