API endpoint flexibility

26 Mar 2024 | 1 minute read

Let's say you have an endpoint in your API that returns the cost for something.

GET: api/v1/cost

And the endpoint returns the following value.

number | null;

Looks good, right?

It does, until you're interested in adding more values in the response. If you have external clients using your API, you're unable to do so without making breaking changes.

If the endpoint would have been designed to return a object instead:

{ cost: number}  | null;

Adding another property to the returned value would have been straightforward and backwards compatible.

{ cost: number, discount?: number } | null

As most products are constantly evolving, it is often impossible to know how these will affect the API in the future. By returning an object instead of the value, you've added more flexibility to your API.