API data structure

Posted 2 years ago by tiagomatosweb

Hi guys, Recently, we have had so much discussion in the office about how we should structure our API data to provide better data to the front end. Thus, I would like to know how devs think about it nowadays. I'm sorry for the long post.

  1. First discussion => One level data or nested data. Some devs rather consume an API receiving that with just one when the record has any related models, like so:
{
  "status": "ok",
  "data": {
    "id": 1,
    "title": "My title",
    "category_id": 1,
    "category_name": "News",
    "post_type_id": 5,
    "post_type_name": "Highlight"
  }
}

Others prefere nested data like so:

{
  "status": "ok",
  "data": {
    "id": 1,
    "title": "My title",
    "category_id": 1,
    "post_type_id": 5,
    "category": {
      "id": 1,
      "name": "News",
    },
    "postType": {
      "id": 5,
      "name": "Highlight"
    }
  }
}

What do you prefer, what is better in your opinion and reasons?

  1. Second discussion: Single endpoint vs multiple endpoint We have had a discussion about what is the best way to provide data to front end. Let say that the front end need to have a bunch of data to make the system works. This data is kinda big because it has a lot of stuff involved. Let say we could have this:
{
  "status": "ok",
  "data": {
    "id": 1,
    "title": "My title",
    "files": [...],
    "invitedCollaborators": [...],
    "invitedInstitutions": [...],
    "tasks": [...],
    "faculties": [...],
    ...
  }
}

Would you create one endpoint that resolves all dependencies and throw only on big object like above, or would you prefere create separate endpoints to call each chunks, for instance: http://api.myproject.com/project/1 http://api.myproject.com/project/1/files http://api.myproject.com/project/1/invited-collaborators http://api.myproject.com/project/1/invited-institutions http://api.myproject.com/project/1/tasks http://api.myproject.com/project/1/faculties And then let the front end resolve this dependencies?

  1. Third discussion: generic object name (data) or descriptive object name (project). For instance, would you prefer return this with generic object called always data
{
  "status": "ok",
  "data": {
    "id": 1,
    "title": "My title",
  }
}

or this with a more descriptive name for the object

{
  "status": "ok",
  "project": {
    "id": 1,
    "title": "My title",
  }
}

These are only small representative example to illustrate our scenario. Glad you hear your thoughts. Thank you very much!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.