Create a RESTful API service using Grape

Overview

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

environment

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

console


$ rails new sample_app

This time, the app name was "sample_app".

First install the gem

Add the following

Gemfile



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

console


$ 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.

db/seeds.rb


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.

~/sample_api/
  ├ 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.

config/application.rb


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', '*')]
  end
end

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.

config/routes.rb


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.
end

[Child] app / api / api.rb

Create an API parent class.

app/api/api.rb


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
end

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

Create a parent class for API v1.

app/api/resources/v1/root.rb


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
    end
  end
end

​ 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

app/api/entities/v1/root_entity.rb


module Entities
  module V1
    class RootEntity < Grape::Entity

    end
  end
end

Create Entity file for userAPI

Only display name, email and age.

(Created_at and updated_at are not displayed)

app/api/entities/v1/user_entity.rb


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

Create a class for userAPI.

app/api/resources/v1/user.rb


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 ~ ~
        end

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

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

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

        desc "Delete user"
        route_param :id do
           delete do
             user = User.find(params[:id])
             user.destroy
           end
        end
      end
    end
  end
end
$ 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

URL:http://localhost:3000/api/v1/users

Body: raw JSON(application/json)

Body


{
  “name”:“Sample”
  “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)

Body


{
  “name”:"sample"
  “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

URL:http://localhost:3000/api/v1/users/:id

(: 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

URL:http://localhost:3000/api/v1/users

スクリーンショット 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

URL:http://localhost:3000/api/v1/users/:id

スクリーンショット 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)