The New York Times API in Django

Renan
2 min readNov 7, 2021

--

Manipulating the NYT developer API

The New York Times developer API

To consolidate my knowledge about APIs, I created a web-app to manipulate requests and responses and fill in the content of a website. After some research, I decided to use The New York Times developer API.

You can follow this project at nytx.herokupapp.com. Check the repository.

Making the Actual API Queries

When the Home Page is loaded, an API call requests the List Overview, which will bring the Top 5 Best Sellers books for a number of different categories. (*get your free API Key for The New York Times here)

The basic structure is: logo, navigation menu, page title and the contents.

nytx.herokuapp.com

To make the API queries, I’m using the Python requests library. The requests.get() function will be a string value. To deserialize it, use req.json().

import requestsdef GetLatestOverview():
url = 'https://api.nytimes.com/svc/books/v3/lists/overview.json?api-key=*MyApiKey'
req = requests.get(url)
reply = req.json()
return reply

If no dates are specified, this query will return the latest published list for many categories, such as “Fiction” and “Nonfiction”. The API engine reply has the following structure:

{"query-info":"...",
"results":{
"publication-info":"...",
"lists":[{
"list-name":"list1",
"books":[{
"book-info":"book1",
"rank":1,
"title":"TITLE1"
},{
"book-info":"book2",
"rank":2,
"title":"TITLE2"
},{...
}]
},{
"list-name":"list2",
"books":[{
"book-info":"book1",
"rank":1,
"title":"TITLE1"
},{
"book-info":"book2",
"rank":2,
"title":"TITLE2"
},{...
}]
},{...
}]
}

This JSON value is passed to the Django View, and finally sent over to the Django Template to get rendered in html:

#views.py
def BooksOverview(request):
template_name = 'books/books_overview.html'
context = {}
context['latest_overview'] = GetLatestOverview()
return render(request, template_name, context)
#books_overview.html
{% for item in latest_overview.results.lists %}
<div>
<div class="category-title">
{{item.list-name}}
</div>
<div class="books-list">
{% for book in item.books %}
<div class="each-book">
# {{book.rank}} -
{{book.title|title}}
</div>
{% endfor %}
</div>
</div>
{% endfor %}

Because the web-app isn’t responsive yet, only the first two books are displayed under each category, instead of five.

If you visit the site (here), click a category name and another API call will get the complete list of Best Seller Books for that specific category — usually 15 books.

Technology and services involved in this project so far:

  • Coded in Django Framework / Python
  • Hosted in GitHub
  • Deployed to Heroku with gunicorn
  • API calls through the requests library
  • API responses interpreted as JSON
  • Styling with CSS

--

--

Renan

I write to organize thoughts and ideas in a rational way about technology, health, lifestyle and productivity.