IBM Bluemix Weather Company API with Python

Here is a simple example of calling the IBM Weather Company REST API using Python. The program asks for a US ZIP code and then displays some of the data. A perfect program for an intro to programming class. Also, on GitHub.


# Using the IBM Bluemix Weather Company API
# Bruce Elgort
# July 9, 2016
# Version 1.0
# IBM Weather Company Docs: https://console.ng.bluemix.net/docs/services/Weather/weather_rest_apis.html#rest_apis

import requests
import json

def get_weather(zip):
    username = 'your username'
    password = 'your password'

    watsonUrl = 'https://twcservice.mybluemix.net/api/weather/v1/location/' + zip + ':4:US' + '/observations.json?language=en-US'

    try:
        r = requests.get(watsonUrl,auth=(username,password))
        return r.text
    except:
        return False

def display_weather(results):
    print()
    print('Here is the weather for {0}'.format(results['observation']['obs_name']))
    print('{0:20} {1:<10}'.format('Current Temperature:',str(results['observation']['temp']) + '° and ' + results['observation']['wx_phrase']))
    print('{0:20} {1:<10}'.format('Feels Like: ',str(results['observation']['feels_like']) + '°'))
    print('{0:20} {1:<10}'.format('Low Temp: ',str(results['observation']['min_temp']) + '°'))
    print('{0:20} {1:<10}'.format('High Temp: ',str(results['observation']['max_temp']) + '°'))
    print('{0:20} {1:<10}'.format('Winds:',str(results['observation']['wspd']) + ' mph coming from the ' + results['observation']['wdir_cardinal']))

def get_weather():
    zip = input('Enter US ZIP code to get weather for:\n')
    results = get_weather(zip)
    if results != False:
        results = json.loads(str(results))
        display_weather(results)
    else:
        print('Something went wrong :-(')

if __name__ == '__main__':
    get_weather()
Advertisements

Learn to Program with Python

MongoDB and Python: A Simple Example

The code below demonstrates how to use Python to connect to a MongoDB database. I chose to use a cloud based instance of MongoDB provided free of charge by MongoLab.com. The script demonstrates how to:

  • Use the PyMongo library to connect to a Mongo database
  • Insert documents into a collection
  • Display all of the documents from the collection

I also used a local instance of MongoDB for testing. You will will need to use a Python package manager such as EasyInstall to install the PyMongo library.

Here is the Python code:

# mongo_hello_world.py
# Author: Bruce Elgort
# Date: March 18, 2014
# Purpose: To demonstrate how to use Python to
# 1) Connect to a MongoDB document collection
# 2) Insert a document
# 3) Display all of the documents in a collection</code>

from pymongo import MongoClient

# connect to the MongoDB on MongoLab
# to learn more about MongoLab visit http://www.mongolab.com
# replace the "" in the line below with your MongoLab connection string
# you can also use a local MongoDB instance
connection = MongoClient("yourmongodbconnectionstring")

# connect to the students database and the ctec121 collection
db = connection.students.ctec121

# create a dictionary to hold student documents

# create dictionary
student_record = {}

# set flag variable
flag = True

# loop for data input
while (flag):
   # ask for input
   student_name,student_grade = input("Enter student name and grade: ").split(',')
   # place values in dictionary
   student_record = {'name':student_name,'grade':student_grade}
   # insert the record
   db.insert(student_record)
   # should we continue?
   flag = input('Enter another record? ')
   if (flag[0].upper() == 'N'):
      flag = False

# find all documents
results = db.find()

print()
print('+-+-+-+-+-+-+-+-+-+-+-+-+-+-')

# display documents from collection
for record in results:
# print out the document
print(record['name'] + ',',record['grade'])

print()

# close the connection to MongoDB
connection.close()

If you have any questions please let me know.