Don’t Make Me Think, When I Consume Your API

I recently worked on the voucher badge feature.  I needed to create an api endpoint to consume the voucher count, because we use services.

Unused Voucher Badge
The first iteration, the api passed voucher objects. However, I decided to refactor and pass the voucher count and less data between services, in hopes to shave couple milliseconds off load time. My first refactor looked like the following. Looking at the code, I know exactly what is happening and what data is being passed. It’s simple. 
unused voucher count as integer
Now imagine you’re consuming this new endpoint for the first time, with no knowledge of the implementation. You receive the following json object.  You might think, “Seven? what the hell does seven mean?” Then you’ll inevitably follow the source to VoucherController in order to understand.   

Instead, why not be explicit? Make it clear to everyone who consumes your lovely api what their getting back.

unused voucher count as a hash

That is so much better! Now I don’t have to visit the Api and look at the source code in order to understand what the object is.

So why not make others happy by telling them what their consuming, instead of making them think. Make your api intention explicit!
[EDIT]

Lets take this one step further and change our controller name as well. To be clear the vouchers controller only had one job of grabbing all unused voucher and returning the count. If it was part of a larger vouchers controller, I would have refactor it out instead .


Not only are we explicit with the object that is being returned, but the API name. I think this gives a better explanation of the api.

This post was based on a lightning talk I planned on giving at RubyConf 2014. However, the talks were cut short so I decided to make a blog post about it instead.

Standard