DEV Community

K-Sato
K-Sato

Posted on • Updated on

Build a simple API using RoR5

Overview

Here is a simple guideline to create a simple API with RoR5. In this post, I'll create a simple blog like application that users can read, create, update and delete posts on.
The complete code is available here

Table of contents

  1. Create the application
  2. Create the controller and model for Post
  3. Set up Routes with namespaces
  4. Set up the Post controller
  5. Test the api using postman

Overview

Here is a simple guideline to create a simple API with RoR5. In this post, I'll create a simple blog like application that users can read, create, update and delete posts on.

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Set up Routes with namespaces

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

Rails.application.routes.draw do
  namespace 'api' do
    namespace 'v1' do
      resources :posts
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

The code above creates routes like this. (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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Create 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
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

Next, Run the api!

$ rails s
Enter fullscreen mode Exit fullscreen mode

Open postman and test the following requests.

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

You can retrieve 2 sets of data you have created on the console.

image.png

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

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

image.png

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

Let's create data!
When you create data, you have to send 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)

Let's Update data!
Change the selected option to PUT and pass json data.

image.png

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

Lastly, let's try to delete data.
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.

Top comments (1)

Collapse
 
meave9786 profile image
meave9786

Such this is very nice article word unscramble it is latest and great puzzle game online.