如何为现有 rails 应用构建版本 API?
how to build an version API for an existing rails app?
如何为现有 rails 应用构建版本 API?
我已经构建了一个简单的应用程序,具有用户和公司的关系
Company has_many users
User belongs_to company
我如何为这个应用构建一个版本api
API 的目录结构
在这里,ApiController 是 ApplicationController 的子class,并充当所有其他 API 控制器的父 class。
app/controllers/
.
|-- api
| `-- v1
| |-- api_controller.rb
| |-- users_controller.rb
|-- companies_controller.rb
|-- application_controller.rb
控制器的外观如下:
app/controllers/api/v1/api_controller.rb
module Api::V1
class ApiController < ApplicationController
#API stuff here
end
end
app/controllers/api/v1/users_controller.rb
module Api::V1
class UsersController < ApiController
# POST /v1/users
def create
your code goes here
end
end
end
API 路线
routes.rb
namespace :api, defaults: {format: :json} do
namespace :v1 do
resources :users
end
end
API URL 用于用户的索引操作,仅示例
http://localhost:3000/api/v1/users.json
如何为现有 rails 应用构建版本 API? 我已经构建了一个简单的应用程序,具有用户和公司的关系
Company has_many users
User belongs_to company
我如何为这个应用构建一个版本api
API 的目录结构
在这里,ApiController 是 ApplicationController 的子class,并充当所有其他 API 控制器的父 class。
app/controllers/
.
|-- api
| `-- v1
| |-- api_controller.rb
| |-- users_controller.rb
|-- companies_controller.rb
|-- application_controller.rb
控制器的外观如下:
app/controllers/api/v1/api_controller.rb
module Api::V1
class ApiController < ApplicationController
#API stuff here
end
end
app/controllers/api/v1/users_controller.rb
module Api::V1
class UsersController < ApiController
# POST /v1/users
def create
your code goes here
end
end
end
API 路线
routes.rb
namespace :api, defaults: {format: :json} do
namespace :v1 do
resources :users
end
end
API URL 用于用户的索引操作,仅示例
http://localhost:3000/api/v1/users.json