From 8ba00acea33a7046609cc82584364a6de3cecd17 Mon Sep 17 00:00:00 2001 From: Brodur <49418324+Brodur@users.noreply.github.com> Date: Thu, 8 Oct 2020 10:31:03 -0500 Subject: [PATCH 1/2] Updated swapi.rb to handle HTTP <-> HTTPS The base URL was incorrect, changed to "https://swapi.dev/api" URL redirect was not handled, added error handling from https://stackoverflow.com/a/39160567 --- lib/swapi.rb | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/lib/swapi.rb b/lib/swapi.rb index 8ec75de..82fae55 100644 --- a/lib/swapi.rb +++ b/lib/swapi.rb @@ -1,14 +1,14 @@ -require 'open-uri' +require "open-uri" module Swapi class << self - BASE_URL = 'http://swapi.co/api' - PLANETS = 'planets' - PEOPLE = 'people' - STARSHIPS = 'starships' - VEHICLES = 'vehicles' - SPECIES = 'species' - FILMS = 'films' + BASE_URL = "https://swapi.dev/api".freeze + PLANETS = "planets".freeze + PEOPLE = "people".freeze + STARSHIPS = "starships".freeze + VEHICLES = "vehicles".freeze + SPECIES = "species".freeze + FILMS = "films".freeze def get_all(type) get type @@ -40,12 +40,23 @@ def get_film(film_id) private - def get(type, id = '') + def get(type, id = "") response = execute_request("#{type}/#{id}") end def execute_request(uri) - response = open("#{BASE_URL}/#{uri}", "User-Agent" => "swapi-ruby").read + url = "#{BASE_URL}/#{uri}" + + uri = URI.parse(url) + tries = 3 + + begin + response = uri.open(redirect: false).read + rescue OpenURI::HTTPRedirect => e + uri = e.uri # assigned from the "Location" response header + retry if (tries -= 1) > 0 + raise + end end end end From 92902989e794c73386840c0659bae80d32998a92 Mon Sep 17 00:00:00 2001 From: Brodur <49418324+Brodur@users.noreply.github.com> Date: Thu, 8 Oct 2020 10:41:25 -0500 Subject: [PATCH 2/2] Added JSON Parsing by default Not a must have, but convenient to already have the JSON parsed and ready to use. --- lib/swapi.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/swapi.rb b/lib/swapi.rb index 82fae55..35ebc0a 100644 --- a/lib/swapi.rb +++ b/lib/swapi.rb @@ -51,7 +51,7 @@ def execute_request(uri) tries = 3 begin - response = uri.open(redirect: false).read + response = JSON.parse(uri.open(redirect: false).read) rescue OpenURI::HTTPRedirect => e uri = e.uri # assigned from the "Location" response header retry if (tries -= 1) > 0