John Nunemaker: how to create an API

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

I have been asked to build an API for managing our subscribers. I’m researching how to build APIs in Rails. I previously linked to John Nunemaker’s debugging advice. I like these rules:

1. Document as You Build

2. Be Consistent

3. Provide the URLs

4. Present the Data

About #2, I find it easy in the short term but almost impossible over the long term. Give me a year and I’ll clutter any API with a stupid mix of return values. All the same, I really am in total agreement with what is written here:

As we documented the API, we noticed a lot of inconsistencies. For example, in some places we return a hash and in others we returned an array. Upon realizing these issues, we started making some rules.

To solve the array/hash issue, we elected that every response should return a hash. This is the most flexible solution going forward. It allows us to inject new keys without having to convert the response or release a whole new version of the API.

Changing from an array to a hash meant that we needed to namespace the array with a key. We then noticed that some places were name-spaced and others weren’t. Again, we decided on a rule. In this case, all top level objects should be name-spaced, but objects referenced from a top level object or a collection of several objects did not require name-spacing.

{users:[{user:{…}}, {user:{…}}]} // nope
{users:[{…}, {…}]} // yep
{username: ‘jnunemaker’} // nope
{user: {username:’jnunemaker’}} // yep

You get the idea. Consistency is important. It is not so much how you do it as that you always do it the same.

Post external references

  1. 1
    http://railstips.org/blog/archives/2011/12/01/creating-an-api/
Source