Sign Up

Talk Programming , Career, Mental Health, Talk Personal Finance ❤️‍ Post a query and receive responses ✅

Sign In

Post a query and receive responses. Ask anything, Ask Mitra ❤️‍

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Sorry, you do not have permission to ask a question, You must login to ask a question.

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Proper API Response structure {}; Importance & Advantages!

Proper API Response structure {}; Importance & Advantages!

Before starting to write anything about API, I would like to mention that all this is my personal thoughts based on my knowledge, experiences, and issues I have faced in the past. 

It is the modern age of the Internet, and there are thousands, if not millions, of websites we have stumbled upon. Hundreds of which may be dynamic (i.e., fetch data whenever we request it from some data source).

The whole process of data fetching, in most cases, is done through an API (SOAP, REST or GraphQL). Thus, you can consider an API as the translator between two people who speak two different languages. Just imagine what would happen if the translator translated it wrong.

Things to consider in the API

Communication is key!
Thus, there are lots of things which I think we should consider when setting up an API response.

Do not use top-level data objects or Arrays in the API.

I used to think it was easy to just send the data after fetching it directly from the database.
For example, sending this response for an API call https://api.xyz.com/users/1

{
  "fullName": "Full Name",
  "dateOfBirth": "2000-01-01"
}

Or the e.g. below for API callshttps://api.xyz.com/users

[
  {
    "fullName": "First User",
    "dateOfBirth": "2000-01-01"
  },
  {
    "fullName": "Second User",
    "dateOfBirth": "1990-04-04"
  }
]

While it will be easy to return the data like this, it will cause a huge problem sooner or later.
The major problem is that we can’t add extra information in the first response object, and it’s not even possible in the second response array.

Use consistent variable name casing in the API

There are variable ways to name a variable:

  • CamelCase is the popular one among JavaScript developers.
  • Snake_case is the popular one among Python developers (snake_case for Python developers… what a coincidence…).
  • PascalCase
  • kebab-case

I think it was not really necessary to mention it because developers using a specific language already have their own preference over variable name casing.

Just a note from my side; using multiple name casings in a single project is a big NO!
If possible, I would even suggest everyone grab a name casing technique and follow it throughout the entire journey of programming in life.

Use proper variable names in the API

This is not just for the API response object, but also the codes itself and Database entity itself as well.

I am pretty sure there are thousands of articles/notes talking about how variable names should be written, so I am not going to go in depth, but I would like to attach a simple yet important note about this topic:
Variables’ names should be “As short as possible, as long as required“!

Solution

The simple yet powerful solution to the API response structure is to simply have the data structure as follows:

For example, sending this response for an API call https://api.xyz.com/users/1

{
"message": "Successfully fetched User data",
"data": {
  "fullName": "Full Name",
  "dateOfBirth": "2000-01-01"
}

Or the e.g. below for API call https://api.xyz.com/users

{
  "message": "Successfully fetch Users data",
  "pagination": {
    "page": 1,
    "count": 2,
    "perPage": 10
  },
  "data": [
    {
      "fullName": "First User",
      "dateOfBirth": "2000-01-01"
    },
    {
      "fullName": "Second User",
      "dateOfBirth": "1990-04-04"
    }
  ]
}

You might have already noticed that I am able to send messages in the API response. And also, in the second API usage example, I am even able to send pagination details.
There will be thousands of data processing happening, so pagination is obviously to be done sooner or later. However, in the previous approach, we could not properly mention the pagination details. which we have overcome.

You might now be wondering, Isn’t it painful to access the data going one more level deep in the object? i.e. response.data instead of response.
The answer is yes, but apart from that downside, it’s the only good point I can think of.

For example, let’s say we have to respond with an error message if the API request is invalid. Following this approach, we can simply send the response like:

{
  "message": "Invalid email address" // or any other error message
}

And now in the frontend/mobile app, we can always refer to response.message to get information about the API usage. And to understand if the API call was a success or failure, we can use the HTTP status code of the API call.

The main point

The major point of all this discussion is that the APi response should never be a top-level data object itself.

Instead, use an object which contains all the information you want to share from server to frontend (not related to the API).
And within the top-level object, include the data related to the API call inside a result or data key.

This will result in clean and consistent API responses across every API endpoint. And also, you will be able to share extra information that is not related to the specific API call.

Conclusion

I have made this mistake in the past and learnt the hard way from it. That doesn’t mean you have to make this mistake yourself to learn.
You can try implementing this approach I have mentioned in your next project (or even your current project if possible without major breaking changes).

If you are someone developing an API, I would love to hear your thoughts about this approach and if you would like to switch to this approach (if not already using it).
If you are someone who consumes an API, I would love to hear your thoughts about how this change (if it is not what your current API provides) would affect you.

If you are already using this approach, then cheers. You are making life for yourself and the frontend developer easy. 😉

Originally posted at: https://santoshb.com.np/blog/importance-of-proper-api-response/

Related Posts

You must login to add a comment.

1 Comment