安装:rest-client4400✨
gem install rest-client
一个简单的HTTP和REST client for Ruby.javascript
能够用它来发HTTP请求css
基本用法:html
require 'rest-client' java
RestClient.get(url, headers={})git
RestClient.post(url, payload, headers={}) github
Application Programming Interface: 程序和程序的接口,定义接口叫什么名字,要传什么参数进去,它会回传什么东西出来,可能回发生的errors等等。web
在写Ruby程序的时候,使用library库的方法,这时候API就是method的名字,参数,回传值等等。 数据库
对Web应用来讲,API就是在定义网址URL的样子,请求的HTTP方法是什么,传什么参数过去,返回什么资料格式。json
经常使用的就是JSON, XML。api
JSON格式的转化,to_json和parse
> require 'json'
使用聚合数据网
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
根据火车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 指未经过真实性验证。
在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
train.reservations.pluck(:seat_number)
获得关联对象集合的某个属性的集合: 至关于查询method
Reservation.joins(:trains).where("trains.id == *** ").select(:seat_number)
或者 纯SQL
select reservations.seat_number FROM reservations inner JOIN trains ON trains.id == reservations.train_id where train.id == **
给火车订票系统,添加用户,用户能够订票
重点1
给user增长一个API key ,做为惟一识别码。
add_index :users, :authenication_token, :unique => true
在user.rb中,添加self.authentication_token = Devise.friendly_token
一个随机的20个字母的字符串 (见gem 文档)
惟一的识别码,
如何写用户认证API:
https://github.com/plataformatec/devise/wiki/How-To:-Simple-Token-Authentication-Example (已过时,有可选的连接)
可选:
Token ,基于Rails JSON APIs的验证的token。
能够和devise一块儿用,支持使用Devise进行email验证,以及用户注册,登入,密码相关修改。
request.format = :json
增长一个views/api/v1/trains/show.json.jbuilder
在controllers/api/v1/trains_controller.rb中增长show方法。
⚠️写网址的时候务必加上.json
http://localhost:4000/api/v1/trains/0603.json
不然没法找到show.json.jbuilder模版,由于默认是text/html。
或者在controller中加上:
分析:get "/trains/:train_number" => 'trains#show', :as => :train
/trains/:train_number 是指URL, 相似user/:id
⚠️加上冒号:,是指具体的记录的属性名称。
as: :train是用于生成helper连接 ,train_url(train.number)
分页功能:
加入gem 'kaminari'
rails g kaminari:config 而后设置默认每页数量,重启服务器。
在控制器@trains = Train.order(:number).page(params[:page])
在views:
给Train加一个图片
has_one_attached :image
上传:
train.logo.attach(io: File.open("/Users/chentianwei/Desktop/bose.jpg"),
filename: "bose.jpg",
content_type: "image/jpg")
合并分支 :
git checkout master
git merge train_book
完成后上传到git. https://github.com/chentianwei411
远程仓库若是变化了,本地就不能git push 了,须要先git fetch,但我彷佛fetch不下来?
学习git 的连接:
https://git-scm.com/
对API 进行测试
以前的博客:https://www.cnblogs.com/chentianwei/p/9060522.html , http://www.cnblogs.com/chentianwei/p/9124505.html
加上gem 'rspec-rails'
Web API 测试的重点是:
对API测试,是请求测试,即对请求的回复结果的判断是不是预期判断:
使用rails g rspec:request XXX 快速生成
spec/requests/auth_spec.rb
RSpec.describe "API_V1::Auth", :type => :request do
HTTPVerb 路径, params:{hash参数}
expect(response).to have_http_status(响应数字)
expect(response.body).to eq({hash参数}.to_json)
end
一个例子:
重点1:
response的网页状态码能够在controller中设置,如:
def signup