DEV Community

Adam La Rosa
Adam La Rosa

Posted on

Star Wars Recursion

Following my exploration of the maze recursion proved to be a powerful tool. While exploring the a Star Wars API (also known as the "swapi") I was able to use recursion to search a portion of the API in its entirety.

The Star Wars API (which can be found at http://www.swapi.co) is a neat little tool I've found useful to play around with. What I found odd at first though is that when asking for a particular resource, "people" for example, not all results were returned at once. For example...

JSON.parse(RestClient.get(http://www.swapi.co/people/))

...returns a hash with four keys.

["count", "next", "previous", "results"]

A quick look at the size of "results" show me I've received ten characters from the Star Wars movies. But as "count" is an integer of 87, I know I'm missing 77 characters to dream about. The "next" key points to another web address to what I assume will be ten more results.

How exactly can I get them all at once? Recursion!

I figure I can write a method that will pull down the first results, check to see if there's a valid address in the "next" key, and if so use the same method to keep fetching characters. In this pursuit I ended up with the following class...

require 'rest-client'
require 'json'

class Swapi
  def initialize
    @people = []
  end

  def get_planets(path)
    planets = JSON.parse(RestClient.get(path))
    planets["results"].each { |planet| @planets << planet }
    return "complete" if planets["next"] == nil
    get_planets(planets["next"])
  end

  def people
    @people
  end
end

With the instance variable I've got a spot to put all the results. That combined with the main "get_planets" method that calls itself & a getter to view the results I execute it with the first people address...

p = Swapi.new
p.get_people("http://www.swapi.co/api/people/")

With that all 87 of the results are loaded into a single array.

Top comments (0)