FindFurryFriend Project (part 2) — Rails API (routes)

Meghan Elizabeth
2 min readMay 17, 2021

--

Photo by Alvan Nee on Unsplash

RESTful Routes

Routes are the code that listens and receives requests.

RESTful (Representation State Transfer) routing is a conventional pattern on how to handle URL’s. It provides mapping from HTTP verbs (get, post, put, patch, delete) to controller / CRUD actions (create, read, update, destroy). Consistent names for URL’s result’s in an app thats much easier to navigate.

Ex) Below are the 7 RESTful routes with a pets example

Rails Router

Rails router allows us to define URL’s and dispatch them to a particular controller action.

For example, when our Rails app receives an incoming request to GET /pets/3. It goes through our Rails routes file to match it to a controller action.

get '/pets/:id', to: 'pets#show'

In the code above we see that the GET /pets/:id request is dispatched to our pets controller’s show action. We could write each route out like that but rails made it even easier for us by creating resource routing. Instead of typing out each one like the above example we can type resources :pets and that will create seven RESTful routes in our application.

Below is what resources :pets creates

Controller Namespace and Routing

What if we don’t want our URL to be www.something.com/pets? What if we want our URL to be www.something.com/admin/pets?

We can do that! We can namespace our routes which is useful when we want to organize groups of controllers together.

namespace :admin do 
resources :pets
end

Nested Routes

We can also nest our resources. When we nest resources, these are children of other resources. In my model classes- pets belong to shelters. So in order to see all pets of a specific animal shelter (/shelters/:id/pets), we need to nest our pets resources inside of our shelters resources (shown below).

Shown below is my code in FindFurryFriend. Here are a couple examples of URL’s for FindFurryFriends:

  • /api/v1/shelters/:id/pets
  • /api/v1/shelters/:id/pets/:id

Summary

  • Rails router allows us to define URL’s and dispatch them to a particular controller action — get '/pets/:id', to: 'pets#show'
  • Rails resources cleans up our code and gives us the 7 RESTful routes in just one line
  • Namespace allows us to organize groups of controllers together
  • Nest a child route under a parent (example: to see all the pets in a specific animal shelter)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response