我在使用Rails 4构建的应用程序中添加了一个API。我已经搜索了一些内容,这就是我想出来的。
在我的routes.rb
中 My normal html view endpoints up here
...........
...........
# API
require 'api_constraints'
namespace :api, defaults: { format: :json }, path: nil, constraints: { subdomain: 'api' } do
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
resources :users, only: :show
end
end
我的api_constraints.rb
class ApiConstraints
def initialize(options)
@version = options[:version]
@default = options[:default]
end
def matches?(req)
@default || req.headers['Accept'].include?("application/vnd.MYAPP.v#{@version}")
end
end
我的bas api控制器(controllers/api_controller.rb)
class Api::V1::ApiController < ApplicationController
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session
end
my api users_controller (controllers/api/v1/users_controller.rb)
class Api::V1::UsersController < Api::V1::ApiController
respond_to :json
def show
respond_with User.find(params[:id])
end
end
我遇到的问题是,当我访问api.MYAPP.com/users/USERID
时,它只是指向正常的users_controller.rb,向我显示html视图,它应该路由到api / v1 / users_controller.rb。
当我运行rake路线时,我得到了
user GET /users/:id(.:format) users#show
和
api_user GET /users/:id(.:format) api/v1/users#show {:format=>:json, :subdomain=>"api"}
如果我更改我的api名称空间以使其具有url中的版本
namespace :api, defaults: { format: :json }, path: nil, constraints: { subdomain: 'api' } do
namespace :v1 do
resources :users, only: :show
end
end
当我访问api.myapp.com/v1/users/USERID
我在这里做错了什么?