Building My Own "New On Streaming" Movie List

Building My Own "New On Streaming" Movie List

TLDR - If you want programmatic access to what's playing on streaming services, across the world, the Movie of the Night API is an excellent service with an incredibly generous free tier. I used it to build my own personal "what's new" page here. Want the details? Keep reading.

The Problem

Ok, in the grand scheme of things, this is less a problem and more a very minor inconvenience. I love movies, and I especially love finding a random one on the streaming services I subscribe to and giving it a shot. During the week, I'll open up one of the apps, see what's new, close it, open another, and repeat. Every now and then I'll know a movie is out and Google to see where it's streaming, but that usually lands you on a "recipe" page, and by that I mean a page that spends two hundred or so paragraphs talking about the movie and then at the very, very end, it tells you where the movie can be found. And usually it's wrong.

The Solution

Given that - earlier this week I simply googled to see if there was an API for streaming services and was happily surprised to find the Movie of the Night API. Best of all, their free tier gives you a thousand requests per month which is way more than I need.

Their API covers 50 different streaming services across 65 different countries. At a high level, you can:

  • Search and get shows (shows being movie or TV series)
  • Get information about what services are available in particular countries
  • And this is the big one - get a list of changes, which includes shows coming on and off streaming services.

For my streaming report page, I wanted to focus on the streaming services I subscribe to and focus on the past seven days. Here's how I built it.

The Serverless Function

Everything is done via a simple Netlify serverless function. As it's only a bit over a hundred lines, I'll share it all below, then break it down:

import { getStore } from "@netlify/blobs";

const CACHE_MAX = 12 * 60 * 60 * 1000;
const CACHE_KEY = "filtered-shows";

/*
catalogs is how we filter to services I care about, _and_ handle filtering to 
free or subscription
*/
const CATALOGS = [
        'netflix.subscription', 'hulu.subscription', 'disney.subscription', 
        'peacock.subscription', 'paramount.subscription',  'prime.subscription', 
        'hbo.subscription', 'apple.subscription'
    ];

const API_URL = "https://api.movieofthenight.com/v4/changes?country=us&change_type=new&item_type=show&show_type=movie&catalogs=" + CATALOGS.join(',');
const MAX_API_CALLS = 5;


export async function fetchStreamingData(apiKey) {
    const url = new URL(API_URL);
    url.searchParams.set("from", String(Math.floor(Date.now() / 1000) - 7 * 24 * 60 * 60));
    const headers = { "x-api-key": apiKey };
    const result = { changes: [], shows: [] };

    for (let call = 0; call < MAX_API_CALLS; call++) {
        const response = await fetch(url, { headers });
        if (!response.ok) {
            throw new Error(`Movie of the Night API returned ${response.status}`);
        }

        const page = await response.json();
        result.changes.push(...page.changes);

        const shows = Array.isArray(page.shows)
            ? page.shows.map(show => ({ ...show, showId: show.showId ?? show.id }))
            : Object.entries(page.shows).map(([showId, show]) => ({ ...show, showId }));
        result.shows.push(...shows);

        if (!page.hasMore || call === MAX_API_CALLS - 1) break;
        if (!page.nextCursor) {
            throw new Error("Movie of the Night API indicated more results without a nextCursor");
        }

        url.searchParams.set("cursor", page.nextCursor);
    }

    return result;
}

export default async (req, context) => {
    const cacheStore = getStore("streaming-movies");
    const refresh = new URL(req.url).searchParams.toString() !== "";

    if (!refresh) {
        const cached = await cacheStore.get(CACHE_KEY, { type: "json" });
        if (cached && Date.now() - new Date(cached.date).getTime() < CACHE_MAX) {
            return Response.json(cached.filteredShows);
        }
    }

    let movieOfTheNightKey = process.env.MOVIEOFTHENIGHTKEY;
    let data = await fetchStreamingData(movieOfTheNightKey);
    let showsById = new Map(data.shows.map(show => [show.showId, show]));

    /*
    do a crap ton of filtering/mapping. i also discovered that changes had duplicate results. not sure why.
    note - i now filter by service, so this may not be needed...
    */
    let seen = new Set()

    let filteredShows = data.changes.filter(change => {
        if (seen.has(change.showId)) return false;
        seen.add(change.showId);
        return true;
    }).map(change => {
        let s = {};
        let show = showsById.get(change.showId);

        s.title = show.title;
        s.overview = show.overview;
        s.images = show.imageSet;

        s.streaming = {
            name: change.service.name,
            link: change.link
        }

        s.timestamp = change.timestamp;
        return s;
        
    });

    await cacheStore.setJSON(CACHE_KEY, { filteredShows, date: new Date() });

    return Response.json(
        filteredShows
    );
};

export const config = {
  path:"/api/streaming-movies"
}

Alright, so the core functionality lives in the default export. I'm using Netlify blobs as a lightweight caching mechanism so I first get access to that. I wanted a hacky way to refresh the cache so I added a simple URL parameter hook for that. If that isn't passed, and the cache exists, and it hasn't expired, I quickly return it. My cache is for 12 hours, which honestly was a bit of a guess. I have no way of knowing this but I assume most services make changes daily, but even if not, 12 hours is a good long but not too long cache. Probably.

The core API I use from Movie of the Night is the Changes API. This has multiple different filters and I'll explain the ones I used in a bit. The result from the API call looks like so:

{
    changes: an array of change objects, with a showId value,
    shows: an array of shows that map to the changes,
    hasMore: true, 
    nextCursor: ....
}

You get 25 results per page so I used a utility function that would repeatedly call this (when more data exists) up to 5 times. My function simply appends changes and shows into the same array so the final result looks like the pseudo-code above but with a lot more data.

For my filters, I start off by defining my services. The API supports filtering by service, and this is the important bit, filtering by the type of subscription needed within the service. Some services have free movies without needing a subscription. Some services, and Amazon Prime is a good example of this, let you buy multiple other add-ons for more content. So by using "service name.type" where type is "subscription", I'm basically filtering to items in the core subscription service of the particular service in question. Given that, you can see I've defined them as an array below:

const CATALOGS = [
        'netflix.subscription', 'hulu.subscription', 'disney.subscription', 
        'peacock.subscription', 'paramount.subscription',  'prime.subscription', 
        'hbo.subscription', 'apple.subscription'
    ];

I then simply create my URL. I'm also filtering by:

  • country
  • movies
  • new items

Here's the bit that builds this up:

const API_URL = "https://api.movieofthenight.com/v4/changes?country=us&change_type=new&item_type=show&show_type=movie&catalogs=" + CATALOGS.join(',');

Once I get all my data, I then need to build a result array. Remember that the changes array isn't the show itself, but rather points to it, and it's possible a show may show up more than once in changes, so I filter to unique shows and then map my data to match what I thought I wanted on the front end. The API returns a lot of information about each result and you can see the full breakdown in their docs.

By the way, that last little config portion simply gives me a nice URL for my front end code. Speaking of that...

The Front End

I kept things incredibly simple on the front end. Get my data. Render my data. So I start with an empty div, and then fill it up. Note that while my back end may return a lot of results, I capped the front end tgo 50.

function formatDate(unixTimestamp) {
    const date = new Date(unixTimestamp * 1000);
    return new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    }).format(date);
}

document.addEventListener('DOMContentLoaded', init, false);

async function init() {
    const $films = document.querySelector('#films');
    let filmsReq = await fetch('/api/streaming-movies');
    let films = (await filmsReq.json()).slice(0,50);
    let filmHTML = '';
    for(let film of films) {
        filmHTML += `
        <div class="film">
        <a href="${film.streaming.link}" target="_blank" rel="noopener"><img src="${film.images.verticalPoster.w240}" alt="Poster for ${film.title}"></a>
        <a href="${film.streaming.link}" target="_blank" rel="noopener">${film.title}</a><br/>
        Streaming via ${film.streaming.name} on ${formatDate(film.timestamp)}.
        </div>
        `;
    }
    $films.innerHTML = filmHTML;
    console.log(films);
}

You can see that result here.

Tomorrow I'm going to build a new service - given that the changes API can show upcoming releases, I'm going to build a simple email newsletter for Sunday that tells me about the shows coming later that week.