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
-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
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
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
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
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.
app/api/entities/v1/root_entity.rb
module Entities
module V1
class RootEntity < Grape::Entity
end
end
end
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
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.
Postman URL https://www.postman.com/
Launch Postman Registration is easy if you follow the instructions.
$ rails s
Set the data to be registered in Body in JSON format and execute
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
You can see that a new user is registered with the 6th id in the column below.
Update the registered information. Set the information to be changed in the Body element.
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
}
The update is being done.
Delete the registered information
URL:http://localhost:3000/api/v1/users/:id
(: id is the id value registered in db, set to 6 here)
I succeeded in deleting the data created earlier.
Get all the registered information. Try to get 5 data registered as Seeds data.
URL:http://localhost:3000/api/v1/users
You can check the data registered below.
Specify the id from the registered information and acquire only specific information (the data information of id: 6 before being deleted is acquired).
URL:http://localhost:3000/api/v1/users/:id
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.
Reference: Memo on how to use Postman, a convenient tool for API development and testing https://qiita.com/zaburo/items/16ac4189d0d1c35e26d1
Reference: Check the API using Postman https://qiita.com/me-654393/items/b14824dd9b37de0da163
Reference: RESTFUL API USING GRAPE IN RAILS https://www.nascenia.com/restful-api-using-grape-in-rails/
Reference: grape github https://github.com/ruby-grape/grape
Recommended Posts