
银行如何利用对话式 AI 实现客户服务转型
本文将带你从零开始使用 Ruby on Rails 构建 RESTful API,并通过 Postman 测试其 CRUD 功能。
REST API(Representational State Transfer API)是不同软件应用之间进行数据交换和通信的接口。
在现代开发中,前后端分离架构更为常见:
我们将使用 Rails 构建一个 RESTful API,并通过 Postman 测试其功能。
rails new rails-rest-api -d postgresql --api
cd rails-rest-api
--api
参数会生成一个专门用于 API 开发的 Rails 应用。
rails g model actor name:string country:string
rails db:create
rails db:migrate
rails g controller api/v1/actors
在 config/routes.rb
中添加:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :actors
end
end
end
在 db/seeds.rb
添加示例数据:
Actor.create!(name: "Tom Holland", country: "United Kingdom")
Actor.create!(name: "Johnny Depp", country: "United States")
Actor.create!(name: "Margot Robbie", country: "Australia")
运行填充命令并启动服务器:
rails db:seed
rails server
访问 http://localhost:3000/api/v1/actors
,即可看到返回的 JSON 数据。
http://localhost:3000/api/v1/actors
http://localhost:3000/api/v1/actors
{
"name": "Chris Hemsworth",
"country": "Australia"
}
http://localhost:3000/api/v1/actors/:id
(替换 :id
为实际演员 ID){
"name": "Chris Evans",
"country": "United States"
}
http://localhost:3000/api/v1/actors/:id
rack-cors
Gem在 Gemfile
添加:
gem 'rack-cors'
安装依赖:
bundle install
在 config/initializers/cors.rb
添加:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins "http://localhost:3001"
resource "*",
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
这样前端可以安全地访问 Rails API。
通过本教程,你已经学会:
你现在可以扩展 API 功能,例如增加身份认证、分页查询或数据验证。
原文链接:Building a RESTful API with Rails and Testing CRUD using Postman