Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Faraday your way into APIs

Faraday your way into APIs

An introduction to faraday, a great tool to communicate with external APIs.

Other Decks in Programming

Transcript

  1. • Error management • Won’t follow redirect • Need to

    parse JSON • Need SSL support The built-in way require 'net/http' data = Net::HTTP.get URI.parse(‘https://api.github.com/users/alexcp')
  2. require 'net/https' require 'json' ! url = URI.parse('https://api.github.com/users/alexcp') ! http

    = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE response = http.request(Net::HTTP::Get.new(url.request_uri)) ! if response.code == 200 JSON.parse response.body else response.error! end The built-in way
  3. Issues with Net::HTTP • Interface is hard to guess •

    Inconsistent interface • Bad exception handling
  4. require 'faraday' require 'faraday_middleware' ! conn = Faraday.new(url: 'https://api.github.com') do

    |c| c.use Faraday::Adapter::NetHttp c.use FaradayMiddleware::ParseJson, content_type: 'application/json' c.use FaradayMiddleware::FollowRedirects, limit: 3 c.use Faraday::Response::RaiseError # raise exceptions on 40x, 50x end ! response = conn.get '/users/alexcp' response.body # {"login"=>"alexcp", "id"=>684172, ...} Middleware
  5. class MiddlewareExample def initialize(app, options = {}) @app = app

    @options = options end ! def call(env) # do something with the request @app.call(env).on_complete do # do something with the response end end end Middleware