KrisG
KrisG

Reputation: 1091

Rails implement an API using Routes pointing to existing controller actions

I have a Rails app that does everything I need it to do via a HTML interface, now I'd like to bolt on an API providing access to bits of the functionality.

How would I do this selective forwarding of some API controller actions to another controller's actions using the Routes.rb?

I have tried the following:

My regular controller routes work fine using:

match 'stuff' => 'stuff#index'
get 'stuff/index'
get 'stuff/some_get_action'
post 'stuff/some_post_action'

But then when I try for my API:

match 'api' => 'api#index'
match 'api/some_get_action' => 'stuff#some_get_action', :via => :get
match 'api/some_post_action' => 'stuff#some_post_action', :via => :post

or...

match 'api' => 'api#index'
get 'api/some_get_action', :to => 'stuff#some_get_action'
post 'api/some_post_action', :to => 'stuff#some_post_action'

I get an error. When I navigate to /api/index to server a HTML page that contains forms for testing the API URLs the url_for raises a 'Routing error' exception saying 'No route matches...'.

Upvotes: 0

Views: 648

Answers (1)

Carson Cole
Carson Cole

Reputation: 4451

You may want to include ':as => ' and define your route names that you may be using as your link paths.

get 'api/some_get_action' => 'stuff#some_get_action', :as => 'some_get_action'

and the link path in your index file will have 'some_get_action_path'. Not sure that 'match' or 'get' automatically resolves to a path name, which by setting ':as' it definitely will.

I like your idea for setting up this page for testing. I'm always doing it in the console, which is surely more difficult than simply clicking a link. Your links probably need to infer that they are :json requests, not :http.

Upvotes: 1

Related Questions