Mayank Kashyap's Blog

Creating an API using Rails

October 01, 2015 | 4 Minute Read

Hey there! In this post I will explain to you how you can create a simple ruby on rails api without the use of rails api gem. This blog uses references from the railscast tutorial of API Versioning. You can refer a simple user api created using rails at my github respository.

This Blog assumes that the user has already installed ruby, rails and postgresql server in his system. For installation of the same, refer here : Installing Ruby On Rails Environment in Ubuntu.
This blog also assumes that the user has prior knowledge about the relational databases.

Getting Started

Once you have installed Ruby On Rails Environment, you can create a new rails app by typing in the following command:

$ rails new name_of_app
$ cd name_of_app

This will create a new rails app in the current directory with the current database configured as sqlite3.
You can change the settings from the cofig file found in config/database.yml.

	default: &default
  	adapter: postgresql #change adapter name according to database
  	pool: 5
  	timeout: 5000

  	# and change the database: name to the name you want for your database in all the 3 environments i.e. development, test and production.
  	# note: name should be different for all the 3 environments.

Also you need to change the gem for your database configuration in the Gemfile:

#for using sqlite3 as database use :
gem 'sqlite3'
#for using postgresql as database use :
gem 'pg'

Creating and Migrating Database

After this you can create the desired model/table that you want in your database, using the following command:

 
	#for creating a User model with attributes name of type string and mobileno of type integer
$ bin/rails generate model User name:string mobileno:integer

This will create a model named User with the above mentioned attributes. Now run the following two commands to create and migrate database:

$ bin/rake db:create
$ bin/rake db:migrate

This will create and migrate a postgres database with the name as specified in the database.yml file.

Creating HTTP Rest API

Now to create HTTP Rest API, create a folder named 'api' in the app/controllers folder.

Now create another folder inside the 'api' folder named 'v1'. This denotes that the api is using version 1 of the api. To create another versions create different folders inside the 'api' folder.

Now to create CRUD(Create Read Update Delete) operations for the User model, go to the 'routes.rb' file in the 'config' folder and add this code after the first line:

	namespace :api , defaults: {format: 'json'} do
    	namespace :v1 do
    	  	resources :users
    	end
  	end

  	resources :users

Now create a file named 'users_controller.rb' inside the 'v1' folder. And write the following code inside it:

module Api
  module V1
    class UsersController < ApplicationController
      skip_before_filter  :verify_authenticity_token
      respond_to :json
      
      def index
        respond_with User.all
      end
      
      def show
        respond_with User.find(params[:id])
      end
      
      def create
        respond_with User.create(name: params[:name], mobileno: params[:mobileno])
      end
      
      def update
        respond_with User.update(params[:id], name: params[:name], mobileno: params[:mobileno])
      end
      
      def destroy
        respond_with User.destroy(params[:id])
      end
    end
  end
end

Also add the following gem to the Gemfile:

	gem 'responders', '~> 2.0'

Run the following code in terminal:

	$ bundle install

Hosting api on localhost and accessing it using Postman Plugin

Now to host the api on localhost, go to terminal and type the following code:

	$ rails s

This will host the api on the localhost and you can visit localhost:3000 on you browser and you will see a getting started page.
Now if you will visit the localhost:3000/api/v1/users you will see an empty array. This is because your database is empty. Now to access all requests to the api, I recommend using Postman Plugin for chrome. Install it and send post request to the following url 'http://localhost:3000/api/v1/users' with params 'name' and 'mobileno' and fill the database with some records and then you can call get request on the same url for getting the records in json format.

Now to send put request, you need to send the put reuest at http://localhost:3000/api/v1/users/:id_of_user along with the updated params.

To send DELETE request just send the delete request to the same url as put and the user will be deleted.

Further content coming soon...