我是Rails API实现的新手。是否有任何博客/网站/书籍/教程我可以开始实施rails API实现。
答案 0 :(得分:2)
有一个非常好用且易于使用的宝石来构建rails api,称为rails-api,你可以查看它,它已经很好地记录了。
答案 1 :(得分:1)
除了其他答案之外,您还要记住的一个问题是,API只是一个series of endpoints - 允许您向端点发送请求&收到回复。
您通常会从宝石中找到的东西&其他信息是rails中的API本质上是命名空间控制器 -
-
参考RailsCast on this,您会找到以下代码:
#app/controllers/api/v1/products_controller.rb
module Api
module V1
class ProductsController < ApplicationController
class Product < ::Product
# Note: this does not take into consideration the create/update actions for changing released_on
def as_json(options = {})
super.merge(released_on: released_at.to_date)
end
end
respond_to :json
def index
respond_with Product.all
end
def show
respond_with Product.find(params[:id])
end
def create
respond_with Product.create(params[:product])
end
def update
respond_with Product.update(params[:id], params[:product])
end
def destroy
respond_with Product.destroy(params[:id])
end
end
end
end
由于rails只是一系列modules
&amp; classes
,API基本上可以让您创建一个模块来存储您的API
控制器类。
支持路线包括(根据Railscast):
#config/routes.rb
namespace :api, defaults: {format: 'json'} do
scope module: :v1, constraints: ApiConstraints.new(version: 1) do
resources :products, :other, :controllers
end
end
正如您所看到的,路由实际上只允许您向作用域API控制器发送json
个请求。因此,端点将成为:
#api/v1/products
#api/v1/other
#api/v1/controllers
-
所以底线是一个API更多的是关于确定您希望发送(和接收)的数据,因为它是如何设置系统