You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在现有Ruby on Rails Web应用中添加API以对接Android移动端?

没问题!完全不用折腾新建一个仅API模式的RoR应用——你可以直接在现有Web项目里无缝添加API功能,下面是一步步的实操指南,亲测好用:

在现有Ruby on Rails应用中添加API功能的步骤

1. 配置API专属路由

首先打开config/routes.rb,把API路由放在命名空间+版本号下,这样能避免和现有Web路由冲突,也方便后续API迭代升级:

namespace :api do
  namespace :v1 do
    # 按需添加你需要的资源路由,比如文章、用户等
    resources :posts, only: [:index, :show]
    resources :users, only: [:show]
  end
end

配置后,你的API端点就会是/api/v1/posts、/api/v1/users/1这类格式,清晰又规范。

2. 创建API控制器

在app/controllers目录下新建api/v1子目录,然后创建对应业务的控制器,比如PostsController:

class Api::V1::PostsController < ApplicationController
  # 跳过Web端的CSRF验证——移动端API不用这套机制
  skip_before_action :verify_authenticity_token

  def index
    @posts = Post.all
    # 直接返回JSON格式数据,RoR会自动处理响应头
    render json: @posts
  end

  def show
    @post = Post.find(params[:id])
    render json: @post
  end
end

如果有多个API控制器,建议抽一个BaseController出来统一处理公共逻辑(比如身份验证),让其他API控制器继承它。

3. 身份验证(可选但强烈推荐)

如果你的API需要用户登录才能访问,推荐用**JWT(JSON Web Token)**方案,简单又轻量:

  • 先添加JWT的gem:在Gemfile里加gem 'jwt',然后运行bundle install
  • 创建API基础控制器app/controllers/api/v1/base_controller.rb:
class Api::V1::BaseController < ApplicationController
  skip_before_action :verify_authenticity_token
  before_action :authenticate_user!

  private

  def authenticate_user!
    # 从请求头里获取token(格式一般是"Bearer XXX")
    token = request.headers['Authorization']&.split(' ')&.last
    return render json: { error: '请先登录' }, status: :unauthorized unless token

    begin
      # 用你的密钥解密token,获取用户ID
      decoded = JWT.decode(token, Rails.application.credentials.jwt_secret, true, algorithm: 'HS256')
      @current_user = User.find(decoded[0]['user_id'])
    rescue JWT::DecodeError
      render json: { error: '无效的登录凭证' }, status: :unauthorized
    end
  end
end

之后让你的API控制器继承这个BaseController,比如class Api::V1::PostsController < Api::V1::BaseController,就能统一处理身份验证了。

4. 优化JSON响应(可选)

如果不想返回模型的所有字段(比如密码哈希这类敏感数据),可以自定义JSON输出:

  • 简单场景用as_json:
def show
  @post = Post.find(params[:id])
  render json: @post.as_json(
    only: [:id, :title, :content, :created_at], # 只返回指定字段
    include: { comments: { only: [:id, :body] } } # 关联数据也按需返回
  )
end
  • 复杂场景推荐用Active Model Serializers:先加gemgem 'active_model_serializers',然后创建序列化器app/serializers/api/v1/post_serializer.rb:
class Api::V1::PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :content, :created_at
  has_many :comments, serializer: Api::V1::CommentSerializer
end

之后控制器里直接render json: @post,就会自动用序列化器处理输出,代码更整洁。

5. 测试你的API

可以用Postman、curl或者RoR自带的rails console来测试:
比如用curl测试列表接口:

curl http://localhost:3000/api/v1/posts

带token测试详情接口:

curl -H "Authorization: Bearer 你的JWT_TOKEN" http://localhost:3000/api/v1/posts/1

内容的提问来源于stack exchange,提问作者Han JeongTaek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:05:23