This tutorial assumes that you have Ruby installed using either rbenv or rvm

Building a Todolist is usually one of the most basic steps in learning a web framework for any platform. There is an increased use of web applications using the SPA (Single Page Application) architecture, where the client-side templating is generated by Javascript while the data is generated from a backend server. Usually, this data is consumed by a Javascript framework such as React, Angular or Vue.js. This tutorial is here to teach you how to build out a Restful API using Ruby on Rail 5.

Project Setup

First create a new directory and cd into it.

mkdir todolist  && cd todolist

Then install rails 5.1

gem install rails

Once Rails is installed create the project by running

rails new todolist --api --database=postgresql

Setting up the Database

Then run the server to make sure it works

rails server
Rails Start Page

Rails Start Page

Configure your config/database.yml for your current Postgres db instance

default: &default
      adapter: postgresql
      encoding: unicode

      pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>




development:
  
       <<: *default
  
       database: TodoList

Once your database config is set up, you can create the db by running

rails db:create

Scaffolding the API

To finally be able to build out our todos, first we need to generate an ActiveRecord model that represents a todo. In your command line, run

rails generate model Todo title:string description:text finished:boolean

This will create a todo.rb file in your app/models folder that represents an active record model for your todo.

class Todo < ApplicationRecord
end

This will also create a migration file to create the todo table in your database.

class CreateTodos < ActiveRecord::Migration[5.1]
  def change
    create_table :todos do |t|
      t.string :title
      t.text :description

      t.timestamps
    end
  end
end

Now run rails db:migrate to persist these changes to the database.

Postgres Rails Todo Schema

Postgres Rails Todo

Creating the Controllers

Now that we have out models create, now we must create a controller to handle our CRUD functions. Run

rails generate controller Todos

This will generate an empty controller

class TodosController < ApplicationController
end

Controller Methods

One of the first things that I like to do is specify our whitelist and our callbacks

This makes sure someone doesn’t set a field that they shouldn’t as well as cut down on redundant code.

private

    def set_todo
   
       @todo = Todo.find(params[:id])
  
    end
    def todo_params
     params.require(:todo).permit(:title, :description, :finished)
    end

Now lets create our before action that will be called on specify route methods

before_action :set_todo, only: [:show, :update, :destroy]

We will also create the individual CRUD methods for each REST route.

before_action :set_todo, only: [:show, :update, :destroy]


# GET /todos

def index
  
    @todos = Todo.all



end

# GET /todos/1


def show

end




def create
  
    @todo = Todo.new(todo_params)

  
    if @todo.save
    
      render :show, status: :created, location: @todo
  
    else
    
      render json: @todo.errors, status: :unprocessable_entity
  
    end

end




def update
  
    if @todo.update(todo_params)
    
       render :show, status: :ok, location: @todo
  
    else
    
        render json: @todo.errors, status: :unprocessable_entity
  
    end

end 

def destroy
  
    @todo.destroy

end



private
 
    def set_todo
    
      @todo = Todo.find(params[:id])
  
    end

  
    def todo_params
    
      params.require(:todo).permit(:title, :description, :finished)
  
    end

Routing

To be able to access the routes we’ll have the resource to our config/ routes.rb file

resources :todos, defaults: {format: :json}

You can check that this works by running rails routes

Rails routes todolist

Rails routes todolist

JSON Templates

The next step is to create json templates for your models. This can be done by creating a todos folder under views along with these 3 files

Todo List Template Directory Structure

Todo List Template Directory Structure

_todo.json.jbuilder

json.extract! todo, :id, :title, :finished

index.json.jbuilder

json.array! @todos, partial: 'todos/todo', as: :todo

show.json.jbuilder

json.partial! "todos/todo", todo: @todo

These map to the methods in your controllers.

Once that is done, make sure to uncomment the jbuilder gem in your gemfile.

gem 'jbuilder', '~> 2.5'

Testing Rest Endpoints Insomnia

Now that our app is built out, lets test some of our endpoints. We’ll use a tool called Insomnia. It’s similar to POSTMAN but the user interface is more

Testing POST Requests

First let’s create a json Post request with the required parameters at http://localhost:3000/todos. This should return the JSON Object with an Id. Do this several more time to create a list of Todos.

Json Post Request Rails

Json Post Request Rails

Testing GET Requests

Once we’ve created that list, now do a GET Request to http://localhost:3000/todos. This should return the list of Todos that you created.

Get Request Rails Todolist

Get Request Rails Todolist

Test several of the individual Get Requests by going to http://localhost:3000/todos/{id}.

Individual Get Request

Individual Get Request

Testing PUT Request

You can also change data in a specific Todo by creating a Put Request. Let’s change one of the Todos to finished.

Put Request Rails TodoList

Put Request Rails TodoList

Testing Delete Requests

Now let’s delete a todo. Create the delete requests with the Id as the parameter in the URL http://localhost:3000/todos/{id}

Delete Request Rails Todolist

Delete Request Rails Todolist

Conclusions

As you can see, the basics of getting started with Rails API development is fairly simple. Once your app is up and running, you can use SPA frameworks such as  React or Angular to consume the data from your REST API. Then you can add other features like associations and authentication to your app to make it more practical. Those will be covered in future posts.

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit