发布于 2026-01-06 4 阅读
0

使用 Rails 从零开始创建 API 的入门指南

使用 Rails 从零开始创建 API 的入门指南

你掌握了一些极具价值的数据,迫不及待地想要与全世界分享。你决定构建一个 API,但你对使用 Ruby on Rails 构建应用程序还不太熟悉。

你是不是好高骛远了?

不!即使只掌握 Ruby on Rails 的基础知识,你也完全可以构建 API。

本教程将教你如何配置 Rails 以作为 API 使用。

先决条件下载

我们将使用名为 Postman 的免费工具来测试我们的 API。
下载Postman

目标

创建 API,用于提供您最喜欢的快餐店的隐藏菜单菜品。

本教程将帮助您创建一个能够实现以下功能的 API:

  1. 在您的 API 中索引所有隐藏菜单项的实例
  2. 显示隐藏菜单项的实例
  3. 创建隐藏菜单项的实例
  4. 更新隐藏菜单项的实例
  5. 删除隐藏菜单项的实例

创建和测试 API 功能的 8 个步骤

  1. 创建一个新的 Rails API
  2. 启用 CORS(跨域资源共享)
  3. 使用 rails g resource 命令创建模型、控制器、数据库迁移表和路由
  4. 指定隐藏菜单项的属性和数据类型
  5. 定义索引、显示、创建、更新和销毁操作
  6. 创建索引、显示、创建、更新和销毁操作的路由
  7. 种子数据
  8. 启动服务器和 Postman 来测试 API 功能

步骤 1:创建一个新的 Rails API

在您选择的目录中,在终端中输入以下命令。此命令将创建一个名为 secret_menu_api 的新 Rails API。

#in your terminal
rails new secret_menu_api --api
Enter fullscreen mode Exit fullscreen mode

切换到 secret_menu_api 目录,然后在终端中输入以下命令打开 API。

# in your terminal
cd secret_menu_api

code .
Enter fullscreen mode Exit fullscreen mode

步骤 2:启用 CORS(跨域资源共享)

CORS 允许其他人访问您的 API。为了防止未经授权的访问,Rails 会自动禁用 CORS。让我们启用 CORS,以便其他人可以访问我们丰富的数据!

在新建的 Rails API 的文件资源管理器中,展开以下目录以打开 cors.rb 文件。

配置>初始化器>cors.rb

然后,

  1. 取消注释第 8-16 行(注意:行号可能有所不同,但相应的代码粘贴在下面供您参考)。
  2. 在第 10 行,将代码 (origins 'example.com') 更改为 (origins '*'),如下所示。
# in config>initializers>cors.rb
# lines 8-16

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

Enter fullscreen mode Exit fullscreen mode

在文件资源管理器中,向下滚动到最底部并打开 Gemfile 文件。
取消注释第 26 行,gem 'rack-cors'

# in Gemfile
gem 'rack-cors'
Enter fullscreen mode Exit fullscreen mode

在终端中运行 bundle install。

#in terminal
bundle install
Enter fullscreen mode Exit fullscreen mode

步骤 3:通过 rails g resource 命令创建模型、控制器、数据库迁移表和路由。

命令语法:
rails g resource(模型名称的单数形式)

# in terminal
rails g resource Secret_menu_item
Enter fullscreen mode Exit fullscreen mode

你会发现这条命令一次性创建了以下文件!
为了方便你找到这些文件,文件目录已包含在第二行中。

  1. 一个名为 secret_menu_item 的模型
    app>models>secret_menu_item.rb

  2. 一个名为 secret_menu_items_controller.rb 的控制器 app>controllers>secret_menu_items_controller.rb

  3. 名为 routes.rb 的路由
    配置>routes.rb

  4. 数据库迁移表名为 202042720449_create_secret_menu_items.rb
    db>migrate>202042720449_create_secret_menu_items.rb

注意:202042720449 是我创建迁移文件的日期和时间时间戳。您的文件将具有不同的时间戳。

步骤 4:指定隐藏菜单项的属性和数据类型

我们的 API 旨在显示有关隐藏菜单项的实用信息。我们将通过将以下属性设置为隐藏菜单项的属性来显示这些信息:

  • 隐藏菜单项的名称
  • 提供隐藏菜单菜品的餐厅名称
  • 菜单说明

指定属性。
在您的 02042720449_create_secret_menu_items.rb 文件中,复制并粘贴以下内容:

# in db>migrate>202042720449_create_secret_menu_items.rb

class CreateSecretMenuItems < ActiveRecord::Migration[6.0]
  def change
    create_table :secret_menu_items do |t|
      t.string :menu_name
      t.string :restaurant_name
      t.string :menu_description
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

迁移您的表

# in your terminal

rails db:migrate
Enter fullscreen mode Exit fullscreen mode

如果迁移成功完成,您应该在终端中看到以下输出。

# Message in your terminal

== 20200427020449 CreateSecretMenuItems: migrating ============================
-- create_table(:secret_menu_items)
   -> 0.0022s
== 20200427020449 CreateSecretMenuItems: migrated (0.0023s) ===================
Enter fullscreen mode Exit fullscreen mode

在你的数据库目录中,打开 schema.rb 文件。
你会看到该文件现在显示了你的数据结构。

# in db>schema.rb

ActiveRecord::Schema.define(version: 2020_05_03_161829) do

  create_table "secret_menu_items", force: :cascade do |t|
    t.string "menu_name"
    t.string "restaurant_name"
    t.string "menu_description"
  end
end
Enter fullscreen mode Exit fullscreen mode

步骤 5:定义索引、显示、创建、更新和销毁操作

这些操作使我们的 API 能够:

  1. 索引:显示数据库中所有隐藏菜单项的实例
  2. 显示:显示隐藏菜单项的实例
  3. 创建:创建隐藏菜单项的实例
  4. 更新:更新现有隐藏菜单项的实例
  5. 删除:已存在的隐藏菜单项的实例

这些操作在我们的控制器中按以下方式定义。
请将以下内容复制并粘贴到您的 secret_menu_items_controller.rb 文件中。

#in app>controllers>secret_menu_items_controller.rb

class SecretMenuItemsController < ApplicationController
    def index
        @secretMenuItems = SecretMenuItem.all 
        render json: @secretMenuItems
    end 

    def show
        @secretMenuItem = SecretMenuItem.find(params[:id])
        render json: @secretMenuItem
    end 

    def create
        @secretMenuItem = SecretMenuItem.create(
            menu_name: params[:menu_name],
            restaurant_name: params[:restaurant_name],
            menu_description: params[:menu_description]
        )
        render json: @secretMenuItem
    end 

    def update
        @secretMenuItem = SecretMenuItem.find(params[:id])
        @secretMenuItem.update(
            menu_name: params[:menu_name],
            restaurant_name: params[:restaurant_name],
            menu_description: params[:menu_description]
        )
        render json: @secretMenuItem
    end 

    def destroy
        @secretMenuItems = SecretMenuItem.all 
        @secretMenuItem = SecretMenuItem.find(params[:id])
        @secretMenuItem.destroy
        render json: @secretMenuItems
    end 

end
Enter fullscreen mode Exit fullscreen mode

步骤 6:创建索引、显示、创建、更新和销毁操作的路由

路由接收来自客户端的 HTTP 请求,并将请求转发到相应控制器中定义的相应操作。我们需要为控制器中定义的所有操作设置路由。设置路由非常简单!

复制以下内容并粘贴到 routes.rb 文件中。

# in config>routes.rb

Rails.application.routes.draw do
  resources :secret_menu_items, only: [:index, :show, :create, :update, :destroy]
end
Enter fullscreen mode Exit fullscreen mode

步骤 7:种子数据

1.在我们的数据库中创建一些我们隐藏菜单项的实例。

# in db>seed.rb

menu1 = SecretMenuItem.create(menu_name: "Chipotle Nachos", restaurant_name: "Chipotle", menu_description:"Build a plate of nachos with all of your favorite fixings")
menu2 = SecretMenuItem.create(menu_name: "Starbucks butterbeer Frappuccino", restaurant_name: "Starbucks", menu_description:"Combine three pumps of toffee nut syrup and three pumps of caramel with a Crème Frappuccino base")
menu3 = SecretMenuItem.create(menu_name: "Skittles", restaurant_name: "Jamba Juice", menu_description:"A mixture of lemonade, lime sherbet, frozen yogurt, and strawberries")
Enter fullscreen mode Exit fullscreen mode

2. 初始化数据

# in your terminal
rails db:seed
Enter fullscreen mode Exit fullscreen mode

3.检查你的数据是否已正确初始化。

# in your terminal
rails c

# It will pull up a console
2.6.1 :002 >
Enter fullscreen mode Exit fullscreen mode

输入 SecretMenuItem.all 来提取我们刚刚添加的所有隐藏菜单项实例。

# in your terminal

2.6.1 :002 > SecretMenuItem.all
   (0.5ms)  SELECT sqlite_version(*)
  SecretMenuItem Load (0.2ms)  SELECT "secret_menu_items".* FROM "secret_menu_items" LIMIT ?  [["LIMIT", 11]]
 => #<ActiveRecord::Relation [#<SecretMenuItem id: 1, menu_name: "Chipotle Nachos", restaurant_name: "Chipotle", menu_description: "Build a plate of nachos with all of your favorite ...">, #<SecretMenuItem id: 2, menu_name: "Starbucks butterbeer Frappuccino", restaurant_name: "Starbucks", menu_description: "Combine three pumps of toffee nut syrup and three ...">, #<SecretMenuItem id: 3, menu_name: "Skittles", restaurant_name: "Jamba Juice", menu_description: "A mixture of lemonade, lime sherbet, frozen yogurt...">]> 
Enter fullscreen mode Exit fullscreen mode

如果您看到了我们所有隐藏菜单项,说明我们的数据已正确植入!

步骤 8:启动服务器和 Postman 以测试 API 功能

在终端中运行以下命令来启动服务器。

#in your terminal
rails s
Enter fullscreen mode Exit fullscreen mode

下载并打开 Postman。Postman
是一个用于测试我们 API 功能的实用工具。

邮递员布局

打开 Postman 后,你会看到两个按钮(GET 和 Send)之间有一条灰色横条。

GET 是一个 HTTP 方法按钮。点击向下箭头,您将看到其他 HTTP 方法的下拉选项。

我们将使用不同的 HTTP 方法来测试 API 的不同操作(稍后会详细介绍!)。

在HTTP方法按钮的右侧,您会看到一个带有占位符“输入请求URL”的灰色栏。我们将在此处输入API服务器的URL。

在网址栏右侧,您会看到一个蓝色的发送按钮。
设置好所有必要的参数以测试 API 功能后,点击发送按钮即可。

如何测试索引操作和索引路由?
索引功能使我们的 API 能够显示 API 中所有隐藏菜单项的实例。

Index 响应 GET 请求。

在 Postman 中
:1. 将 HTTP 方法设置为 GET;
2. 输入请求 URL:http://localhost:3000/secret_menu_items;
3. 点击发送。

屏幕上会显示一个对象数组。每个对象都是一个隐藏菜单项的实例。这意味着我们的索引操作和路由已正确设置!

[
    {
        "id": 1,
        "menu_name": "Chipotle Nachos",
        "restaurant_name": "Chipotle",
        "menu_description": "Build a plate of nachos with all of your favorite fixings."
    },
    {
        "id": 2,
        "menu_name": "Starbucks butterbeer Frappuccino",
        "restaurant_name": "Starbucks",
        "menu_description": "Combine three pumps of toffee nut syrup and three pumps of caramel with a Crème Frappuccino base."
    },
    {
        "id": 3,
        "menu_name": "Skittles",
        "restaurant_name": "Jamba Juice",
        "menu_description": "A mixture of lemonade, lime sherbet, frozen yogurt, and strawberries."
    },
]

Enter fullscreen mode Exit fullscreen mode

如何测试显示操作和显示路线
显示功能使我们的 API 能够显示隐藏菜单项的实例。

显示响应 GET 请求。

在以下示例中,我们将通过 API 显示 ID 为 1 的隐藏菜单项实例。为此,我们将在 URL 中指定 ID 号:
http://localhost:3000/secret_menu_items/
(要调出的实例的 ID 号)

在 Postman 中
:1. 将 HTTP 方法设置为 GET;
2. 输入请求 URL:http://localhost:3000/secret_menu_items/1;
3. 点击发送。

屏幕上会出现 ID 为 1 的隐藏菜单项“Chipotle Nachos”。这意味着我们的显示操作和路线已正确设置!

{
    "id": 1,
    "menu_name": "Chipotle Nachos",
    "restaurant_name": "Chipotle",
    "menu_description": "Build a plate of nachos with all of your favorite fixings."
}
Enter fullscreen mode Exit fullscreen mode

如何测试 CREATE ACTION 和 CREATE ROUTEN?CREATE ACTION
允许 API 创建我们隐藏菜单项的新实例。
还记得我们在 seed.rb 中是如何创建隐藏菜单项新实例的吗?
我们将使用 Postman 创建一个!

创建对象响应 HTTP 方法 POST。

在 Postman 中
:1. 将 HTTP 方法设置为 POST;
2. 输入请求 URL:http://localhost:3000/secret_menu_items;
3. 打开“Body”选项卡
。在包含 HTTP 方法、URL 栏和发送按钮的行下方,您会看到一行选项卡。点击“Body”选项卡。它会在下方显示另一行选项。在这些选项中……

  1. 点击“表单数据”,将显示一个表格,表格的列分别为“键”和“值”。在“键”列中,我们将输入属性名称;在“值”列中,我们将输入对应属性的值。

在“键”列下,复制并粘贴以下内容:

menu_name

restaurant_name

menu_description

在“数值”列中,复制并粘贴以下内容:麦当劳麦
满分(Hash Brown McMuffin
McDonald's
An Egg McMuffin),并将薯饼放在正中间。

  1. 点击发送

屏幕上将显示我们新创建的麦香薯饼麦满分实例。这意味着我们的创建操作和路由已正确设置!

{
    "id": 4,
    "menu_name": "Hash Brown McMuffin",
    "restaurant_name": "McDonald's",
    "menu_description": "A traditional Egg McMuffin with the hash brown right in the center"
}
Enter fullscreen mode Exit fullscreen mode

如何测试更新操作和路由
更新功能使我们的 API 能够更新现有隐藏菜单项的实例。

更新操作响应 HTTP 方法 PATCH。

假设我们想用完全不同的隐藏菜单时间更新我们的麦香薯饼麦满分。

麦香薯饼麦满分的ID是4。

我们将通过在请求 URL 中提供其 ID 来告诉 Postman 我们想要更新麦香薯饼。http
://localhost:3000/secret_menu_items/4

在 Postman 中
:1. 将 HTTP 方法设置为 PATCH;
2. 输入请求 URL:http://localhost:3000/secret_menu_items/4;
3. 打开“正文”选项卡。

  1. 单击表单数据,在键值表中更新值。

您的关键列应该已经填写了以下内容,这是之前测试创建操作和路由时的结果。

关键信息:

菜单名称、

餐厅名称

、菜单描述

在“数值”列中,复制并粘贴以下内容: Shake Shack
花生酱培根芝士汉堡, 培根汉堡配花生酱

  1. 按下发送键

您的屏幕应该显示所有隐藏菜单项,包括实例 ID 为 4 的花生酱培根芝士汉堡。这意味着我们的更新操作和路由已正确设置!

[
    {
        "id": 1,
        "menu_name": "Chipotle Nachos",
        "restaurant_name": "Chipotle",
        "menu_description": "Build a plate of nachos with all of your favorite fixings."
    },
    {
        "id": 2,
        "menu_name": "Starbucks butterbeer Frappuccino",
        "restaurant_name": "Starbucks",
        "menu_description": "Combine three pumps of toffee nut syrup and three pumps of caramel with a Crème Frappuccino base"
    },
    {
        "id": 3,
        "menu_name": "Skittles",
        "restaurant_name": "Jamba Juice",
        "menu_description": "A mixture of lemonade, lime sherbet, frozen yogurt, and strawberries"
    },
    {
        "id": 4,
        "menu_name": "Peanut butter bacon cheeseburger",
        "restaurant_name": "Shake Shack",
        "menu_description": "A bacon burger with a side of peanut sauce"
    }
]
Enter fullscreen mode Exit fullscreen mode

如何测试销毁操作和路由
销毁操作使我们的 API 能够删除已存在的秘密菜单项实例。

销毁操作响应 DELETE 请求。

假设我们要销毁我们的花生酱培根芝士汉堡实例。

花生酱培根芝士汉堡的ID是4。

我们将通过在请求 URL 中提供花生酱培根芝士汉堡的 ID 来告诉 Postman 我们想要删除它。http
://localhost:3000/secret_menu_items/4

在 Postman 中
:1. 将 HTTP 方法设置为 DELETE;
2. 输入请求 URL:http://localhost:3000/secret_menu_items/4;
3. 点击发送。

我们的屏幕上应该显示除刚刚删除的花生酱培根芝士汉堡之外的所有实例。这意味着我们的销毁操作和路径已正确设置!

[
    {
        "id": 1,
        "menu_name": "Chipotle Nachos",
        "restaurant_name": "Chipotle",
        "menu_description": "Build a plate of nachos with all of your favorite fixings."
    },
    {
        "id": 2,
        "menu_name": "Starbucks butterbeer Frappuccino",
        "restaurant_name": "Starbucks",
        "menu_description": "Combine three pumps of toffee nut syrup and three pumps of caramel with a Crème Frappuccino base"
    },
    {
        "id": 3,
        "menu_name": "Skittles",
        "restaurant_name": "Jamba Juice",
        "menu_description": "A mixture of lemonade, lime sherbet, frozen yogurt, and strawberries"
    }
]
Enter fullscreen mode Exit fullscreen mode

就是这样。只要具备 Ruby on Rails 的基础知识,我们就可以按照以下 8 个步骤将 Rails 配置为 API:

  1. 创建一个新的 Rails API
  2. 启用 CORS(跨域资源共享)
  3. 使用 rails g resource 命令创建模型、控制器、数据库迁移表和路由
  4. 指定隐藏菜单项的属性和数据类型
  5. 定义索引、显示、创建、更新和销毁操作
  6. 创建索引、显示、创建、更新和销毁操作的路由
  7. 种子数据
  8. 启动服务器和 Postman 来测试 API 功能

现在,去创建你的新 Rails API,然后告诉我结果如何!

文章来源:https://dev.to/lisahjung/beginner-s-guide-to-creating-an-api-from-scratch-using-rails-2eie