Stop making this API design mistake, stop returning just a value in your API responses. Always return an object | #API Design Tip

By | January 23, 2021

Web APIs SHOULD NOT just return a boolean, string or a number/integer value in the response body for any response.

Take the following.

If you have an operation which for a successful (2XX) creation operation, returns just the value of the new object’s identifier in the response body, like the below examples, then you are opening yourself to future problems.

Returning back an integer value

123

Or returning back a string value

"f536f2d4-219b-4f7c-861f-5feb8651d7ef"

Or returning the operation outcome, which is not recommended because if you are using HTTP codes correctly, you should not need to return an operation status, but if you need to, then do what you need to do.

true

Why should I not return only a value in the API response body?

Well, what happens when the operation needs to returning another value (another field or object in the response).

You would need to change the response to return an object rather than a value because now you need to return multiple properties or objects in the response. That would introduce a breaking change because now the response schema would require changes by the clients. After all, now you could have something like the below JSON.

{
  "customerId": "f536f2d4-219b-4f7c-861f-5feb8651d7ef",
  "firstName": "Daniel",
  "lastname": "Tammadge"
}

And with a breaking change, you have two choices. Change to all your clients to support the new response, or you would need to support multiple versions of the operation.

However, if you designed the API to return an object instead of only a value in the body in the first case, then you would not need to introduce a breaking change or introduce the need to maintain a new version of the operation.


Note: This should be followed for handling errors & validations as well.


Leave a Reply