以低成本让您的Grape+Rails应用符合JSON API规范 - Hark

作者:API传播员 · 2025-11-16 · 阅读时间:4分钟
本文介绍如何以低成本使用Grape和Rails构建符合JSON API规范的API,通过代码示例展示设置默认响应格式、定义端点和配置路由的方法,帮助开发者提升开发效率并减少规范不一致问题。

以低成本让您的 Grape + Rails 应用符合 JSON API 规范

在 Ruby 和 Rails 社区中,许多框架和库都遵循“包含电池”的理念,即通过采用公认的惯例,减少开发者在常见或不相关细节上的投入。这种方式不仅提高了开发效率,还为扩展平台提供了便利。在 JSON API 的背景下,这种惯例的采用可以显著减少开发者在端点响应设计上的时间投入,从而专注于功能开发。


JSON API 规范的优势

开发者经常会面临 API 变更带来的问题,比如依赖的库不再支持某些方法,或者默认语义发生变化导致旧行为被隐藏。JSON API 的稳定性和可维护性。

此外,JSON API 规范详细规定了从响应格式到端点行为的方方面面,包括集合与数组的选择、缺失记录的 HTTP 响应代码等。这些规定帮助开发者避免重复造轮子,将更多精力集中在功能实现上。


实现 JSON API 的代码示例

以下是一个基于 Grape 和 JSON API 的简单实现示例:

# Gemfile
gem 'pg'
gem 'sequel-rails'
gem 'sequel_secure_password'
gem 'grape'
gem 'grape-jsonapi-resources'
gem 'jsonapi-resources'

# app/models/user.rb
class User < Sequel::Model
  plugin :secure_password  def validate
    super
    validates_presence [:email, :password_digest, :first_name, :last_name]
  end
end# app/controllers/api/base.rb
module API
  class Base < Grape::API
    mount API::V1::Base
  end
end# app/controllers/api/v1/base.rb
module API
  module V1
    class Base < Grape::API
      mount API::V1::Users
    end
  end
end

以上代码通过嵌套命名空间实现了 API 的版本化,结构清晰且易于扩展。


设置默认响应格式

在 Grape 中,可以通过扩展 ActiveSupport::Concern 来设置默认的响应格式:

# app/controllers/concerns/api/v1/defaults.rb
module API
  module V1
    module Defaults
      extend ActiveSupport::Concern

      included do
        version 'v1', using: :path
        format :json
        formatter :json, Grape::Formatter::JSONAPIResources
        content_type :json, 'application/vnd.api+json'        rescue_from Sequel::NoMatchingRow do |exception|          params = env['api.endpoint'].params
          record_not_found = JSONAPI::Exceptions::RecordNotFound.new(params[:id])
          not_found = JSONAPI::ErrorsOperationResult.new(record_not_found.errors[0].code, record_not_found.errors)
          error! not_found, 404
        end
      end
    end
  end
end

上述代码中,included 方法设置了 API 的版本、响应格式以及内容类型。此外,针对 Sequel 在处理不存在记录时返回 nil 的行为,我们通过捕获 Sequel::NoMatchingRow 异常并返回 404 错误来符合 JSON API 的规范。


定义端点

以下是用户相关的端点定义,包括 GET 和 POST 请求:

# app/controllers/api/v1/users.rb
module API
  module V1
    class Users < Grape::API
      include API::V1::Defaults

      resource :users do
        desc '返回所有用户'
        get do
          users = User.all
          render users
        end        desc '返回指定用户'
        params do
          requires :id, type: Integer, desc: '用户 ID'
        end
        route_param :id do
          get do
            user = User.with_pk!(params[:id])
            render user
          end
        end        desc '创建用户'
        params do
          requires :email, type: String, desc: '新用户邮箱'
          requires :first_name, type: String, desc: '新用户名'
          requires :last_name, type: String, desc: '新用户姓'
          requires :password, type: String, desc: '新用户密码'
          optional :password_confirmation, type: String, desc: '密码确认'
        end
        post do
          user = User.new(
            email: params[:email],
            first_name: params[:first_name],
            last_name: params[:last_name],
            password: params[:password],
            password_confirmation: params[:password_confirmation]
          )
          user.save
        end
      end
    end
  end
end

通过上述代码,我们定义了用户的基本操作,包括获取所有用户、获取指定用户以及创建新用户。


配置路由

最后,在 routes.rb 文件中挂载 API:

# config/routes.rb
mount API::Base => '/api'

完成配置后,您可以通过 /api/v1/users/:id 访问用户端点,并获得符合 JSON API 规范的响应。


总结

通过 Grape 和 JSON API 的结合,您可以以较低的成本构建符合规范的 API。JSON API 的标准化设计不仅提升了开发效率,还减少了因规范不一致带来的问题。通过本文的示例代码,您可以快速上手并实现自己的 API 项目。

原文链接: https://www.hark.bz/blog/post/make-graperails-app-json-api-compliant-cheap-2/