Ruby on Rails Grape Gem

루비 온 레일스 Grape Gem 사용하기

Grape 젬은 레일스 환경에서 REST 와 유사한 API 프레임워크이다.

Grape GitHub
Grape Gem GitHub HomePage

Install Gem

1
2
# Gemfile
gem 'grape'

Gemfile 에 grape 젬을 추가해준뒤 bundle install 명령어를 실행한다.

설정하기

적용하기 위한 프로젝트의 레일스 버전이 7버전으로 grape github README 를 따라 6버전 이상의 세팅 방법을 따라 진행 하였다.

path: ./config/initializers/inflections.rb
아래의 코드가 이미 작성되어있고 주석처리가 되어있다. 해당부분 주석을 제거하고 작성해주면 된다.

1
2
3
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym "DefaultController" # 베이스가 되는 클래스의 이름을 입력하는 부분이다.
end

컨트롤러 생성

1
2
3
4
cd app
mkdir api
touch base_api.rb
touch default_controller.rb

path: ./app/api/base_api.rb

1
2
3
4
5
6
7
8
class BaseApi < Grape::API
# 기타 공용 함수들?
helpers do
def server_port
Rails.env['PORT'] || 3000
end
end
end

path: ./app/api/default_controller.rb

1
2
3
4
5
6
7
8
9
class DefaultController < BaseApi
version 'v1', using: :path
format :json
prefix :api

get 'alive' do
"rails server run #{server_port} port"
end
end

path: ./config/routes.rb

1
2
3
4
Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
mount DefaultController => '/'
end

curl을 이용하여 요청하기


User Controller 생성하기

1
2
3
# work dir: ./app
cd user_controller
touch user_api.rb

path: ./app/api/user_controller/user_api.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
module UserController
class UserApi < BaseApi

resource 'users' do
helpers do
def post_params
params.as_json(only: %i[email password name nick_name age gender])
end
end
# GET /api/v1/users/all
get 'all' do
users = User.all
{
total: users.count,
result: users.map { |r| Entities::UserEntity.represent(r) },
}
end

# POST /api/v1/users
post do
user = User.create(post_params)
present user, with: Entities::UserEntity
end
end
end
end

POST /users


GET /users/all


Author

han Ju Ryeon

Posted on

2022-03-06

Updated on

2022-03-06

Licensed under

댓글