How to make REST API in Rails | Part 2

How to make REST API in Rails

Making a simple API in rails 

We have seen in the part-1 of this post How to make an end point through ReST to get the user info as Json“. If you haven’t covered up part-1, please go through it to have a better understanding of this tutorial.


So far, we have created an end point for show action which look like:
http://localhost:3000/api/v1/users/1

Now we will make more endpoints to create, update and delete a user.

Create action in Rails API

Let’s code “create action in app/controllers/api/v1/users_controller.rb


class Api::V1::UsersController < ApplicationController
respond_to :json
skip_before_filter :verify_authenticity_token

def show
respond_with User.find(params[:id])
end

def create
user=User.new(user_params) 
        # if the user is saved successfully than respond with json data and status code 201
        if user.save 
render json: user, status: 201
else
render json: { errors: user.errors}, status: 422
end
end

private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation) 
        end
end 


Here we have another private method user_params to sanitize the attributes to be assigned through mass-assignment. After successful creation of the user we are responding with the json data and status code 201.

Now, we need to tell our config/routes.rb file that we also have create action. Let’s add create action in config/routes.rb file


Rails.application.routes.draw do

# API routes path
namespace :api, defaults: { format: :json } do
namespace :v1 do
#devise_for :users
resources :users, :only => [:show, :create]
end
end
end


Hurray!!! We have successfully created the endpoint to create a user  which you can check through by sending a post request through POSTMAN (A tool to check API endpoints).

POST request through postman to create a user


Response of the POST request


Update action in Rails API

Time to update the user being already created. The update action responds to PUT/PATCH request.

Let’s add update action to app/controllers/api/v1/users_controller.rb

class Api::V1::UsersController < ApplicationController
respond_to :json
skip_before_filter :verify_authenticity_token

def show
respond_with User.find(params[:id])
end

# Creating users
def create
user=User.new(user_params)

if user.save
render json: user, status: 201
else
render json: { errors: user.errors}, status: 422
end
end

# Updating users
def update
user = User.find(params[:id])

if user.update(user_params)
render json: user, status: 200
else
render json: { errors: user.errors }, status: 422
end
end

private

def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end


You might have guessed the next step, yes, now we need to add the update action in config/routes.rb file too. So let’s do it.

Rails.application.routes.draw do

# API routes path
namespace :api, defaults: { format: :json } do
namespace :v1 do
#devise_for :users
resources :users, :only => [:show, :create, :update]
end
end
end


Now Let’s test our update action.

Update action through POSTMAN 


Update action response


Destroy action in Rails API

Destroy action is used to delete a record and here we are going to delete a user. So let’s add the destroy action in app/controllers/api/v1/users_controller.rb

class Api::V1::UsersController < ApplicationController
respond_to :json
skip_before_filter :verify_authenticity_token

def show
respond_with User.find(params[:id])
end

# Creating users
def create
user=User.new(user_params)

if user.save
render json: user, status: 201
else
render json: { errors: user.errors}, status: 422
end
end

# Updating users
def update
user = User.find(params[:id])

if user.update(user_params)
render json: user, status: 200
else
render json: { errors: user.errors }, status: 422
end
end

# Deleting users
def destroy
user = User.find(params[:id])
user.destroy
head 204
end

private

def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end


Here we are deleting the user with a particular ID which is being passed as a parameter and after successful deletion of the user we are giving 204 code which means the server has processed the request and doesn’t return any content. We may also respond with 200 status code but this is more suitable.

Remember to update config/routes.rb file


Rails.application.routes.draw do

# API routes path
namespace :api, defaults: { format: :json } do
namespace :v1 do
#devise_for :users
resources :users, :only => [:show, :create, :update, :destroy]
end
end
end


Destroy action with POSTMAN


Destroy action response


Congratulations!! you are done with the CRUD part of a ReSTful API in Rails.

Further you can dockerize this Rails app – Follow this post to dockerize this API

2 thoughts on “How to make REST API in Rails | Part 2

Leave a Reply

Your email address will not be published. Required fields are marked *