如何在现有 Rails 服务器之上添加 API 层
How to add an API layer on top of an existing Rails server
有一些关于此的问题,但所有问题都包括更改现有路线或从头开始创建 APIs。我想做的是将 API 完全分开在不同的子路径下。像这样:
/users/:id
-> 常规 Rails 服务器
/api/v1.0/users/:id
-> 修改了 API 层,它访问基础 Rails 服务器的模型和控制器
我真的很想将 API 的逻辑与 Rails 基本实现分开
在 routes.rb 配置:
namespace :api do
namespace :v1 do
resources :users
end
end
如果您想使用 API
而不是 Api
,请在 config/initializers/inflectors.rb
添加:
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym 'API'
end
您的 users_controller 必须在 app/api/v1/controllers
中,并且看起来像这样:
module API
module V1
class UsersController < ApplicationController
...
end
end
end
找到更多选项
你检查过了吗? Api on Rails
特别注意第 2 章中 routes.rb 的布局。它展示了如何使用作用域和命名空间来创建到项目中不同子目录的路由。
有一些关于此的问题,但所有问题都包括更改现有路线或从头开始创建 APIs。我想做的是将 API 完全分开在不同的子路径下。像这样:
/users/:id
-> 常规 Rails 服务器
/api/v1.0/users/:id
-> 修改了 API 层,它访问基础 Rails 服务器的模型和控制器
我真的很想将 API 的逻辑与 Rails 基本实现分开
在 routes.rb 配置:
namespace :api do
namespace :v1 do
resources :users
end
end
如果您想使用 API
而不是 Api
,请在 config/initializers/inflectors.rb
添加:
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym 'API'
end
您的 users_controller 必须在 app/api/v1/controllers
中,并且看起来像这样:
module API
module V1
class UsersController < ApplicationController
...
end
end
end
找到更多选项
你检查过了吗? Api on Rails
特别注意第 2 章中 routes.rb 的布局。它展示了如何使用作用域和命名空间来创建到项目中不同子目录的路由。