API Content Structures Pros and Cons

From today on I will write down notes of what I’ve learned from the book “Build APIS You Won’t Hate”.

Today the topic is about the response content structure.

JSON-API

The famous JSON-API suggests to use plural key for both single resources and resource collections.

{
  "users": [
    {
      "id": "1",
      "name": "bearzk"
    }
  ]
}

{
  "users": [
    {
      "id": "1",
      "name": "bearzk"
    },
    {
      "id": "2",
      "name": "tom"
    }
  ]
}

Pros

Cons

Twitter Style

Twitter uses another strategy instead, it will give you single thing or collection of things when you asked differently.

{
  "id": "1",
  "name": "bearzk"
}

[
  {
    "id": "1",
    "name": "bearzk"
  },
  {
    "id": "2",
    "name": "tom"
  }
]

Pros

Cons

Facebook Style

Ask for one, get one.

{
  "id": "1",
  "name": "bearzk"
}

Ask for more, get more, namespaced.

{
  "data": [
    {
      "id": "1",
      "name": "bearzk"
    },
    {
      "id": "2",
      "name": "tom"
    }
  ]
}

Pros

Cons

BAYWH Style

always with name space, also when other object wrapped within.

{
  "data": {
      "id": "1",
      "name": "bearzk"
  }
}

{
  "data": [
    {
      "id": "1",
      "name": "bearzk"
    },
    {
      "id": "2",
      "name": "tom"
    }
  ]
}

{
  "data": {
    "id": "1",
    "name": "bearzk",
    "comments": {
      "data": [
        {
          "id": "1234",
          "text": "Awesome API!"
        },
        {
          "id": "4321",
          "text": "Yeah!"
        },
        page: "1"
      ]
    }
  }
}

Pros

Cons