DRY up your JSON APIs with Rails

Making an API in rails can become very ugly if not done correctly. Odds are, your API requirements include something like the following:

  • Authentication
  • CRUD operations
  • Useful error messages


Let's start with the easiest part: authorization.

We clearly see that the @user = User.find_by(api_key: request.authorization) is repeated twice. Let's move that into a before_action.

To follow best practices, we will make the following changes:

  1. Make an ApiController for other API controllers to inherit
  2. Set the @user object as current_user.

The ApiController will be the base for our future API controllers.

Finally, we can inherit from the ApiController and all of our actions will be protected:

Re-Usable Views

An easy way to render your models is to use the to_json method. However, it can prove to be painful if you wish to use only specific fields, especially if they're nested. For example:

The solution is to bring the V back into MVC for your APIs using a tool like jbuilder. Your controller method will look very light and simple:

And your view will look like this:

DRY up your CRUD with rescue_from

It may be tempting to follow the traditional flow of rails model saving:

By using the rescue_from method, you can significantly DRY up your code. Let's add to our ApiController:

Now the rest of your controllers can become incredibly DRY:

Better Error Messages with StrongParameters

For DRY and useful API error messages, you can also use StrongParameters to your advantage:

And now in your other controllers:

Now your end user will automatically be given a descriptive error message if they forget a parameter!

comments powered by Disqus