
使用NestJS和Prisma構建REST API:身份驗證
Grape 是一個專為構建 RESTful API 而設計的 Ruby 框架。它以輕量級著稱,并且能夠很好地與 Rails 集成。通過提供一個簡單的 DSL(領域特定語言),Grape 讓開發者可以輕松定義 API,同時專注于處理參數驗證、格式化和版本控制等常見任務。
在開始之前,確保您已經安裝了 Rails。如果尚未安裝,可以通過以下命令創建一個新的 Rails 應用程序:
rails new grape_api_example
cd grape_api_example
然后運行以下命令安裝所需的 gem:
bundle install
在 Rails 應用的 app
目錄下,為 API 創建一個新目錄:
mkdir app/api
接下來,創建一個 API 的基類文件 app/api/base_api.rb
,該類將繼承自 Grape::API
,并作為所有 API 端點的基礎。
為了確保 API 的向后兼容性,建議為 API 添加版本控制。在本示例中,我們將創建 API 的第一個版本(v1)。首先,創建一個目錄 app/api/v1
,并在其中添加一個基礎文件 app/api/v1/base.rb
。
接下來,我們將創建一個簡單的用戶管理端點。新建文件 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 生效,需要在 config/routes.rb
文件中掛載 API。例如:
mount API::V1::Users => '/v1'
為了支持用戶管理端點,我們需要生成一個用戶模型。運行以下命令:
rails generate model User name:string email:string
rails db:migrate
啟動 Rails 服務器:
rails server
您可以使用 curl 或 Postman 等工具測試 API 端點。以下是一些示例請求:
獲取所有用戶:
curl http://localhost:3000/v1/users
獲取特定用戶:
curl http://localhost:3000/v1/users/1
創建新用戶:
curl -X POST http://localhost:3000/v1/users -d "name=John Doe&email=johndoe@example.com"
更新用戶信息:
curl -X PUT http://localhost:3000/v1/users/1 -d "name=Jane Doe&email=janedoe@example.com"
刪除用戶:
curl -X DELETE http://localhost:3000/v1/users/1
通過結合 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/