Rails API模式 #
一、创建API应用 #
1.1 创建API模式项目 #
bash
rails new myapi --api
1.2 配置API模式 #
ruby
# config/application.rb
config.api_only = true
二、API控制器 #
2.1 控制器基类 #
ruby
class Api::V1::BaseController < ApplicationController
skip_before_action :verify_authenticity_token
private
def render_success(data = nil)
render json: { success: true, data: data }
end
def render_error(message)
render json: { success: false, error: message }, status: :bad_request
end
end
三、总结 #
3.1 核心要点 #
| 要点 | 说明 |
|---|---|
| –api | 创建API模式 |
| api_only | API配置 |
| JSON响应 | render json |
3.2 下一步 #
现在你已经掌握了API模式,接下来让我们学习 API控制器,深入了解Rails的API控制器设计!
最后更新:2026-03-28