什么是 Grape?

Grape 是一個專為構建 RESTful API 而設計的 Ruby 框架。它以輕量級著稱,并且能夠很好地與 Rails 集成。通過提供一個簡單的 DSL(領域特定語言),Grape 讓開發者可以輕松定義 API,同時專注于處理參數驗證、格式化和版本控制等常見任務。


在 Rails 應用中設置 Grape

在開始之前,確保您已經安裝了 Rails。如果尚未安裝,可以通過以下命令創建一個新的 Rails 應用程序:

rails new grape_api_example
cd grape_api_example

然后運行以下命令安裝所需的 gem

bundle install

創建 API

在 Rails 應用的 app 目錄下,為 API 創建一個新目錄:

mkdir app/api

接下來,創建一個 API 的基類文件 app/api/base_api.rb,該類將繼承自 Grape::API,并作為所有 API 端點的基礎。


為 API 添加版本控制

為了確保 API 的向后兼容性,建議為 API 添加版本控制。在本示例中,我們將創建 API 的第一個版本(v1)。首先,創建一個目錄 app/api/v1,并在其中添加一個基礎文件 app/api/v1/base.rb


定義 API 端點

接下來,我們將創建一個簡單的用戶管理端點。新建文件 app/api/v1/users.rb,并添加以下代碼:

module API
 module V1
 class Users < Grape::API
 resource :users do
 desc '返回用戶列表'
 get do
 User.all
 end

 desc '返回指定用戶'
 params do
 requires :id, type: Integer, desc: '用戶 ID'
 end
 route_param :id do
 get do
 User.find(params[:id])
 end
 end

 desc '創建用戶'
 params do
 requires :name, type: String, desc: '用戶名'
 requires :email, type: String, desc: '用戶郵箱'
 end
 post do
 User.create!({
 name: params[:name],
 email: params[:email]
 })
 end

 desc '更新用戶'
 params do
 requires :id, type: Integer, desc: '用戶 ID'
 requires :name, type: String, desc: '用戶名'
 requires :email, type: String, desc: '用戶郵箱'
 end
 put ':id' do
 user = User.find(params[:id])
 user.update({
 name: params[:name],
 email: params[:email]
 })
 end

 desc '刪除用戶'
 params do
 requires :id, type: Integer, desc: '用戶 ID'
 end
 delete ':id' do
 User.find(params[:id]).destroy
 end
 end
 end
 end
end

掛載 API

要使 API 生效,需要在 config/routes.rb 文件中掛載 API。例如:

mount API::V1::Users => '/v1'

創建用戶模型

為了支持用戶管理端點,我們需要生成一個用戶模型。運行以下命令:

rails generate model User name:string email:string
rails db:migrate

測試 API

啟動 Rails 服務器:

rails server

您可以使用 curlPostman 等工具測試 API 端點。以下是一些示例請求:


結論

通過結合 Ruby on Rails 和 Grape,您可以輕松構建功能強大且靈活的 RESTful API。Grape 提供了一個輕量級的框架,使得定義和管理 API 端點變得簡單,而 Rails 則為底層基礎設施提供了強大的支持。本示例展示了一個用于用戶管理的基本 CRUD API,幫助您快速上手 Grape 的使用。基于此基礎,您可以進一步擴展 API 功能,并將其與其他服務集成。


原文鏈接: https://www.railscarma.com/blog/building-a-restful-api-using-grape-in-ruby-on-rails/

上一篇:

使用Node.js創建REST API

下一篇:

使用 Axum 框架在 Rust 中入門 REST API Web 服務開發...
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費