Making an API in rails can become very ugly if not done correctly. Odds are, your API requirements include something like the following:
- 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
To follow best practices, we will make the following changes:
- Make an
ApiControllerfor other API controllers to inherit
- Set 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:
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
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!