Sunday, November 15, 2015

JSON web request using Python

Get the requests module
If you don't already have the requests module, follow these steps:
1. Download the requests module ZIP. Here's a direct link to the ZIP:

2. Unzip

3. Copy and paste the "requests" folder to C:\<python installation folder>\Lib\
Note: I'm using python 2.6, and my installation folder is C:\Python26


The explanation of what it's doing
#I'm using the Yahoo API to request the USD:EUR exchange rate
#It's passing back json format
#so i'm using a json decoder from the requests object
#then i'm navigating the dictionary of dictionaries to get to the exchange rate
#Note: There's no error handling or anything, this is just to show a simple example of how to do a web request in python

The Code
import json import requests #Get exchange rates req = requests.get(' * from where pair in ("USDEUR")&format=json&env=store://') res = req.json() exchangeRate = float(res["query"]["results"]["rate"]["Rate"]) #Get euros euros = float(raw_input("How many euros?")) #Convert USD = (euros * exchangeRate) #Output print """ Exchange rate: {0} Euros: {1} USD: {2} """.format(exchangeRate, euros, USD)

No comments:

Post a Comment

There was an error in this gadget