Why You Should Taste Grape
Hi folks, let's talk about APIs today.
I know that Rails 5 with
--api mode is around the corner. But I need to say you how awesome is to build APIs with Grape. I will show you why.
What are the main features we expect from a good API?
- Parameter validation
- Parameter coercion
The first four items are the ones in which Grape really shines for me. I am going through one at a time.
For this tutorial, let's suppose we need to build an API to create and list customers.
Ok, this is our starting point. Anyone used to Rails can grasp this snippet.
We have two routes, the first to create and the second to get customers.
Something nice in Grape is that we can declare and validate the expected params in every route.
Parameter validation is as simple as telling Grape what we want. Given our base code above, we can simply add some validation by doing:
declared(params, include_missing: false) returns only declared params which aren't missing (has some value).
If any validation fails, a 400 HTTP status code will be automatically returned with the error(s).
Sometimes we need to treat some param before using it. Look how easy it is:
Here we strip the occupation param.
A good API must be well documented.
We are able to document the response of each endpoint. Check grape-swagger to see what you can do with it.
With grape-entity we can organize our serialization code and keep it dry:
It will return only the specified attributes.
Ok, it seems nice, but..
I like Rails. Do I have to stop using it to use Grape?
No! You can mount a Grape API inside your Rails application (or Sinatra, Rack..).
Read Grape's readme and give it a try.