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:
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:
- Index: Retrieves all resources, mapped to
GET /todos. - Show: Retrieves a single resource by ID, mapped to
GET /todos/:id. - Create: Creates a new resource, mapped to
POST /todos. - Update: Updates an existing resource by ID, mapped to
PUT /todos/:id. - Destroy: Deletes an existing resource by ID, mapped to
DELETE /todos/:id.
Path parameters in Rails are defined within the route itself using a colon (:) followed by the parameter name, such as . When a request hits a route with a path parameter, like , Rails captures the value in the URL and makes it available through the hash within the relevant controller action. For instance, in the action captures the segment from the URL, allowing the action to fetch the corresponding todo item from the data store. The 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.
First, we will create the index method in the TodosController. This method will handle GET requests to fetch all todo items.
Explanation:
def index: This defines theindexaction within the controller.todos = TodoService.get_all: Calls theget_allmethod fromTodoServiceto 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.
Explanation:
class TodoService: Defines theTodoServiceclass.@todos = []: A class variable to store the todo items.def self.get_all: Defines a class methodget_allto return all todo items.
Next, we implement the show method to handle GET requests for fetching a specific todo item by ID.
Explanation:
def show: This defines theshowaction within the controller.todo = TodoService.get_by_id(params[:id]): Calls theget_by_idmethod fromTodoServiceto fetch a specific todo item, using theIDfrom 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.
Explanation:
def self.get_by_id(id): Defines a class methodget_by_idto find a todo item by itsID.@todos.find { |todo| todo[:id] == id.to_i }: Finds the todo item in the@todosarray with the matchingID.
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:
Similarly, to show a specific todo item, we can send the GET request to the todos/:id route:
In this lesson, we covered:
- Setting up the
TodosControllerwithindexandshowmethods to handleGETrequests. - Creating and using the
TodoServicefor fetching all todos and specific todos byID. - Testing
GETqueries 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.
