(In order to load the stylesheet of this notebook, execute the last code cell in this notebook)

NYT Books: Finding the popular best-sellers

Introduction

In this assignment, we will compile a list of books that were best-sellers during the summer of 2014. To get this list, we will use the Books API, from the New York Times.


Step 0. Preparation

Before we start working on the notebook, let's make sure that everything is setup properly. You should have downloaded and installed

If you are working from the undergraduate lab (on a linux machine) these are both installed, but you need to follow the instructions from here.

Step 1. Acquiring access to the API

Like most APIs, NYT requires that each developer should have a private (secret) key in order to use their services. This way, they are able to throttle the number of requests that are being issued. According to their website, this limit is at 5,000 requests per day. You can register here. When asked, request a key for the Best Sellers API. Your key will be in the next web page. Save it in a text file named key.txt, in the same folder as this notebook.

Do not add this key to your repo (git add) because it includes sensitive information that only you should know. To make sure that you do not add this by mistake, you will need to tell git which files to always ignore. We can do this by creating a .gitignore file under the root directory of the repository (spring-2015-homeworks/) and inside it add the path to the file that you want to ignore:

submissions/Homework-1/key.txt

If you did this right, the file should not come up when you type git status.

Now that we donwloaded our key, we should read it into a variable to use it for the rest of this notebook.


In [1]:
key = ""
with open('key.txt','r') as f:
    key = f.readline().strip()

if len(key) > 0:
    print "Succesfully retrieved API key"


Succesfully retrieved API key

Let's make a sample request to check that everything works fine. We will retrieve the names of NYT best-seller lists.


In [2]:
import requests

response = requests.get("http://api.nytimes.com/svc/books/v3/lists/names.json?api-key=%s"%(key))
print response


<Response [200]>

Before we generate the request string, we need to read the guidelines from here. According to the documentation under the BEST-SELLER LIST NAMES section, the request must follow this URI structure:

http://api.nytimes.com/svc/books/{version}/lists/names[.response_format]?api-key={your-API-key}

We need to replace {version} with v3, the response_format with json and include our secrete API key.

We can try to print the response that NYT returns.


In [4]:
print response.text


{"status":"OK","copyright":"Copyright (c) 2015 The New York Times Company.  All Rights Reserved.","num_results":47,"results":[{"list_name":"Combined Print and E-Book Fiction","display_name":"Combined Print & E-Book Fiction","list_name_encoded":"combined-print-and-e-book-fiction","oldest_published_date":"2011-02-13","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Combined Print and E-Book Nonfiction","display_name":"Combined Print & E-Book Nonfiction","list_name_encoded":"combined-print-and-e-book-nonfiction","oldest_published_date":"2011-02-13","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Hardcover Fiction","display_name":"Hardcover Fiction","list_name_encoded":"hardcover-fiction","oldest_published_date":"2008-06-08","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Hardcover Nonfiction","display_name":"Hardcover Nonfiction","list_name_encoded":"hardcover-nonfiction","oldest_published_date":"2008-06-08","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Trade Fiction Paperback","display_name":"Paperback Trade Fiction","list_name_encoded":"trade-fiction-paperback","oldest_published_date":"2008-06-08","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Mass Market Paperback","display_name":"Paperback Mass-Market Fiction","list_name_encoded":"mass-market-paperback","oldest_published_date":"2008-06-08","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Paperback Nonfiction","display_name":"Paperback Nonfiction","list_name_encoded":"paperback-nonfiction","oldest_published_date":"2008-06-08","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"E-Book Fiction","display_name":"E-Book Fiction","list_name_encoded":"e-book-fiction","oldest_published_date":"2011-02-13","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"E-Book Nonfiction","display_name":"E-Book Nonfiction","list_name_encoded":"e-book-nonfiction","oldest_published_date":"2011-02-13","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Hardcover Advice","display_name":"Hardcover Advice & Misc.","list_name_encoded":"hardcover-advice","oldest_published_date":"2008-06-08","newest_published_date":"2013-04-21","updated":"WEEKLY"},{"list_name":"Paperback Advice","display_name":"Paperback Advice & Misc.","list_name_encoded":"paperback-advice","oldest_published_date":"2008-06-08","newest_published_date":"2013-04-21","updated":"WEEKLY"},{"list_name":"Advice How-To and Miscellaneous","display_name":"Advice, How-To & Miscellaneous","list_name_encoded":"advice-how-to-and-miscellaneous","oldest_published_date":"2013-04-28","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Picture Books","display_name":"Children's Picture Books","list_name_encoded":"picture-books","oldest_published_date":"2008-06-08","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Chapter Books","display_name":"Children's Chapter Books","list_name_encoded":"chapter-books","oldest_published_date":"2008-06-08","newest_published_date":"2012-12-09","updated":"WEEKLY"},{"list_name":"Childrens Middle Grade","display_name":"Children's Middle Grade","list_name_encoded":"childrens-middle-grade","oldest_published_date":"2012-12-16","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Young Adult","display_name":"Young Adult","list_name_encoded":"young-adult","oldest_published_date":"2012-12-16","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Paperback Books","display_name":"Children's Paperback Books","list_name_encoded":"paperback-books","oldest_published_date":"2008-06-08","newest_published_date":"2012-12-09","updated":"WEEKLY"},{"list_name":"Series Books","display_name":"Children's Series","list_name_encoded":"series-books","oldest_published_date":"2008-06-08","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Hardcover Graphic Books","display_name":"Hardcover Graphic Books","list_name_encoded":"hardcover-graphic-books","oldest_published_date":"2009-03-15","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Paperback Graphic Books","display_name":"Paperback Graphic Books","list_name_encoded":"paperback-graphic-books","oldest_published_date":"2009-03-15","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Manga","display_name":"Manga","list_name_encoded":"manga","oldest_published_date":"2009-03-15","newest_published_date":"2015-02-08","updated":"WEEKLY"},{"list_name":"Combined Print Fiction","display_name":"Combined Hardcover & Paperback Fiction","list_name_encoded":"combined-print-fiction","oldest_published_date":"2011-02-13","newest_published_date":"2013-05-12","updated":"WEEKLY"},{"list_name":"Combined Print Nonfiction","display_name":"Combined Hardcover & Paperback Nonfiction","list_name_encoded":"combined-print-nonfiction","oldest_published_date":"2011-02-13","newest_published_date":"2013-05-12","updated":"WEEKLY"},{"list_name":"Animals","display_name":"Animals","list_name_encoded":"animals","oldest_published_date":"2014-09-07","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Business Books","display_name":"Business","list_name_encoded":"business-books","oldest_published_date":"2013-11-03","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Celebrities","display_name":"Celebrities","list_name_encoded":"celebrities","oldest_published_date":"2014-09-07","newest_published_date":"2015-02-15","updated":"MONTHLY"},{"list_name":"Crime and Punishment","display_name":"Crime and Punishment","list_name_encoded":"crime-and-punishment","oldest_published_date":"2014-10-12","newest_published_date":"2015-02-15","updated":"MONTHLY"},{"list_name":"Culture","display_name":"Culture","list_name_encoded":"culture","oldest_published_date":"2014-10-12","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Education","display_name":"Education","list_name_encoded":"education","oldest_published_date":"2014-10-12","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Espionage","display_name":"Espionage","list_name_encoded":"espionage","oldest_published_date":"2014-12-14","newest_published_date":"2015-02-15","updated":"MONTHLY"},{"list_name":"Expeditions Disasters and Adventures","display_name":"Expeditions, Disasters and Adventures","list_name_encoded":"expeditions-disasters-and-adventures","oldest_published_date":"2014-12-14","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Family","display_name":"Family","list_name_encoded":"family","oldest_published_date":"2014-09-07","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Fashion Manners and Customs","display_name":"Fashion, Manners and Customs","list_name_encoded":"fashion-manners-and-customs","oldest_published_date":"2014-10-12","newest_published_date":"2015-02-15","updated":"MONTHLY"},{"list_name":"Food and Fitness","display_name":"Food and Fitness","list_name_encoded":"food-and-fitness","oldest_published_date":"2013-09-01","newest_published_date":"2015-02-15","updated":"MONTHLY"},{"list_name":"Games and Activities","display_name":"Games and Activities","list_name_encoded":"games-and-activities","oldest_published_date":"2014-10-12","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Hardcover Business Books","display_name":"Hardcover Business Books","list_name_encoded":"hardcover-business-books","oldest_published_date":"2011-07-03","newest_published_date":"2013-10-13","updated":"MONTHLY"},{"list_name":"Health","display_name":"Health","list_name_encoded":"health","oldest_published_date":"2014-10-12","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Humor","display_name":"Humor","list_name_encoded":"humor","oldest_published_date":"2014-09-07","newest_published_date":"2015-02-15","updated":"MONTHLY"},{"list_name":"Indigenous Americans","display_name":"Indigenous Americans","list_name_encoded":"indigenous-americans","oldest_published_date":"2014-12-14","newest_published_date":"2015-02-15","updated":"MONTHLY"},{"list_name":"Paperback Business Books","display_name":"Paperback Business Books","list_name_encoded":"paperback-business-books","oldest_published_date":"2011-07-03","newest_published_date":"2013-10-13","updated":"MONTHLY"},{"list_name":"Hardcover Political Books","display_name":"Politics","list_name_encoded":"hardcover-political-books","oldest_published_date":"2011-07-03","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Race and Civil Rights","display_name":"Race and Civil Rights","list_name_encoded":"race-and-civil-rights","oldest_published_date":"2014-12-14","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Relationships","display_name":"Relationships","list_name_encoded":"relationships","oldest_published_date":"2014-09-07","newest_published_date":"2015-02-15","updated":"MONTHLY"},{"list_name":"Religion Spirituality and Faith","display_name":"Religion, Spirituality and Faith","list_name_encoded":"religion-spirituality-and-faith","oldest_published_date":"2014-09-07","newest_published_date":"2015-02-15","updated":"MONTHLY"},{"list_name":"Science","display_name":"Science","list_name_encoded":"science","oldest_published_date":"2013-04-14","newest_published_date":"2015-02-15","updated":"MONTHLY"},{"list_name":"Sports","display_name":"Sports","list_name_encoded":"sports","oldest_published_date":"2014-03-02","newest_published_date":"2015-01-11","updated":"MONTHLY"},{"list_name":"Travel","display_name":"Travel","list_name_encoded":"travel","oldest_published_date":"2014-09-07","newest_published_date":"2015-02-15","updated":"MONTHLY"}]}

It is not possible to read the raw response. Instead, we need to decode the raw response as JSON and use the json library to print it.


In [5]:
import json
print json.dumps(response.json(), indent=2)


{
  "status": "OK", 
  "num_results": 47, 
  "results": [
    {
      "updated": "WEEKLY", 
      "display_name": "Combined Print & E-Book Fiction", 
      "list_name_encoded": "combined-print-and-e-book-fiction", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2011-02-13", 
      "list_name": "Combined Print and E-Book Fiction"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Combined Print & E-Book Nonfiction", 
      "list_name_encoded": "combined-print-and-e-book-nonfiction", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2011-02-13", 
      "list_name": "Combined Print and E-Book Nonfiction"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Hardcover Fiction", 
      "list_name_encoded": "hardcover-fiction", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Hardcover Fiction"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Hardcover Nonfiction", 
      "list_name_encoded": "hardcover-nonfiction", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Hardcover Nonfiction"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Paperback Trade Fiction", 
      "list_name_encoded": "trade-fiction-paperback", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Trade Fiction Paperback"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Paperback Mass-Market Fiction", 
      "list_name_encoded": "mass-market-paperback", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Mass Market Paperback"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Paperback Nonfiction", 
      "list_name_encoded": "paperback-nonfiction", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Paperback Nonfiction"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "E-Book Fiction", 
      "list_name_encoded": "e-book-fiction", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2011-02-13", 
      "list_name": "E-Book Fiction"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "E-Book Nonfiction", 
      "list_name_encoded": "e-book-nonfiction", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2011-02-13", 
      "list_name": "E-Book Nonfiction"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Hardcover Advice & Misc.", 
      "list_name_encoded": "hardcover-advice", 
      "newest_published_date": "2013-04-21", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Hardcover Advice"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Paperback Advice & Misc.", 
      "list_name_encoded": "paperback-advice", 
      "newest_published_date": "2013-04-21", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Paperback Advice"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Advice, How-To & Miscellaneous", 
      "list_name_encoded": "advice-how-to-and-miscellaneous", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2013-04-28", 
      "list_name": "Advice How-To and Miscellaneous"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Children's Picture Books", 
      "list_name_encoded": "picture-books", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Picture Books"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Children's Chapter Books", 
      "list_name_encoded": "chapter-books", 
      "newest_published_date": "2012-12-09", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Chapter Books"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Children's Middle Grade", 
      "list_name_encoded": "childrens-middle-grade", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2012-12-16", 
      "list_name": "Childrens Middle Grade"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Young Adult", 
      "list_name_encoded": "young-adult", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2012-12-16", 
      "list_name": "Young Adult"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Children's Paperback Books", 
      "list_name_encoded": "paperback-books", 
      "newest_published_date": "2012-12-09", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Paperback Books"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Children's Series", 
      "list_name_encoded": "series-books", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2008-06-08", 
      "list_name": "Series Books"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Hardcover Graphic Books", 
      "list_name_encoded": "hardcover-graphic-books", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2009-03-15", 
      "list_name": "Hardcover Graphic Books"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Paperback Graphic Books", 
      "list_name_encoded": "paperback-graphic-books", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2009-03-15", 
      "list_name": "Paperback Graphic Books"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Manga", 
      "list_name_encoded": "manga", 
      "newest_published_date": "2015-02-08", 
      "oldest_published_date": "2009-03-15", 
      "list_name": "Manga"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Combined Hardcover & Paperback Fiction", 
      "list_name_encoded": "combined-print-fiction", 
      "newest_published_date": "2013-05-12", 
      "oldest_published_date": "2011-02-13", 
      "list_name": "Combined Print Fiction"
    }, 
    {
      "updated": "WEEKLY", 
      "display_name": "Combined Hardcover & Paperback Nonfiction", 
      "list_name_encoded": "combined-print-nonfiction", 
      "newest_published_date": "2013-05-12", 
      "oldest_published_date": "2011-02-13", 
      "list_name": "Combined Print Nonfiction"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Animals", 
      "list_name_encoded": "animals", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2014-09-07", 
      "list_name": "Animals"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Business", 
      "list_name_encoded": "business-books", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2013-11-03", 
      "list_name": "Business Books"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Celebrities", 
      "list_name_encoded": "celebrities", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2014-09-07", 
      "list_name": "Celebrities"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Crime and Punishment", 
      "list_name_encoded": "crime-and-punishment", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2014-10-12", 
      "list_name": "Crime and Punishment"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Culture", 
      "list_name_encoded": "culture", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2014-10-12", 
      "list_name": "Culture"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Education", 
      "list_name_encoded": "education", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2014-10-12", 
      "list_name": "Education"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Espionage", 
      "list_name_encoded": "espionage", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2014-12-14", 
      "list_name": "Espionage"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Expeditions, Disasters and Adventures", 
      "list_name_encoded": "expeditions-disasters-and-adventures", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2014-12-14", 
      "list_name": "Expeditions Disasters and Adventures"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Family", 
      "list_name_encoded": "family", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2014-09-07", 
      "list_name": "Family"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Fashion, Manners and Customs", 
      "list_name_encoded": "fashion-manners-and-customs", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2014-10-12", 
      "list_name": "Fashion Manners and Customs"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Food and Fitness", 
      "list_name_encoded": "food-and-fitness", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2013-09-01", 
      "list_name": "Food and Fitness"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Games and Activities", 
      "list_name_encoded": "games-and-activities", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2014-10-12", 
      "list_name": "Games and Activities"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Hardcover Business Books", 
      "list_name_encoded": "hardcover-business-books", 
      "newest_published_date": "2013-10-13", 
      "oldest_published_date": "2011-07-03", 
      "list_name": "Hardcover Business Books"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Health", 
      "list_name_encoded": "health", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2014-10-12", 
      "list_name": "Health"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Humor", 
      "list_name_encoded": "humor", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2014-09-07", 
      "list_name": "Humor"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Indigenous Americans", 
      "list_name_encoded": "indigenous-americans", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2014-12-14", 
      "list_name": "Indigenous Americans"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Paperback Business Books", 
      "list_name_encoded": "paperback-business-books", 
      "newest_published_date": "2013-10-13", 
      "oldest_published_date": "2011-07-03", 
      "list_name": "Paperback Business Books"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Politics", 
      "list_name_encoded": "hardcover-political-books", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2011-07-03", 
      "list_name": "Hardcover Political Books"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Race and Civil Rights", 
      "list_name_encoded": "race-and-civil-rights", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2014-12-14", 
      "list_name": "Race and Civil Rights"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Relationships", 
      "list_name_encoded": "relationships", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2014-09-07", 
      "list_name": "Relationships"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Religion, Spirituality and Faith", 
      "list_name_encoded": "religion-spirituality-and-faith", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2014-09-07", 
      "list_name": "Religion Spirituality and Faith"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Science", 
      "list_name_encoded": "science", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2013-04-14", 
      "list_name": "Science"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Sports", 
      "list_name_encoded": "sports", 
      "newest_published_date": "2015-01-11", 
      "oldest_published_date": "2014-03-02", 
      "list_name": "Sports"
    }, 
    {
      "updated": "MONTHLY", 
      "display_name": "Travel", 
      "list_name_encoded": "travel", 
      "newest_published_date": "2015-02-15", 
      "oldest_published_date": "2014-09-07", 
      "list_name": "Travel"
    }
  ], 
  "copyright": "Copyright (c) 2015 The New York Times Company.  All Rights Reserved."
}

Now, this is much better! We can easily see that the response consists of a response status, the number of results and a list of the best-seller lists. For each of these lists, we get information about its name, its update frequency, its lifetime and its codename.

Instead of JSON, we can also set the response type to be XML.


In [9]:
response = requests.get("http://api.nytimes.com/svc/books/v3/lists/names.xml?api-key=%s"%(key))
print response.text[:500]


<?xml version="1.0" encoding="UTF-8"?>
<result_set><status>OK</status><copyright>Copyright (c) 2015 The New York Times Company.  All Rights Reserved.</copyright><num_results>47</num_results><results><result><list_name>Combined Print and E-Book Fiction</list_name><display_name><![CDATA[Combined Print & E-Book Fiction]]></display_name><list_name_encoded>combined-print-and-e-book-fiction</list_name_encoded><oldest_published_date>2011-02-13</oldest_published_date><newest_published_date>2015-02-08</n

Again, as before, we can use a library to print the XML in a readable way.


In [8]:
import xml.dom.minidom
xml_parser = xml.dom.minidom.parseString(response.text)
pretty_response = xml_parser.toprettyxml()
print pretty_response


<?xml version="1.0" ?>
<result_set>
	<status>OK</status>
	<copyright>Copyright (c) 2015 The New York Times Company.  All Rights Reserved.</copyright>
	<num_results>47</num_results>
	<results>
		<result>
			<list_name>Combined Print and E-Book Fiction</list_name>
			<display_name>
<![CDATA[Combined Print & E-Book Fiction]]>			</display_name>
			<list_name_encoded>combined-print-and-e-book-fiction</list_name_encoded>
			<oldest_published_date>2011-02-13</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Combined Print and E-Book Nonfiction</list_name>
			<display_name>
<![CDATA[Combined Print & E-Book Nonfiction]]>			</display_name>
			<list_name_encoded>combined-print-and-e-book-nonfiction</list_name_encoded>
			<oldest_published_date>2011-02-13</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Hardcover Fiction</list_name>
			<display_name>Hardcover Fiction</display_name>
			<list_name_encoded>hardcover-fiction</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Hardcover Nonfiction</list_name>
			<display_name>Hardcover Nonfiction</display_name>
			<list_name_encoded>hardcover-nonfiction</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Trade Fiction Paperback</list_name>
			<display_name>Paperback Trade Fiction</display_name>
			<list_name_encoded>trade-fiction-paperback</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Mass Market Paperback</list_name>
			<display_name>Paperback Mass-Market Fiction</display_name>
			<list_name_encoded>mass-market-paperback</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Paperback Nonfiction</list_name>
			<display_name>Paperback Nonfiction</display_name>
			<list_name_encoded>paperback-nonfiction</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>E-Book Fiction</list_name>
			<display_name>E-Book Fiction</display_name>
			<list_name_encoded>e-book-fiction</list_name_encoded>
			<oldest_published_date>2011-02-13</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>E-Book Nonfiction</list_name>
			<display_name>E-Book Nonfiction</display_name>
			<list_name_encoded>e-book-nonfiction</list_name_encoded>
			<oldest_published_date>2011-02-13</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Hardcover Advice</list_name>
			<display_name>
<![CDATA[Hardcover Advice & Misc.]]>			</display_name>
			<list_name_encoded>hardcover-advice</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2013-04-21</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Paperback Advice</list_name>
			<display_name>
<![CDATA[Paperback Advice & Misc.]]>			</display_name>
			<list_name_encoded>paperback-advice</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2013-04-21</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Advice How-To and Miscellaneous</list_name>
			<display_name>
<![CDATA[Advice, How-To & Miscellaneous]]>			</display_name>
			<list_name_encoded>advice-how-to-and-miscellaneous</list_name_encoded>
			<oldest_published_date>2013-04-28</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Picture Books</list_name>
			<display_name>Children's Picture Books</display_name>
			<list_name_encoded>picture-books</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Chapter Books</list_name>
			<display_name>Children's Chapter Books</display_name>
			<list_name_encoded>chapter-books</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2012-12-09</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Childrens Middle Grade</list_name>
			<display_name>Children's Middle Grade</display_name>
			<list_name_encoded>childrens-middle-grade</list_name_encoded>
			<oldest_published_date>2012-12-16</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Young Adult</list_name>
			<display_name>Young Adult</display_name>
			<list_name_encoded>young-adult</list_name_encoded>
			<oldest_published_date>2012-12-16</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Paperback Books</list_name>
			<display_name>Children's Paperback Books</display_name>
			<list_name_encoded>paperback-books</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2012-12-09</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Series Books</list_name>
			<display_name>Children's Series</display_name>
			<list_name_encoded>series-books</list_name_encoded>
			<oldest_published_date>2008-06-08</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Hardcover Graphic Books</list_name>
			<display_name>Hardcover Graphic Books</display_name>
			<list_name_encoded>hardcover-graphic-books</list_name_encoded>
			<oldest_published_date>2009-03-15</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Paperback Graphic Books</list_name>
			<display_name>Paperback Graphic Books</display_name>
			<list_name_encoded>paperback-graphic-books</list_name_encoded>
			<oldest_published_date>2009-03-15</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Manga</list_name>
			<display_name>Manga</display_name>
			<list_name_encoded>manga</list_name_encoded>
			<oldest_published_date>2009-03-15</oldest_published_date>
			<newest_published_date>2015-02-08</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Combined Print Fiction</list_name>
			<display_name>
<![CDATA[Combined Hardcover & Paperback Fiction]]>			</display_name>
			<list_name_encoded>combined-print-fiction</list_name_encoded>
			<oldest_published_date>2011-02-13</oldest_published_date>
			<newest_published_date>2013-05-12</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Combined Print Nonfiction</list_name>
			<display_name>
<![CDATA[Combined Hardcover & Paperback Nonfiction]]>			</display_name>
			<list_name_encoded>combined-print-nonfiction</list_name_encoded>
			<oldest_published_date>2011-02-13</oldest_published_date>
			<newest_published_date>2013-05-12</newest_published_date>
			<updated>WEEKLY</updated>
		</result>
		<result>
			<list_name>Animals</list_name>
			<display_name>Animals</display_name>
			<list_name_encoded>animals</list_name_encoded>
			<oldest_published_date>2014-09-07</oldest_published_date>
			<newest_published_date>2015-01-11</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Business Books</list_name>
			<display_name>Business</display_name>
			<list_name_encoded>business-books</list_name_encoded>
			<oldest_published_date>2013-11-03</oldest_published_date>
			<newest_published_date>2015-01-11</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Celebrities</list_name>
			<display_name>Celebrities</display_name>
			<list_name_encoded>celebrities</list_name_encoded>
			<oldest_published_date>2014-09-07</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Crime and Punishment</list_name>
			<display_name>Crime and Punishment</display_name>
			<list_name_encoded>crime-and-punishment</list_name_encoded>
			<oldest_published_date>2014-10-12</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Culture</list_name>
			<display_name>Culture</display_name>
			<list_name_encoded>culture</list_name_encoded>
			<oldest_published_date>2014-10-12</oldest_published_date>
			<newest_published_date>2015-01-11</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Education</list_name>
			<display_name>Education</display_name>
			<list_name_encoded>education</list_name_encoded>
			<oldest_published_date>2014-10-12</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Espionage</list_name>
			<display_name>Espionage</display_name>
			<list_name_encoded>espionage</list_name_encoded>
			<oldest_published_date>2014-12-14</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Expeditions Disasters and Adventures</list_name>
			<display_name>Expeditions, Disasters and Adventures</display_name>
			<list_name_encoded>expeditions-disasters-and-adventures</list_name_encoded>
			<oldest_published_date>2014-12-14</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Family</list_name>
			<display_name>Family</display_name>
			<list_name_encoded>family</list_name_encoded>
			<oldest_published_date>2014-09-07</oldest_published_date>
			<newest_published_date>2015-01-11</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Fashion Manners and Customs</list_name>
			<display_name>Fashion, Manners and Customs</display_name>
			<list_name_encoded>fashion-manners-and-customs</list_name_encoded>
			<oldest_published_date>2014-10-12</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Food and Fitness</list_name>
			<display_name>Food and Fitness</display_name>
			<list_name_encoded>food-and-fitness</list_name_encoded>
			<oldest_published_date>2013-09-01</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Games and Activities</list_name>
			<display_name>Games and Activities</display_name>
			<list_name_encoded>games-and-activities</list_name_encoded>
			<oldest_published_date>2014-10-12</oldest_published_date>
			<newest_published_date>2015-01-11</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Hardcover Business Books</list_name>
			<display_name>Hardcover Business Books</display_name>
			<list_name_encoded>hardcover-business-books</list_name_encoded>
			<oldest_published_date>2011-07-03</oldest_published_date>
			<newest_published_date>2013-10-13</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Health</list_name>
			<display_name>Health</display_name>
			<list_name_encoded>health</list_name_encoded>
			<oldest_published_date>2014-10-12</oldest_published_date>
			<newest_published_date>2015-01-11</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Humor</list_name>
			<display_name>Humor</display_name>
			<list_name_encoded>humor</list_name_encoded>
			<oldest_published_date>2014-09-07</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Indigenous Americans</list_name>
			<display_name>Indigenous Americans</display_name>
			<list_name_encoded>indigenous-americans</list_name_encoded>
			<oldest_published_date>2014-12-14</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Paperback Business Books</list_name>
			<display_name>Paperback Business Books</display_name>
			<list_name_encoded>paperback-business-books</list_name_encoded>
			<oldest_published_date>2011-07-03</oldest_published_date>
			<newest_published_date>2013-10-13</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Hardcover Political Books</list_name>
			<display_name>Politics</display_name>
			<list_name_encoded>hardcover-political-books</list_name_encoded>
			<oldest_published_date>2011-07-03</oldest_published_date>
			<newest_published_date>2015-01-11</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Race and Civil Rights</list_name>
			<display_name>Race and Civil Rights</display_name>
			<list_name_encoded>race-and-civil-rights</list_name_encoded>
			<oldest_published_date>2014-12-14</oldest_published_date>
			<newest_published_date>2015-01-11</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Relationships</list_name>
			<display_name>Relationships</display_name>
			<list_name_encoded>relationships</list_name_encoded>
			<oldest_published_date>2014-09-07</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Religion Spirituality and Faith</list_name>
			<display_name>Religion, Spirituality and Faith</display_name>
			<list_name_encoded>religion-spirituality-and-faith</list_name_encoded>
			<oldest_published_date>2014-09-07</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Science</list_name>
			<display_name>Science</display_name>
			<list_name_encoded>science</list_name_encoded>
			<oldest_published_date>2013-04-14</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Sports</list_name>
			<display_name>Sports</display_name>
			<list_name_encoded>sports</list_name_encoded>
			<oldest_published_date>2014-03-02</oldest_published_date>
			<newest_published_date>2015-01-11</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
		<result>
			<list_name>Travel</list_name>
			<display_name>Travel</display_name>
			<list_name_encoded>travel</list_name_encoded>
			<oldest_published_date>2014-09-07</oldest_published_date>
			<newest_published_date>2015-02-15</newest_published_date>
			<updated>MONTHLY</updated>
		</result>
	</results>
</result_set>


Step 2. Parsing the responses

In this section, we practice some of the basic Python tools that we learned in class and the powerful string handling methods that Python offers. Our goal is to be able to pick the interesting parts of the response and transform them in a format that will be useful to us.

Our first task will be to isolate the names of all the best-seller lists of the NYT. Fill in the rest of the print_names_from_XML() function that reads the XML response and prints all these names. (5 pts)

Hint: Our pretty formatter puts each tag on a separate line. You may want to read the documentation of the split(), strip() and startswith() functions.


In [15]:
def print_names_from_XML(response):
    """Prints the names of all the best-seller lists that are in the response.
    
    Parameters:
        response: Response object
        The response object that is a result of a get request for the names of the
        best-selling lists from the Books API. 
    
    """   
    xml_parser = xml.dom.minidom.parseString(response.text)
    pretty_response = xml_parser.toprettyxml()
    
    # Fill-in the code that prints the list names

In [16]:
response = requests.get("http://api.nytimes.com/svc/books/v3/lists/names.xml?api-key=%s"%(key))
print_names_from_XML(response)


Combined Print and E-Book Fiction
Combined Print and E-Book Nonfiction
Hardcover Fiction
Hardcover Nonfiction
Trade Fiction Paperback
Mass Market Paperback
Paperback Nonfiction
E-Book Fiction
E-Book Nonfiction
Hardcover Advice
Paperback Advice
Advice How-To and Miscellaneous
Picture Books
Chapter Books
Childrens Middle Grade
Young Adult
Paperback Books
Series Books
Hardcover Graphic Books
Paperback Graphic Books
Manga
Combined Print Fiction
Combined Print Nonfiction
Animals
Business Books
Celebrities
Crime and Punishment
Culture
Education
Espionage
Expeditions Disasters and Adventures
Family
Fashion Manners and Customs
Food and Fitness
Games and Activities
Hardcover Business Books
Health
Humor
Indigenous Americans
Paperback Business Books
Hardcover Political Books
Race and Civil Rights
Relationships
Religion Spirituality and Faith
Science
Sports
Travel

Can you do the same thing for the JSON response? Notice that a JSON object is basically a dictionary. (5 pts)


In [17]:
def print_names_from_JSON(response):
    """Prints the names of all the best-seller lists that are in the response.
    
    Parameters:
        response: Response object
        The response object that is a result of a get request for the names of the
        best-selling lists from the Books API. 
    
    """     
    # Fill-in the code that prints the list names

In [18]:
response = requests.get("http://api.nytimes.com/svc/books/v3/lists/names.json?api-key=%s"%(key))
print_names_from_JSON(response)


Combined Print and E-Book Fiction
Combined Print and E-Book Nonfiction
Hardcover Fiction
Hardcover Nonfiction
Trade Fiction Paperback
Mass Market Paperback
Paperback Nonfiction
E-Book Fiction
E-Book Nonfiction
Hardcover Advice
Paperback Advice
Advice How-To and Miscellaneous
Picture Books
Chapter Books
Childrens Middle Grade
Young Adult
Paperback Books
Series Books
Hardcover Graphic Books
Paperback Graphic Books
Manga
Combined Print Fiction
Combined Print Nonfiction
Animals
Business Books
Celebrities
Crime and Punishment
Culture
Education
Espionage
Expeditions Disasters and Adventures
Family
Fashion Manners and Customs
Food and Fitness
Games and Activities
Hardcover Business Books
Health
Humor
Indigenous Americans
Paperback Business Books
Hardcover Political Books
Race and Civil Rights
Relationships
Religion Spirituality and Faith
Science
Sports
Travel

Let's try something more complicated. Pick your favorite list. Your task is to print the titles of the books that were best-sellers for the list you picked, on the week of July 1st, 2014. (20 pts)

Notice: If you read the API documentation carefully, you will see that

the service returns 20 results at a time. Use the offset parameter to page through the results.

The total number of books that you should be expecting is returned as num_results. It is easier to handle the response if you are working with JSON, so prefer it over the XML.


In [13]:
# Write your code here


Number of books: 25
List date: 2014-06-21

TOP SECRET TWENTY-ONE
THE SILKWORM
WRITTEN IN MY OWN HEART'S BLOOD
MR. MERCEDES
ALL FALL DOWN
THE GOLDFINCH
ROGUES
THE ONE AND ONLY
THE HURRICANE SISTERS
THE MATCHMAKER
ALL THE LIGHT WE CANNOT SEE
THE TARGET
SKIN GAME
THE VACATIONERS
UNLUCKY 13
TERMINAL CITY
SHATTERED
MIDNIGHT IN EUROPE
GHOST SHIP
CHINA DOLLS
THE INVENTION OF WINGS
THE HUSBAND'S SECRET
NANTUCKET SISTERS
NATCHEZ BURNING
FIELD OF PREY

Perfect! By now you should know how to navigate the responses of the API.

Step 3. Putting it all together

We are now ready to tackle our original problem; to compile a summary for the best-sellers over a period of 2 months.

First, we need to become confident working with dates. Since we want to issue requests that span a period of 2 months, we need to be able to automatically advance a day, without needing to keep the logistics of how many days each month has. To this end, we will use the datetime library. Here is an example


In [19]:
import datetime

now = datetime.datetime.now()
print "Now:", now
print "Now (only date):", now.date()
print "Tomorrow:", now + datetime.timedelta(days=1)
print "Now (formatted):", now.strftime("%d:%m:%Y")

new_year = "01-01-2015"
new_year_date = datetime.datetime.strptime(new_year, "%m-%d-%Y")
print "Parsed", new_year_date.date()


Now: 2015-02-05 23:40:40.783000
Now (only date): 2015-02-05
Tomorrow: 2015-02-06 23:40:40.783000
Now (formatted): 05:02:2015
Parsed 2015-01-01

For a better look at the documentation, you can check here and here.

The basic component of our project will be a function that takes as input a date and a list name, executes as many requests to the Books API as needed to get the list of books for that day and returns the list together with the date of its publication.

To return more than one elements from a function (a tuple of elements) we write

def foo():
    return "foo", 42

and then

r = foo()
print r[0] # "foo"
print r[1] # 42

or

txt, num = foo()
print txt # "foo"
print num # 42

Write a function that, given a list name and a date, returns a tuple with the books that were best-sellers for that date and the date on which the list was published by the NYT. (40 pts)


In [20]:
import datetime
import time

def get_books(date, list_name):
    """Returns a tuple containing the list of books and the publication date of the list
    
    Parameters:
        date: datetime
            The day for which  we want to check the best-selling list.
    
        list_name: string
            The name of best-selling list that want to check. This needs to follow
            the Books API guidelines, e.g. 'hardcore-fiction'.
    
    Returns:
        books_set: set
            The set of books that were best-sellers according to NYT.
        
        published_date: datetime
            The date on which the list was published.
            
    """

Notice that the free API key that we have has a limit of 8 QPS (queries per second). If we send multiple queries and pass this limit, we will get back an error instead of the answer. To avoid this situation, a naive way is, after each query, to wait $1/8=0.125$ seconds. The command for this is

time.sleep(0.125)

Let's now test our function:


In [21]:
date = datetime.date(2014,7,1)
list_name = "hardcover-fiction"
book_list, book_date = get_books(date, list_name)

print book_list
print
print "Published on", book_date


set([u'SHATTERED', u'THE INVENTION OF WINGS', u'MR. MERCEDES', u'FIELD OF PREY', u'THE SILKWORM', u'THE VACATIONERS', u'MIDNIGHT IN EUROPE', u'THE GOLDFINCH', u'ROGUES', u'TOP SECRET TWENTY-ONE', u'THE HURRICANE SISTERS', u'ALL FALL DOWN', u'TERMINAL CITY', u'THE ONE AND ONLY', u'CHINA DOLLS', u"WRITTEN IN MY OWN HEART'S BLOOD", u"THE HUSBAND'S SECRET", u'UNLUCKY 13', u'GHOST SHIP', u'SKIN GAME', u'THE MATCHMAKER', u'NANTUCKET SISTERS', u'NATCHEZ BURNING', u'THE TARGET', u'ALL THE LIGHT WE CANNOT SEE'])

Published on 2014-07-06 00:00:00

Great! The final step is to write a function that takes a time window and a list name, and returns a dictionary with the books that were best-sellers as keys and the number of weeks that they were in the list as values. (30 pts)


In [22]:
import datetime

def most_popular(start_date, end_date, list_name):
    """Returns the books and the number of weeks that were best-sellers for the given time window
    
    Parameters:
        start_date: datetime
            The first day to check.
        
        end_date: datetime
            The last day to check.
            
        list_name: string
            The name of best-selling list that want to check. This needs to follow
            the Books API guidelines, e.g. 'hardcore-fiction'.
    
    Returns:
        books_dict: dictionary
            Dictionary of book titles with the number of weeks on the requested NYT
    """

Again, let's test our function. It might take a while to run (because of the QPS limit).


In [23]:
start_date = datetime.date(2014,6,1)
end_date = datetime.date(2014,8,31)
list_name = "hardcover-fiction"

books_dict = most_popular(start_date, end_date, list_name)
for book in books_dict:
    print book, ":", books_dict[book]


SHATTERED : 1
RESISTANT : 1
CLOSE YOUR EYES, HOLD HANDS : 2
DAYS OF RAGE : 1
ACT OF WAR : 6
ONE PLUS ONE : 4
CUT AND THRUST : 3
COP TOWN : 3
BIG LITTLE LIES : 3
PAW AND ORDER : 1
THE HURRICANE SISTERS : 7
TERMINAL CITY : 2
THE ONE AND ONLY : 8
CHESTNUT STREET : 3
LOVE LETTERS : 1
DELICIOUS! : 3
THE 6TH EXTINCTION : 1
WILLIAM SHAKESPEARE'S THE JEDI DOTH RETURN : 1
THE SNOW QUEEN : 1
MAGIC BREAKS : 1
THE BEEKEEPER'S BALL : 1
NATCHEZ BURNING : 7
LANDLINE : 1
THE DIRECTOR : 1
DARK SKYE : 1
THE FORTUNE HUNTER : 1
THE INVENTION OF WINGS : 14
THE KILL SWITCH : 3
WAYFARING STRANGER : 4
THE SON : 3
THE COLLECTOR : 2
THE SILKWORM : 9
ROBERT LUDLUM'S THE BOURNE ASCENDANCY : 1
SIGHT UNSEEN : 1
ROGUES : 1
INVISIBLE : 8
MY STRUGGLE: BOOK THREE : 1
NINE LIVES TO DIE : 1
A PERFECT LIFE : 4
THE SKIN COLLECTOR : 3
AN UNWILLING ACCOMPLICE : 1
CHINA DOLLS : 4
TOP SECRET : 2
THE KRAKEN PROJECT : 2
BITTERSWEET : 3
THE LINCOLN MYTH : 4
THE HEIST : 5
ROBERT B. PARKER'S CHEAP SHOT : 1
MIDNIGHT CROSSROAD : 1
THE GIRLS OF AUGUST : 4
FOOL'S ASSASSIN : 1
THE BOOK OF LIFE : 5
FIELD OF PREY : 6
SEVERED SOULS : 2
BORN OF FURY : 1
VERTIGO 42 : 1
REMAINS OF INNOCENCE : 3
THE HIGH DRUID'S BLADE : 1
A SHIVER OF LIGHT : 2
MIDNIGHT IN EUROPE : 5
THE GOLDFINCH : 14
EARTH AWAKENS : 1
THE LAST KIND WORDS SALOON : 5
A LONG TIME GONE : 1
TOP SECRET TWENTY-ONE : 9
THE CITY : 4
UNLUCKY 13 : 7
ANY OTHER NAME : 3
I AM PILGRIM : 1
SUSPICION : 1
THE HUSBAND'S SECRET : 14
GHOST SHIP : 4
FAST TRACK : 2
SKIN GAME : 6
THE MATCHMAKER : 5
NANTUCKET SISTERS : 1
THE TARGET : 8
THE CARE AND MANAGEMENT OF LIES : 1
SUMMER HOUSE WITH SWIMMING POOL : 1
MR. MERCEDES : 11
WALKING ON WATER : 3
SIXTH GRAVE ON THE EDGE : 1
THE LOST ISLAND : 2
CALIFORNIA : 3
I'VE GOT YOU UNDER MY SKIN : 2
FOR ALL TIME : 1
THE VACATIONERS : 10
THE SMOKE AT DAWN : 3
ALL THE LIGHT WE CANNOT SEE : 14
COLORLESS TSUKURU TAZAKI AND HIS YEARS OF PILGRIMAGE : 1
ALL FALL DOWN : 6
POWER PLAY : 3
LUCKY US : 3
TOM CLANCY: SUPPORT AND DEFEND : 4
SAVE THE DATE : 2
WRITTEN IN MY OWN HEART'S BLOOD : 10
THE STORIED LIFE OF A. J. FIKRY : 1
SHOTS FIRED : 2
THE PRODIGAL SON : 1
THE MAGICIAN'S LAND : 2
SNIPER'S HONOR : 2
THE DEAD WILL TELL : 1

In [1]:
# Code for setting the style of the notebook
from IPython.core.display import HTML
def css_styling():
    styles = open("../../theme/custom.css", "r").read()
    return HTML(styles)
css_styling()


Out[1]: