Chapter 14. Designing an API

 

This chapter covers

  • Creating JSON responses using ActiveModel::Serializers
  • Creating an API namespace
  • Request testing and using HTTParty for manually interacting with your API
  • Responding appropriately to common API errors

It’s becoming more and more apparent that if you have an application of any significance, you’re going to need an application programming interface, or API. Some applications are only an API. ProgrammableWeb (www.programmableweb.com/), a blog that keeps track of the API space, has a directory of APIs, and at the time of writing, there are 13,628 being tracked. By the time you read this, there could be over 15,000 listed. That’s a lot of APIs!

In this chapter, we’ll compare a few different ways to build APIs, and then you’ll build one. Let’s get going.

14.1. An overview of APIs

For a very long time, it’s been considered good practice in computer science to give your programs a deliberate structure. By “a very long time,” we mean an eternity in computer years: since March 1968. Edsger Dijkstra wrote a paper for that month’s edition of Communications of the ACM, titled “Go To Statement Considered Harmful,” in which he, in his well-known style, declares that using structured programming is the only proper way to write good software. Since then, a great deal of computer science work has been predicated around the proper way to actually structure programs. One example is the MVC pattern that you’ve been applying throughout this book.

14.2. Using ActiveModel::Serializers

14.3. API authentication and authorization

14.4. It’s not a party without ... HTTParty

14.5. Handling errors

14.6. A small refactoring

14.7. Summary