1.简介
随着 Mobile App 的增多,很多时候我们在做用 Rails 做 API Base 项目时,rails 自带的 C 和 V 层显得过于繁杂,grape 可以帮助我们快速的构建和 Rails 完美融合的 API 接口。
2.安装
#gemfile 添加:
gem 'grape', '~> 1.0.2' #当前稳定版本
app文件下创建api文件夹,相关接口都在这
#在config/application.rb 下添加
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]
3.编写相关接口(简单写了两种写法)
#app/api/test_api.rb
class TestAPI < Grape::API #需大写
format :json
get 'get_test' do
{message: "Hello #{params[:name]} via get"}
end
post 'post_test' do
{message: "Hello #{params[:name]} via post"}
end
resource :user do
desc "Return a user."
get :test do
@user = User.first
end
end
end
routes.rb:
mount TestAPI => '/'
分别执行:
#根据你运行端口号
$ curl localhost:3000/get_test?name=test
#=> {"message":"Hello test via get"}
$ curl -d 'name=test' localhost:3056/post_test
#=>{"message":"Hello test via post"}
$ curl localhost:3000/user/test
#=> user的属性值{id:...}
也可以定义一个文件夹(例如app/api/twitter/api.rb):
module Twitter
class API < Grape::API
version 'v1', using: :header, vendor: 'twitter'
# version 'v1', using: :path
format :json
# prefix :api
resource :grade_schools do
desc 'Return grade_schools 20 records'
get :index do
GradeSchool.limit(20)
end
desc 'Return a grade_school.'
params do
requires :id, type: Integer, desc: 'GradeSchool id.'
end
route_param :id do
get do
GradeSchool.find(params[:id])
end
end
desc 'Create a grade_school.'
params do
requires :grade_school, type: String, desc: 'grade_school paramters.'
end
post do
GradeSchool.create!({ name: params[:name],
grade: params[:grade] })
end
desc 'Update a grade_school.'
params do
requires :id, type: String, desc: 'grade_school ID.'
requires :grade, type: String, desc: 'Your grade_school.grade'
end
put ':id' do
GradeSchool.find(params[:id]).update({grade: params[:grade]})
end
desc 'Delete a grade_school.'
params do
requires :id, type: String, desc: 'grade_school ID.'
end
delete ':id' do
GradeSchool.find(params[:id]).destroy
end
end
end
end
routes.rb
mount Twitter::API => '/'
一套增删改查访问操作