- Ruby 2.6.2
- Rails 5.2.8
- grape
- grape-entity
- AASM
parkjiwoon / practice-rails Goto Github PK
View Code? Open in Web Editor NEWRails 프로젝트 연습용
Rails 프로젝트 연습용
Grape 는 Ruby 에서 사용할 수 있는 REST-like API 프레임워크 입니다.
Rails 에서 간단한 DSL 만 추가하면 쉽게 사용할 수 있습니다.
ruby-grape/grape github 참고해서 적용했습니다.
Ruby 버전이 2.4 이상이어야 합니다.
아래 명령어로 gem 을 추가하면 바로 사용 가능합니다.
bundle add grape
Grape API 를 추가하는 건 기존 Rails 와 크게 다르지 않습니다.
기존 Rails 에서는 Controller 를 추가하고 config/routes.rb
에서 라우팅 해줬습니다.
마찬가지로 Grape 역시 API 를 추가하고 config/routes.rb
에서 연결해주면 되는데 여기서는 mount
라는 걸 사용합니다.
module V1
class Hello < Grape::API
version 'v1', using: :path # /v1/... prefix
format :json # json response
desc 'Return success message'
get '/hello' do
{ res: "success" }
end
desc 'Return message with ID'
params do
requires :id, type: Integer, desc: 'ID'
end
get '/hello/:id' do
{ res: "hello #{params[:id]}" }
end
end
end
우선 API 파일을 하나 작성합니다.
Grape 는 api
디렉터리 하위에 API 파일 (Controller) 을 작성하는 것이 관례입니다.
api 버전 관리를 위해 V1
이라는 모듈 하위에 작성했고 클래스는 Grape::API
를 상속 받아야 합니다.
위 코드를 보면 알수 있듯이 별다른 설명이 없어도 알아볼 수 있을 정도로 굉장히 친절합니다.
Rails.application.routes.draw do
mount V1::Hello => '/api'
end
mount
키워드를 사용해서 매핑해줍니다.
이제 우리는 http://localhost:3000/api/v1/hello
URL 로 요청하면 { res: "success" }
응답을 받을 수 있습니다.
비슷한 API 끼리 한 파일에 모아둘 수도 있습니다.
예를 들어 /v1
prefix 를 가지며 항상 json 응답을 주는 API 들끼리 한 곳에 모아두려면 이렇게 작성하면 됩니다.
module V1
class Mount < Grape::API
version 'v1', using: :path
format :json
mount V1::Hello
end
end
별도의 클래스를 하나 선언한 후 공통으로 사용할 version
, format
을 담고 mount
키워드를 사용합니다.
Rails.application.routes.draw do
mount V1::Mount => '/api'
end
그리고 config/routes.rb
파일을 수정하면 V1::Mount
내부에서 마운트되어 있는 V1::Hello
내용들도 전부 /api
에 매핑됩니다.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.