Personal Weather

Introduction

Interacting with remote APIs can be one of the most entertaining parts of programming. As a novice programmer, you can immediately enhance your application through simple calls to external services.

There are thousands of APIs you can use to display and interact with remote data. The possibilities are pretty much endless! Below, we’re going to walk through what would go into building a personal weather site. You could easily extend this into a homemade personal dashboard - for example: include custom news, personal recommendations from Etsy, and your friend’s most recent tweets. The possibilities are endless!

Personal Weather Application: Getting Started

Wunderground.com provides weather forecasts nationwide based on zip code lookup. Wunderground’s API allows you to find weather data based on parameters passed in by your application. For our basic weather application, we’ll show the current weather for Washington, DC.

Step 1: API Key

Sign up for an API key. An API key is a unique identifier that the website uses to track your usage of the site. Wunderground provides a key when you sign up.

Step 2: Determine What Data You Want

Check out the API documentation. For our application, we need to set up the query to find the current weather for zip code 20001.

Wunderground’s API query format is as follows:

http://api.wunderground.com/api/YOUR_API_KEY/hourly/q/20001.xml

Once you replace “YOUR_API_KEY” with your personal API key, you can put this search in the browser to make sure that it works. Note that 20001 is my zip code in Washington, DC.

Step 3: Building the Basic Application

In this tutorial, we’ll just get the minimum code up to make this work. After the site’s up, you can certainly push farther.

From the command line:

rails new personal_weather

Step 4: Set up your homepage

For the homepage, we’ll need a controller and a view.

Create the pages controller by typing the following in the command line:

rails g controller pages

Then, open up app/controllers/pages_controller.rb and add a blank method called home, which will indicate we want a home page:

class PagesController < ApplicationController
  def home
  end
end

To create the view (what will be seen by the user):

Navigate to the app/view/pages folder and create a new file called “home.html.erb” within it. In this file, you can write HTML, so let’s add <h1>Home Sweet Home!</h1> to the content of that file.

Lastly, we need to add the route so your application can appropriately direct traffic.

Navigate to “app/config/routes.rb” and add:

PersonalWeather::Application.routes.draw do
  get "pages/home"
  root :to => "pages#home"
end

Be sure to save all of those files as you go along! We’ve nearly got a complete rails site!

Step 5: Startup the Server

Go back to your command line and open a new tab. Type “rails server” to get your local server started. You can now go to any web browser and type “http://localhost:3000”. You should see a page that says “Welcome abord! You’re riding Ruby on Rails!”

That’s great, but we want our “Home Sweet Home!” page to show. Navigate to “app/public” and delete the index.html file. Then refresh the your browser - you should see Home Sweet Home!

Step 6: Create a WeatherLookup model

We need a good way to retrieve, manage, and save the information we get from Wunderground. Let’s do that in a WeatherLookup model. Instead of creating the model from the command line (which will give us way more than we need), let’s create one ourselves. Navigate to the app/models folder and create a file called “weather_lookup.rb”. Inside the file, type the following:

class WeatherLookup end

Step 7: Setting up HTTParty

To get the information from Wunderground (like we did in our browser), we’ll use a gem called HTTParty. To install the gem, go to your Gemfile and type the following:

gem 'httparty'

Save the file and go to your command line. Type “bundle install” to get HTTParty set up for your application.

Step 8: Fetch data from Wunderground

Within your WeatherLookup model, you can create a method called fetch_weather that has what’s called a “get request” to Wunderground’s API.

 def fetch_weather
    HTTParty.get("http://api.wunderground.com/api/YOUR_API_KEY/hourly/q/20001.xml")
 end

Note that the URL we’re using in our fetch_weather method is the same as what you put in the browser earlier!

Step 9: Saving what you Want

Each time we do a new weather lookup, we want to do a number of things:

  • Store the results from the fetch_weather method.
  • Grab the temperature and weather icon from the XML that Wunderground returns.

First, let’s assign our results from the fetch_weather method into a variable we can use called weather_hash. We’ll do that in a special method called initialize (initialize gets run when a new weather lookup is created).

def initialize
  weather_hash = fetch_weather
end

Then, let’s create a method called assign_value that will save the temperature and weather icon values for our use.

def assign_values(weather_hash)
      hourly_forecast_response = weather_hash.parsed_response['response']['hourly_forecast']['forecast'].first
      self.temperature = hourly_forecast_response['temp']['english']
      self.icon = hourly_forecast_response['icon_url']
 end

The code to the right of the equals sign is probably pretty confusing! What this is is us going inside the weather_hash and digging through nested hashes. You can navigate through these in rails console (we’ll go through that in the end - for now, you can take my word for it!)

After we create that assign_values method, we want to make sure it’s called upon initialize, too. Let’s add it to the initialize method:

def initialize
   weather_hash = fetch_weather
  assign_values(weather_hash)
end

We also want to make temperature and icon accessible on our home view. To do this, add them as attr_accessors above your initialize method:

 attr_accessor :temperature, :icon

Step 10: Doing a weather lookup when you visit home

Go back to app/controllers/pages_controller.rb. You’ll want the controller to do a new weather lookup each time we go to the home page. Add the following code inside your home method to create the new weather lookup:

def home
    @weather_lookup = WeatherLookup.new
end

Step 11: Modify your view

We now have some info that we can put on our home page. Go to your /app/views/home.html.erb file and replace <h1>Home Sweet Home!</h1> with the following code:

<h1>My Personal Weather Lookup</h1>
It is <%= @weather_lookup.temperature %> degrees in Washington, DC!
<%= image_tag @weather_lookup.icon %>

Step 12: Go live!

Restart your server by going to the command line tab in which you typed rails server and type CTRL+C, then rails server again.

Go to your browser and reload “http://localhost:3000/”. Your personal weather lookup should be up!

Extension: Viewing the results of the API call

In step 9, we already knew what values we wanted from the hash returned by our fetch_weather method. What if we didn’t or wanted to look up something else? This is easy using IRB. In a new terminal tab, type irb.

Then, make sure that you can use HTTParty by typing:

require 'httparty'

Now we can make our HTTParty get call straight from the terminal window:

HTTParty.get(“http://api.wunderground.com/api/YOUR_API_KEY/hourly/q/20001.xml”)

The results are super long! However, you can dig through and find all the data you need in the nested hashes to extract the right values.

Thanks! I hope you enjoyed the basic API Tutorial. Check out http://api-fun.herokuapp.com and https://github.com/eliseworthy/api_fun for ideas on how this simple app can be extended.

Just for starters, here are some ideas to keep going:

  • Push your application to Heroku
  • Create validation for the temperature and icon in case the service is unavailable
  • Allow for a user-defined zip code
  • Find another API and add dynamic content to your home page!