
使用這些基本 REST API 最佳實踐構建出色的 API
allow do
origins "*"
resource "*",
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
接下來,我們將為 創建GET
端點api/getcreditscore
。我們的第一步是創建端點的路由。為此,請打開config
目錄中的 routes.rb 文件。
Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
# root "articles#index"
get 'api/getcreditscore', to: 'application#creditscore'
end
現在路由已定義,我們將為端點創建控制器函數。該函數將返回一個 JSON 有效負載,其中包含 500 到 900 之間的隨機數,代表信用評分。要添加此邏輯,請導航到目錄中的application_controller.rbcontrollers
。完成的控制器文件將如下例所示。
class ApplicationController < ActionController::API
def creditscore
render json: { creditscore: rand(500..900) }
end
end
這樣,我們的 API 就可以部署了。
在本例中,我們將在本地運行 Rails 應用程序。要本地運行 API,我們需要啟動 Rails 服務器。我們可以在rails server
應用程序的根目錄中使用命令來執行此操作。
rails server
現在,我們的 Rails 應用程序和 API 已啟動并運行。您可以通過 Postman 發送測試 HTTP 請求。通過向 發送請求localhost:3000/api/getcreditscore
,您應該會看到從application_controller.rb文件中編寫的處理程序200 OK
返回的狀態代碼和信用評分。對于此測試,傳入請求不需要請求正文。creditscore
默認情況下,rails 將在端口 3000 上運行。要更改這種情況,您可以打開目錄中的puma.rb
config
文件并更改以下代碼行以修補您希望服務器監聽的端口。
port ENV.fetch("PORT") { 3000 }
這樣,我們就使用 Rails 創建了一個簡單的 RESTful API。然后可以根據需要擴展此代碼,以構建應用程序的 API。接下來,您可能希望使用 API 密鑰保護 API,將 API 與 API 網關集成,查看 API 的使用情況,或通過API 貨幣化創造收入。要獲得滿足 API 分析和貨幣化需求的解決方案,請立即查看 Moesif以探索所有這些內容以及更多內容!
原文地址:https://www.moesif.com/blog/technical/api-development/Building-A-RESTful-API-With-Rails/