Skip to content

Instantly share code, notes, and snippets.

@PiotrKrzyzek
Created June 1, 2022 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PiotrKrzyzek/fdc8a8001f49605a01460700b4f5c0fd to your computer and use it in GitHub Desktop.
Save PiotrKrzyzek/fdc8a8001f49605a01460700b4f5c0fd to your computer and use it in GitHub Desktop.
Ghost CRM: Delete all empty tags (via admin api) Python script
import requests # pip install requests
import jwt # pip install pyjwt
from datetime import datetime as date
# Admin API key goes here
key = 'Full Ghost Admin Key Here'
domain = 'https://your-ghost-domain-here.com/'
# Split the key into ID and SECRET
id, secret = key.split(':')
# Prepare header and payload
iat = int(date.now().timestamp())
header = {'alg': 'HS256', 'typ': 'JWT', 'kid': id}
payload = {
'iat': iat,
'exp': iat + 5 * 60,
'aud': '/admin/'
}
# Create the token (including decoding secret)
token = jwt.encode(payload, bytes.fromhex(secret), algorithm='HS256', headers=header)
# Make an authenticated request to create a post
# Here we're calling the admin API tags route and specifying we want the count of posts for each tag
url = domain + '/ghost/api/admin/tags/?include=count.posts'
headers = {'Authorization': 'Ghost {}'.format(token)}
r = requests.get(url, headers=headers)
# Save the initial data and some meta data we need for looping
tags_json = r.json()
current_page = int(tags_json['meta']['pagination']['page'])
total_pages = int(tags_json['meta']['pagination']['pages'])
# This is our tag ID holder
tags = []
# Now let's start the main loop
while current_page <= total_pages:
# Ghost starts the page count at '1', so we're starting here as well!
url = domain + '/ghost/api/admin/tags/?include=count.posts&page=' + str(current_page)
r = requests.get(url, headers=headers)
tags_json = r.json()
# We increment the page count here so that we don't forget about it later
current_page = current_page + 1
# In this inner loop, we loop though the paginated items returned and save only the EMPTY tags
for item in tags_json['tags']:
if int(item['count']['posts']) == 0: # post count of zero means this tag is empty
tags.append(item['id'])
# Now that the main loop is done, delete those old tags!
for item in tags:
url = domain + '/ghost/api/admin/tags/' + item
r = requests.delete(url, headers=headers)
# Fancy ending message
print('done')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment