Grape: Routing Multiple Methods

Back | grape, rails, ruby | 11/3/2011 |

Sometimes you want to support both GET and POST in a Grape API.

If you want to support GET you would write something like get [path] do. If you want to support POST you would write post [path] do. What are those get and post methods anyway? The answer is in Grape’s api.rb.

  1. def get(paths = ['/'], options = {}, &block); route('GET', paths, options, &block) end
  2. def post(paths = ['/'], options = {}, &block); route('POST', paths, options, &block) end
  3. def put(paths = ['/'], options = {}, &block); route('PUT', paths, options, &block) end
  4. def head(paths = ['/'], options = {}, &block); route('HEAD', paths, options, &block) end
  5. def delete(paths = ['/'], options = {}, &block); route('DELETE', paths, options, &block) end

These call route, which starts as follows.

  1. def route(methods, paths = ['/'], route_options = {}, &block)
  2.   methods = Array(methods)
  3.   ...
  4. end

The Array construct will take anything and make it into an array, unless it’s already one. Which means that we can pass an array of methods to route. This is definitely part of Ruby magic, a C# or Java developer would strangle you for accepting object as a parameter and then transforming it into [ object ] – but this is completely kosher in Ruby. But I digress, in order to route multiple methods for a single API we can invoke route directly instead of get or post.

  1. route ['GET', 'POST'], "foo/bar" do
  2. # API code goes here
  3. end