安装:rest-client4400✨
gem install rest-client
一个简单的HTTP和REST client for Ruby.
基本用法:
require 'rest-client'
RestClient.get(url, headers={})
RestClient.post(url, payload, headers={})
JSON格式的转化,to_json和parse
> require 'json'
使用聚合数据网
- 注册聚合数据网,选择一类数据并自动得到它的appAPI:
- 登陆这个api的网站https://www.juhe.cn/docs/api/id/39 ,下载示例代码。
- 使用请求示例:http://v.juhe.cn/weather/citys?key=您申请的KEY
- irb
require 'rest-client' require 'json' response = RestClient.get "http://v.juhe.cn/weather/citys?key=您申请的KEY
"
data = JSON.parse(response.body) #得到hash格式的数据集合
data.keys #得到keys
data["result"][0] #得到具体数据。
bundle exec
在当前的bundle中,执行一个script
Rake(software) 维基百科
rake是一个软件task管理和bulid automation tool.It allows the user to specify tasks and describe dependencies as well as to group tasks in a namespace.
⚠️ruby新版已经放弃使用rake了,这里就不学习了。
在“ 离线保存的全栈文件/我的练习/webapi练习/api_exercise”目录建立本教程app.
在rails上获得聚合网的天气API,
重点1:建立lib/tasks/dev.rake文件,建立一个script
重点2: 保护API key
- 新增config/juhe.yml , 设置development环境和production环境的api_key:"XXX"
- 然后在application.rb中的Applicaiton类中设置一个常量JUHE_CONFIG,用于存储不同程序环境下的api_key。
- JUHE_CONFIG = Rails.application.config_for(:juhe)
- 把程序中的api_key换成 JUHE_CONFIG["api_key"]
- 把juhe.yml标记在.gitignorre中: /config/juhe.yml, 不进行版本控制,保护密匙。
- 惯例新增一个juhe.yml.example,让同事看到这个样例。
根据火车train 的API,建立查询和订票系统:
要实作一个订票系统 API 服务器,可以提供给手机 iOS, Android 应用程式,或是一个开放平台给别的开发者串接使用。
重点1:
routes.rb的设置:
as用来产生路由地址的方法
api_v1_trains_url
会请求http://localhost:4000/api/v1/trains 这个网页。
api_vi_train_url(train.number)
会请求转到http://localhost:4000/api/v1/trains/0822 ,假设train.number是“0822”
重点2:
render :json => {变量}
会把变量转成 JSON 字串输出。这里不需要准备 View .erb 档案。因为这两个 API 都是用 HTTP GET 读取,我们可以直接打开浏览器,浏览
http://localhost:3000/api/v1/trains
就是用 GET 读取资料
例子:
在reservations_controller.rb#create方法中:
if @reservation.save
render :json => {...}
else
render :json => {:message => "订票失败", :errors => @reservation.errors }, status =>400
重点3:
--no--assets选项的意思,不生成相关javascritps和styleshees的对应文件。
rails g controller api::v1::reservations --no-assets
不生产:
❌1
报告错误, InvalidAuthenticity 指未通过真实性验证。
ActionController::InvalidAuthenticityToken in Api::V1::ReservationsController#create
在create方法中,需要验证validations。猜测可能是验证的问题。
打开rails console,输入Reservation.count , 提示错误❌:
ArgumentError (Unknown validator: 'ScopeValidator')
发现验证格式写错误了:
❌validates :seat_number, :scope => :train_id , uniqueness: true ❌
✅validates :seat_number, uniqueness: {:scope => :train_id}
或 validates_uniqueness_of :seat_number, :scope => :train_id
但仍然未解决第一个❌:不过不影响在控制台,模拟create方法,✅生产reservation记录。
另外,destroy,update都会报告类似❌。
✅于是复制问题到谷歌和stackoverflow, 找到完美问题原因:
解决办法:在api控制器上加上 skip_before_action :verify_authenticity_token
我已经让ApiController直接继承ActionController::Base
class ApiController < ActionController::Base
但还是不能逃脱检查 伪信息和敏感请求参数。
Rails API
有一个模块RequestForgeryProtection,内有2个类方法:
第一个:
class ApplicationController < ActionController::Base
protect_from_forgery
end
⚠️,GET和HEAD request不会被检查
⚠️,有vaild options:
:only/:except
:if/:unless
:with => :null_session/:reset_session/:exception
第二个:
关掉虚假信息的请求保护
skip_before_action :verify_authenticity_token