Rails Routing & APIs: What Actually Happens Between the URL and Your Controller
When I started studying APIs more seriously, I realized there was a problem with the way I was learning. I knew how to create a Rails API. I knew how to write: resources :products I knew what GET , POST , PATCH and DELETE were supposed to do. But I wasn't always able to explain why things worked the way they did. So I decided to go one step back and review the fundamentals: routing, HTTP, REST and how Rails puts all of these things together. This is what I learned. Rails Routing At its simplest, routing is the thing that connects a URL to some code in your application. In Rails, this happens in routes.rb . For example: get '/about' , to: 'pages#about' If someone requests: GET /about Rails knows that it should call: PagesController #about Pretty straightforward. But Rails gets much more interesting when we start using RESTful routes. resources does a lot of work Instead of manually defining every route for a resource: get '/products' , to: 'products#index' get '/products/:id' , to: 'products#show' post '/products' , to: 'products#create' patch '/products/:id' , to: 'products#update' delete '/products/:id' , to: 'products#destroy' Rails lets us write: resources :products And generates the conventional CRUD routes for us. HTTP Verb Action Purpose GET index List resources GET show Show one resource GET new Form for a new resource POST create Create a resource GET edit Form to edit a resource PATCH update Update a resource DELETE destroy Delete a resource This is one of the reasons Rails feels so productive. The framework isn't just giving us routing functionality. It is encouraging a convention. resource vs resources This one confused me for a while. resources represents a collection: resources :products There can be many products, so Rails generates an index route. resource represents a single resource: resource :profile There isn't an index because we're talking about one profile. It is a small difference, but it makes sense once you think about the resource you're mo