Euan Williams
Euan Williams

Reputation: 11

How to use urllib2 in python 3.4 to get information from an API?

I am trying to get the latitude and longitude of the ISS from the site:

https://api.wheretheiss.at/v1/satellites/25544

I have managed to work out I need to use urllib2, but I can't install it using pip, I get the error:

Could not find a version that satisfies the requirement urllib2 <from the version: > 
No matching distribution found for urllib2 

Could someone tell me how I can install urllib2 and also the code I would need to use to get the latitude and longitude? Thanks.

Upvotes: 1

Views: 6665

Answers (1)

erewok
erewok

Reputation: 7835

Python3.4 includes urllib (not urllib2) by default. To use it, simply import urllib.

Also, be aware that you should follow urllib docs for Python3.4 because things have been moved and are in a different place from where you would expect them if you were looking at urllib2, which was for Python2.

For instance, to request a url using urllib, you would do the following:

from urllib.request import urlopen
with urlopen(url) as link:
    result = link.read()

However, it is recommended (even by the urllib documentation) that you use requests instead:

$ pip install requests

Then, to use requests, you can do the following:

>>> import requests
>>> response = requests.get(url)
etc.

Finally, your endpoint up there is returning JSON, so using requests you can access those values in the following way:

>>> result = response.json()
>>> result['some_key']
['some values...']

Upvotes: 3

Related Questions