[RUBY] Create a RESTful API service using Grape


I created a RESTful API service using grape, so I will summarize it. After creating it, I used Postman to check the behavior.


ruby 2.6.5

Rails 5.2.4

What you did

-Create any User in the Seeds file. gem uses grape. Create in API mode.

-Access from the client using Postman to register, update, and delete data. Get data -The application was created so that general CRUD functions and data acquisition can be acquired using JSON.

First create an application


$ rails new sample_app

This time, the app name was "sample_app".

First install the gem

Add the following


gem ‘grape’ #Easily build RESTful APIs with Rack applications such as rails and sinatra
gem 'grape-entity’ #If only grape is used, all the values will be displayed. grape-By using entity, you can limit and format the display items.
gem ‘grape_on_rails_routes’  #It makes it easy to read and write routes created by the Grape API.

Then bundle instal.

$ bundle install --path vendor/bundle

DB configuration

Generate Usermodel


$ bundle exec rails g model User name:string email:string age:integer
$ rails db:migrate

Prepare the data for the sample.

Create db / seeds.rb with the following contents.


User.create(name: 'Sony', email: '[email protected]', age: '40')
User.create(name: 'Fredo', email: '[email protected]', age: '38')
User.create(name: 'Tom', email: '[email protected]', age: '35')
User.create(name: 'Michael', email: '[email protected]', age: '33')
User.create(name: 'Connie', email: '[email protected]', age: '30')

Have the DB read the file.

$ bundle exec rake db:seed

Directory structure

Make the following directory structure.

  ├ app/api/
  │    └ api.rb
  │    └ resources/
  │          └ v1/
  │            └ root.rb
  │        └ user.rb
  │       └ entities/
  │      └ v1/
  │        └ root_entity.rb
  │        └ user_entity.rb

autoload settings

Make sure the files under app / api are autoloaded.


module SampleApi
  class Application < Rails::Application
    # app/Autoload the rb file under api
   + config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
   + config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

Creating an API

Mount with the [parent-child-grandchild-great-grandchild] relationship as shown in the figure below.

config/routes.rb  # [parent]Routing settings
  └ app/api/api.rb # [Child]API parent class
      └ app/api/resources/v1/root.rb # [Grandchild]API v1 parent class
          └ app/api/resources/v1/users.rb # [Great-grandson]userAPI class

[Parent] config / routes.rb

Set the routing.


Rails.application.routes.draw do
# app/api/api.Mount rb
+ mount API => ‘/' #With this method, you don't need to add a route to each action because the base class points to each action in the class.

[Child] app / api / api.rb

Create an API parent class.


class API < Grape::API
  #1st segment name of url ex) http://localhost/api/
  prefix 'api'
  # app/api/resources/v1/root.Mount rb
  mount Resources::V1::Root

[Grandchild] app / api / resources / v1 / root.rb

Create a parent class for API v1.


module Resources
  module V1
    class Root < Grape::API
      version 'v1'
      format :json
      content_type :json, 'application/json'

      # app/api/resources/v1/users.Mount rb
      mount Resources::V1::Users

​ Next, create an Entity file before creating the userAPI class. If you do not create this, data that you do not want to display, such as creation time and update time, will be displayed when data is acquired.

Create parent class of Entity


module Entities
  module V1
    class RootEntity < Grape::Entity


Create Entity file for userAPI

Only display name, email and age.

(Created_at and updated_at are not displayed)


module Entities
  module V1
    class UserEntity < RootEntity
      # name, email,Display only age
      expose :name, :email, :age

Create a class for userAPI.


module Resources
  module V1
    class Users < Grape::API
      resource :users do
        desc "user list"
        get do
          present User.all, with: Entities::V1::UserEntity  # with:Apply the contents of the entity file by setting ~ ~

        desc "create new user"
        params do
          requires :name, type: String
          requires :email, type: String
          requires :age, type: Integer
        post do
          User.create!({ name: params[:name], email: params[:email], age: params[:age] })

        desc "Update user"
        route_param :id do 
          put do
            User.find(params[:id]).update({ name: params[:name], email: params[:email], age: params[:age] })

        desc "show user"
        params do
          requires :id, type: Integer, desc: "user id"
        get ":id" do
          present User.find(params[:id]), with: Entities::V1::UserEntity #The same applies to this data acquisition.

        desc "Delete user"
        route_param :id do
           delete do
             user = User.find(params[:id])
$ rails grape:routes or rake grape:routes
        GET  |  /api/:version/users(.:format)      |  v1  |  user list      
       POST  |  /api/:version/users(.:format)      |  v1  |  create new user
        PUT  |  /api/:version/users/:id(.:format)  |  v1  |  Update user    
        GET  |  /api/:version/users/:id(.:format)  |  v1  |  user_show      
     DELETE  |  /api/:version/users/:id(.:format)  |  v1  |  Delete user

You can see the list of grape API routes by running the above command.

So far, you have created the API. From here, we will check whether the CRUD function and data acquisition can be performed correctly by using Postman.

You can confirm the acquisition by entering the above URI after starting rails.

Confirmation of request and response using Postman

Postman URL https://www.postman.com/ スクリーンショット 2020-09-18 17.38.25.png

Launch Postman Registration is easy if you follow the instructions.

Start local server

$ rails s

Create data

Set the data to be registered in Body in JSON format and execute

Method: Post


Body: raw JSON(application/json)


  “email”: “[email protected]”
  “age”: 19

Change the Postman settings to the above and press the send button スクリーンショット 2020-09-18 16.20.13.png

You can see that a new user is registered with the 6th id in the column below.

Edit data (update)

Update the registered information. Set the information to be changed in the Body element.

Method: Put

URL:http://localhost:3000/api/v1/users/:id (: id is the id value registered in db, set to 6 here)

Body:raw JSON(application/json)


  “email”: “[email protected]”
  “age”: 20

スクリーンショット 2020-09-18 16.24.30.png

The update is being done.

Delete data (destroy)

Delete the registered information

Method: Delete


(: id is the id value registered in db, set to 6 here)

スクリーンショット 2020-09-18 16.29.27.png

I succeeded in deleting the data created earlier.

Data acquisition (index)

Get all the registered information. Try to get 5 data registered as Seeds data.

Method: Get


スクリーンショット 2020-09-18 16.20.50.png

You can check the data registered below.

Get data by id (show)

Specify the id from the registered information and acquire only specific information (the data information of id: 6 before being deleted is acquired).

Method: Get


スクリーンショット 2020-09-18 16.24.56.png

We were able to confirm the behavior of the CRUD function. I haven't studied enough about Postman's functions, so I will deepen it.

In addition, grape gem still has various functions, so we will learn about them so that we can master them.

Recommended Posts

Create a RESTful API service using Grape
Let's create a RESTful email sending service + client
Create a fortune using Ruby
[Android] Create a calendar using GridView
Create a Jetty project using Eclipse
Create a tomcat project using Eclipse
Create a filtering function using acts-as-taggable-on
Easy way to create a mapping class when using the API
Create a web environment quickly using Docker
[Rails] Let's create a super simple Rails API
Create a prefectural select bar using active_hash
Create a login function using Swift's Optional
Create API using Retrofit2, Okhttp3 and Gson (Java)
[Android] Create a sliding menu without using NavigationView
Create a Privoxy + Tor environment instantly using Docker
[Rails] How to create a graph using lazy_high_charts
[Java] Create something like a product search API
Create a Spring Boot application using IntelliJ IDEA
Create a web api server with spring boot
A story about creating a service that proposes improvements to a website using a machine learning API
Place "Create a to-do list using Rails API mode and React Hooks" on docker
Create a portfolio app using Java and Spring Boot
Create a Java development environment using jenv on Mac
A memorandum when trying to create a GUI using JavaFX
Create a Service with an empty model Liferay 7.0 / DXP
Create a login authentication screen using the session function
[Java] Create a filter
Let's create a file upload system using Azure Computer Vision API and Azure Storage Java SDK
[Rails] Create an echo bot using the LINE Messaging API.
Create a SlackBot with AWS lambda & API Gateway in Java
Create a tomcat project using Eclipse Pleiades All in One
Create a MOB using the Minecraft Java Mythicmobs plugin | Preparation 1
How to create a service builder portlet in Liferay 7 / DXP
I tried to create an API to get data from a spreadsheet in Ruby (with service account)