rails grape 实现移动端接口编写

一、安装

#gemfile 添加
gem 'grape', '~> 1.0.2'

二、在config/application.rb 下添加

#表示对应的API文件存放的路径
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

三、routes中添加

  mount UserAPI => '/'

四、在app目录下,新建一个api文件,并创建user_api.rb文件

#app/api/user_api.rb
class UserAPI < Grape::API
  # 返回的数据为json
  format :json

  # 可以使得API的路径更有意义
  # prefix :LYM

  # http://localhost:3000/get_user?real_name=采购人
  get 'get_user' do
    user = User.where(real_name: params[:real_name])
    {message: user}
  end
  post 'post_user' do
    user = User.where(real_name: params[:real_name])
    {message: user}
  end

  # http://localhost:3000/user/select_supplier?real_name=采购人
  resource :user do
    desc "返回一些数据"
    get :select_supplier do
      User.where(real_name: params[:real_name])
    end
  end

end

使用prefix :LYM 会添加一个命名模块,便于接口的模块化
之前的 http://localhost:3000/user/select_supplier?real_name=采购人
添加了prefix :LYM 之后就变成
http://localhost:3000/LYM/user/select_supplier?real_name=采购人

五、官方提供的增删改模板

module Twitter
  class API < Grape::API
    version 'v1', using: :header, vendor: 'twitter'
    format :json
    prefix :api

    helpers do
      def current_user
        @current_user ||= User.authorize!(env)
      end

      def authenticate!
        error!('401 Unauthorized', 401) unless current_user
      end
    end

    resource :statuses do
      desc 'Return a public timeline.'
      get :public_timeline do
        Status.limit(20)
      end

      desc 'Return a personal timeline.'
      get :home_timeline do
        authenticate!
        current_user.statuses.limit(20)
      end

      desc 'Return a status.'
      params do
        requires :id, type: Integer, desc: 'Status id.'
      end
      route_param :id do
        get do
          Status.find(params[:id])
        end
      end

      desc 'Create a status.'
      params do
        requires :status, type: String, desc: 'Your status.'
      end
      post do
        authenticate!
        Status.create!({
          user: current_user,
          text: params[:status]
        })
      end

      desc 'Update a status.'
      params do
        requires :id, type: String, desc: 'Status ID.'
        requires :status, type: String, desc: 'Your status.'
      end
      put ':id' do
        authenticate!
        current_user.statuses.find(params[:id]).update({
          user: current_user,
          text: params[:status]
        })
      end

      desc 'Delete a status.'
      params do
        requires :id, type: String, desc: 'Status ID.'
      end
      delete ':id' do
        authenticate!
        current_user.statuses.find(params[:id]).destroy
      end
    end
  end
end

routest.rb 添加

 mount Twitter::API => '/'

如果没有web数据库的支持,可以自己建模,搭配下列gem进行编写

gem 'grape-jbuilder', '~> 0.2.0'
gem 'jbuilder', '~> 2.0'

你可能感兴趣的:(rails grape 实现移动端接口编写)