Posted on: Written by: K-Sato
⚠️ This article was posted over 3 years ago. The information might be outdated. ⚠️

Table of Contents

Create the application

You can make an API-only RoR application by just adding --api at the end of rails new command.

$ rails new blog --api

Create the controller and model for Post

You can generate the Post Controller and Post Model by running commands below.

$ rails g model post title:string
$ rails g controller posts
$ rake db:migrate

Set up Routes with namespaces

Namespaces enable you to easily control the versions of your API.

Rails.application.routes.draw do
  namespace 'api' do
    namespace 'v1' do
      resources :posts
    end
  end
end

The code above creates routes like the following. (You can check the routes of your application with rake routes command.)

$ rake routes
api_v1_posts GET    /api/v1/posts(.:format)     api/v1/posts#index
             POST   /api/v1/posts(.:format)     api/v1/posts#create
 api_v1_post GET    /api/v1/posts/:id(.:format) api/v1/posts#show
             PATCH  /api/v1/posts/:id(.:format) api/v1/posts#update
             PUT    /api/v1/posts/:id(.:format) api/v1/posts#update
             DELETE /api/v1/posts/:id(.:format) api/v1/posts#destroy

Set up the Post controller.

Create the api and v1 directories under your controllers directory. Your controllers directory should look like this.

controllers/
          ├ api/
          │    └ v1/
          │      └ posts_controller.rb
          │

Define methods for getting, creating, updating and deleting posts like the code below.

module Api
  module V1
    class PostsController < ApplicationController
      def index
        posts = Post.order(created_at: :desc)
        render json: { status: 'SUCCESS', message: 'loaded posts', data: posts }
      end

      def show
        post = Post.find(params[:id])
        render json: { status: 'SUCCESS', message: 'loaded the post', data: post }
      end

      def create
        post = Post.new(post_params)
        if post.save
          render json: { status: 'SUCCESS', message: 'loaded the post', data: post }
        else
          render json: { status: 'ERROR', message: 'post not saved', data: post.errors }
        end
      end

      def destroy
        post = Post.find(params[:id])
        post.destroy
        render json: { status: 'SUCCESS', message: 'deleted the post', data: post }
      end

      def update
        post = Post.find(params[:id])
        if post.update(post_params)
          render json: { status: 'SUCCESS', message: 'updated the post', data: post }
        else
          render json: { status: 'SUCCESS', message: 'loaded the post', data: post }
        end
      end

      private

      def post_params
        params.require(:post).permit(:title)
      end
    end
  end
end

Test the api using postman

Let’s create some data we can play with on rails console.

$ rails c
2.4.4 :001 > Post.create(title:'title1')
2.4.4 :001 > Post.create(title:'title2')

Next, Run the api!

$ rails s

Open postman and test the following requests.

Get(http://localhost:3000/api/v1/posts)

You can retrieve all the posts you have created on the console.

image.png

GET(http://localhost:3000/api/v1/posts/:id)

You can retrieve one specific post that has id = 1.

image.png

POST (http://localhost:3000/api/v1/posts)

You can create a new post with a POST request.
So change the selected option in the box on the right from GET to POST and pass json data in the body.

image.png

PUT(http://localhost:3000/api/v1/posts/:id)

Change the selected option to PUT and pass json data.

image.png

DELETE(http://localhost:3000/api/v1/posts/:id)

Change the selected option to DELETE and pass json data.

image.png

I’ve usded postman in this post, but you can of course use curl command to do the same.

About the author

I am a web-developer based somewhere on earth. I primarily code in TypeScript, Go and Ruby at work. React, RoR and Gin are my go-to Frameworks.