Faraday w/ auto-run

Start tinkering

HTTP requests to httpbingo.org with Faraday incl. some middleware.

require "bundler/inline"

gemfile do
  source "https://rubygems.org"
  gem "keepgoing" # auto-runs script on changes
  gem "faraday", "~> 2.3"
  gem "faraday-retry", "~> 1.0"

require "faraday"
require "faraday/retry"

# configure Faraday incl. some middleware
retry_options = {
  max: 2,
  interval: 0.5,
  retry_statuses: [500],
  retry_block: -> (env, _options, _retries, _exc) { puts "\n\ngot #{env.status} 😱 will retry\n\n" }

connection = Faraday.new("http://httpbingo.org") do |f|
  f.request :json # encode req bodies as JSON and automatically set the Content-Type header
  f.request :retry, retry_options
  f.response :json # decode response bodies as JSON
  f.response :logger

# POST request
response = connection.post("/post") do |req|
  req.params["limit"] = 100
  req.body = {query: "chunky bacon"}

# GET some json
response = connection.get("/json")
puts "\n", response.body.dig("slideshow", "title"), "\n"

# test-drive retries
response = connection.get("/unstable")
puts "\n", response.status