Larry Hudson

Writing about making websites


Adding a music page to Eleventy using the Last.fm API

31 March 2021

Combining a static site generator like Eleventy with data from APIs is a really powerful combination. By pulling in data from different sources and then building static HTML files, you can add lots of information to your site without compromising the website’s performance.

I’ve just used the Last.fm API to create a new page on my website – the ‘Music I like‘ page. This page includes a list of my top albums for the last week.

Here’s how to add a music page to your Eleventy site:

How to add a music page to Eleventy using the Last.fm API

Using the Last.fm API

First you’ll need to sign up for a Last.fm profile, then sign up for an API account. You just need to fill out a description of what your app will do, and give them a URL for your homepage.

Then we need to work out what we need to query. In the API docs, I found the ‘get top albums’ query. Using this, I was able to send a GET request that returned JSON data with my list of albums, complete with images.

I created a JavaScript file in my _utils folder that handles the querying – you can see this file in the GitHub repo.

Showing the data in Eleventy

I created a new ‘musicPage.js’ file in the _data folder – this allows me to use the data globally in my templates. This file calls the utility function I mentioned above.

Then in my Nunjucks page, I create a grid of albums. For each album, I include a link to search for the album with DuckDuckGo.

In the template, I use the {% image %} shortcode provided by the @11ty/image library to download remote images from Last.fm, convert them to modern formats and serve them from my site rather than Last.fm. This means the performance of my site doesn’t rely on Last.fm API.

Other ideas

Another idea I have is to use the Spotify API to pull in data about recent playlists that I’ve created.