Searching for Media on iTunes¶
You’ve already seen an example using the iTunes API in Generating Request URLs. The iTunes API allows users to search for movies, podcasts, music, music videos, tv shows, and books that are hosted on the iTunes site. You can explore the official iTunes API documentation.
Earlier we showed a possible query for podcasts about Ann Arbor. Now, we’ll show you how to construct it yourself!
We will first need to write our import statements, so that we have access to the requests module and json module.
import requests
import json
At this point, we look to our documentation to find out what the base of the url will be as well as what parameters are neeed to construct the request. In the Searching section of the documentation, we can see that the url should be in the form of https://itunes.apple.com/search?parameterkeyvalue
so we know the base url should be https://itunes.apple.com/search
. To determine what parameters are necessary, we can look at the table to learn what parameter keys are available, as well as get a description of the paramter, if it is required, and what values can be passed through it.
term
is a required parameter with no default value, so we’ll have to provide that.
exceptions-1: What should be the value associated with term?
import requests
import json
params = {"term": }
The value of term is
We also want to make sure that we’re searching for podcasts.
exceptions-2: Look at the iTunes documentation. What is the parameter we need to use to only search for podcasts?
Note that both entity
and media
are parameters we can use for this task. entity
can be more specific, though, so you may need to use that in other situations!
Now, our code can now make a request to the iTunes API:
import requests
import json
parameters = {"term": "Ann Arbor", "entity": "podcast"}
iTunes_response = requests.get("https://itunes.apple.com/search", params = parameters)
In the textbook, this first step would look like this:
All that is left to do is to convert the JSON response to a python object, and we’ll be all set to work with the data we have retrieved, which will be saved in the variable py_data
:
import requests
import json
parameters = {"term": "Ann Arbor", "entity": "podcast"}
itunes_response = requests.get("https://itunes.apple.com/search", params = parameters)
py_data = json.loads(itunes_response.text)