RESTful 原则
给客户端一个资源,他就知道对应的动作资源对应动作
如何设计
- 以资源为中心
- 充分利用 HTTP 现有功能,如动词、状态码、头部字段
- 应该使用 HTTP 方法(如 GET、POST、PUT 和 DELETE)来描述操作。
设计API
举个例子:记账数据
- 资源:items
- 动作:create | update | show | index | destroy
- create 对应 POST /items/,用来创建一条记账
- update 对应 PATCH,表示部分更新
- show 对应 GET /items/:id,用来展示一条记账
- index 对应 GET /items?since=2022-01-01&before=2023-01-01
- destroy 对应 DELETE,表示删除,一般为软删除
- 在
config/routes.rb中设置items的资源
Rails.application.routes.draw do
resources :items
end
- 查看映射的路由
bin/rails routes
resources方法提供了URL和对应方法,
HTTP 方法一一对应app/controllers/items_controller.rb的方法,
无需思考路径
items GET /items(.:format)
POST /items(.:format)
item GET /items/:id(.:format)
PATCH /items/:id(.:format)
PUT /items/:id(.:format)
DELETE /items/:id(.:format)
- 自定义设置路由
只支持POST方法即支持Controller的create方法
resources :items, only: [:create]
添加/api/v1前缀
创建Controller
bin/rails g controller Api::V1::Items
config/routes.rb
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :items, only: [:create]
end
end
end
参考: