It’s been pretty quiet here for a long time, but I’ve been busy building a few businesses, one of which includes a new product I’m helping to build and launch with a couple friends. One of the things I’ve been building is a robust REST API using Grape. If you want a quick overview, check out their README on the GitHub repo. I’ve really enjoyed using Grape and figured I’d share a few little tidbits of how I’m using it so far.
Configuring URL prefix
For a long time I was just using Rails 3 to “mount” my Grape API class like this:
1
| |
This worked well for a while, but then I had a need to plug in some Rack middleware (such as Rack::Cors, which I plan to
blog about soon). Long story short, I couldn’t mount it the same way anymore, but still needed to configure the base
URL for the API to point to /api. Grape makes this really easy.
1 2 3 4 5 | |
Quick side note, I do still mount the API in the Rails routes for the test environment only for my automated API
integration tests. But since I already have the prefix defined in the API, I just mount it to root for these purposes.
1 2 3 | |
Delegate to the Rails logger (if desired)
1
| |
Simple.
Request logging, including body
1 2 3 4 5 | |
Easy peasy.
Global exception handling
1 2 3 4 5 6 7 8 9 10 | |
Handy.
HTTP Basic Authentication
1 2 3 | |
No sweat.
Helper methods
1 2 3 4 5 6 7 | |
Straightforward.
Sending back errors with validation messages
1 2 3 4 5 6 7 | |
Smooth sailing.
General API building tips
I can’t recommend enough the article that John Nunemaker wrote recently on Creating an API. A great read with some great tips.
That’s all for now. Happy coding! :)