设计api
- 发送验证码
- 资源:
validation_codes
- 动作:
create(post)
- 状态码:200 | 201 | 422(参数错误) | 429(too many request)
- 登录登出
- 资源:
session
- 动作:
create | destroy(delete)
- 状态码:
200 | 422
- 当前用户
- 记账数据
- 资源:
items
- 动作:
create | update | show | index | destroy
update
对应 PATCH
,表示部分更新
show
对应 GET /items/:id
,展示一条记账
index
对应 GET /items?since=2022-01-01%before=2023-01-01
destroy
对应 DELETE
,表示删除,一般为软删除
- 标签
- 资源:tags
- 动作:
ceate | update | show | index | destroy
- 打标签:记录标签和用户的关系,用中间缓存,不互相影响
- 资源: taggings(动词的名词形式)
- 动作:
create | index | destroy
代码创建
-
routes.rb
: namespace
代表前缀路径
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
# /api/v1
resources :validation_codes
end
end
end
- 运行
bin/rails routes
:自动生成一系列restful api,如果只想取其中某个api,则加 only
即可,想排除某个api,用exclude
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
# /api/v1
resources :validation_codes, only: [:create]
resource :session, only: [:create, :destroy]
resource :me, only: [:show]
resources :items
resources :tags
end
end
end
- bin/rails g model ... :示例
bin/rails g model item user_id:integer amount:integer notes:text tags_id:integer happen_at:datetime
- 创建对应
controller
,这里以items为示例,执行命令:bin/rails g controller Api::V1::Items
会自动依据目录创建
- bin/rails db:migrate
- 尝试做一下分页:利用库
kaminari
或者pagy
- 配置
gemfile
:gem "kaminari"
-
bundle install
:类似yarn,install可以省略
- 实现:
class Api::V1::ItemsController < ApplicationController
def index
items = Item.page(params[:page]).per(params[:number])
render json: { resources: items }
end
def create
item = Item.new amount: 1
if item.save
render json: { resource: item }
else
render json: { errors: item.errors }
end
end
end
网友评论