Welcome to the first lesson of the "Using REST API to Build ToDo App with Ruby on Rails" course. In this lesson, we will learn how to set up GET
queries to fetch all Todos and fetch a specific Todo by ID
. These fundamental actions are crucial for interacting with and displaying the data in our ToDo application.
In a RESTful API, GET
requests are essential as they enable the retrieval of resources from a server. By the end of this lesson, you'll be equipped to handle these GET
requests to display all todo items or a selected single item.
Before diving into the specific functionalities of GET queries, let’s briefly revisit the existing setup, specifically the routes defined for our ToDo app.
Here’s a quick look at how our routes are set up to direct REST requests to the appropriate controller actions:
Ruby1Rails.application.routes.draw do 2 resources :todos 3end
This code sets up common REST routes for the todos
resource, which will trigger the corresponding methods in the TodosController
.
In Ruby on Rails (RoR), naming conventions and path parameters are crucial for setting up RESTful routes and ensuring the corresponding controller actions are correctly mapped.
Naming conventions in Rails follow standard REST principles. For example, GET /todos
maps to the index
action in the TodosController
to retrieve all todos, while GET /todos/:id
maps to the show
action to retrieve a specific todo by its ID. The resources :todos
declaration in the routes.rb
file automatically sets up these routes and others, adhering to RESTful conventions:
GET /todos
.GET /todos/:id
.POST /todos
.PUT /todos/:id
.DELETE /todos/:id
.Path parameters in Rails are defined within the route itself using a colon (:
) followed by the parameter name, such as :id
. When a request hits a route with a path parameter, like GET /todos/1
, Rails captures the value in the URL and makes it available through the params
hash within the relevant controller action. For instance, params[:id]
in the show
action captures the ID
segment from the URL, allowing the action to fetch the corresponding todo item from the data store. The params
hash is a versatile structure in Rails that stores parameter values from the URL, form data, and other request parameters, making them easily accessible within controller actions.
The integration of these conventions and parameters ensures a clean and predictable routing mechanism in Rails applications, making the codebase easier to understand and maintain. It also facilitates a clear separation of concerns, as routes map neatly to their respective controller actions based on standard conventions.
First, we will create the index
method in the TodosController
. This method will handle GET
requests to fetch all todo items.
Ruby1class TodosController < ApplicationController 2 def index 3 todos = TodoService.get_all 4 render json: todos 5 end 6end
Explanation:
def index
: This defines the index
action within the controller.todos = TodoService.get_all
: Calls the get_all
method from TodoService
to fetch all todo items.render json: todos
: Renders the retrieved todos as JSON.To keep our code organized, we use a service layer. This layer contains the business logic, keeping the controller clean and focused solely on handling requests. We will start by creating the get_all
method in the TodoService
to retrieve all todo items.
Ruby1class TodoService 2 @todos = [] 3 4 def self.get_all 5 @todos 6 end 7end
Explanation:
class TodoService
: Defines the TodoService
class.@todos = []
: A class variable to store the todo items.def self.get_all
: Defines a class method get_all
to return all todo items.Next, we implement the show
method to handle GET
requests for fetching a specific todo item by ID
.
Ruby1class TodosController < ApplicationController 2 def show 3 todo = TodoService.get_by_id(params[:id]) 4 render json: todo 5 end 6end
Explanation:
def show
: This defines the show
action within the controller.todo = TodoService.get_by_id(params[:id])
: Calls the get_by_id
method from TodoService
to fetch a specific todo item, using the ID
from the request parameters.render json: todo
: Renders the retrieved todo item as JSON.Finally, we implement the get_by_id
method to fetch a specific todo item by its ID
.
Ruby1class TodoService 2 @todos = [] 3 4 def self.get_all 5 @todos 6 end 7 8 def self.get_by_id(id) 9 @todos.find { |todo| todo[:id] == id.to_i } 10 end 11end
Explanation:
def self.get_by_id(id)
: Defines a class method get_by_id
to find a todo item by its ID
.@todos.find { |todo| todo[:id] == id.to_i }
: Finds the todo item in the @todos
array with the matching ID
.To ensure everything works correctly, we can test the GET
queries using a test script. This script will send HTTP requests to our endpoints and display the results.
To fetch all todo items, we can send the GET
request to the todos/
route:
Ruby1require 'net/http' 2require 'json' 3 4def get_todos 5 uri = URI('http://localhost:3000/todos') 6 response = Net::HTTP.get(uri) 7 puts "Todos: #{response}" 8end
Similarly, to show a specific todo item, we can send the GET
request to the todos/:id
route:
Ruby1def get_todo_by_id(id) 2 uri = URI("http://localhost:3000/todos/#{id}") 3 response = Net::HTTP.get(uri) 4 puts "Todo: #{response}" 5end
In this lesson, we covered:
TodosController
with index
and show
methods to handle GET
requests.TodoService
for fetching all todos and specific todos by ID
.GET
queries using a test script.You are now equipped to create GET
endpoints to fetch data in your Ruby on Rails ToDo application. Next, proceed to the interactive practice exercises to solidify your understanding. Experiment with the provided code snippets and explore different scenarios to deepen your learning.
Great job on completing your first lesson of this course! Get ready for more exciting lessons ahead as we continue to build out our ToDo app.