API to purge file cache from Spaces CDN after file update

April 10, 2019 1.3k views
Caching CDN

I can’t find a non-manual way to purge the cache of a file in the CDN after I update it in Spaces. I feel like this is a common task but I can’t find any documentation on it besides the one telling you how to do it manually through DO’s website.

How can we purge the cache of a file after an update through an API?

FYI I’m updating files through the aws-sdk S3 API.

3 Answers
asb MOD April 10, 2019
Accepted Answer

Clarifying @jarland’s answer a bit: The Spaces API itself does not have support for purging the CDN’s cache, but the DigitalOcean platform API does. The Spaces API was designed to emulate the AWS S3 API so that developers could use it as a drop-in replacement for S3 existing projects. Spaces-specific functionality like the builtin CDN are not part of the S3 API but are support in the DigitalOcean API.

First you’ll need to find the ID of you CDN endpoint. You can do that by listing your CDN endpoints using:

curl -X GET -H "Content-Type: application/json" \
    -H "Authorization: Bearer $API_TOKEN" \
    "https://api.digitalocean.com/v2/cdn/endpoints" 

Then you can purge the cache with:

curl -X DELETE -H "Content-Type: application/json" \
    -H "Authorization: Bearer $API_TOKEN" \
    -d '{"files": ["*"]}' \
    "https://api.digitalocean.com/v2/cdn/endpoints/<CDN_ENDPOINT_ID>/cache" 

That command would purge the entire cache, but you could list specific files as well.

The DigitalOcean CLI, doctl, supports these as well:

To list the CDN endpoints run:

doctl compute cdn ls

And to purge the cache, run:

doctl compute cdn flush <CDN_ENDPOINT_ID> --files [*]

Find the full API reference docs here: https://developers.digitalocean.com/documentation/v2/#cdn-endpoints

Greetings!

Great question. To purge the cache you would need to go through the control panel, but this is probably not the ideal method for automation. Instead, you should focus on the TTL. This document will give you a bit more insight into that:

https://www.digitalocean.com/docs/spaces/how-to/manage-cdn-cache

You can set the TTL for the whole space or individual files (whole space being a bit easier). Once TTL is reached, the CDN should refresh it’s cache.

Jarland

  • Thanks Jarland. I have my TTL set appropriately, but I still want to purge cache of a single file after it’s updated without going into the control panel. So I take it there’s currently no API to do that?

    • No API for that I’m afraid. I would encourage re-thinking the logic behind doing it that way. Constantly refreshing cache sort of defeats the logic of caching.

      • The file’s cache wouldn’t constantly refresh; it would only be refreshed when the file is updated, which isn’t often. The issue is I require the updated file to be seen immediately while leaving all other files still cached.

Me too … looking for a similar solution!

Thanks

Have another answer? Share your knowledge.