Five scripts that put the tinykoi API to work
· Developers · 5 min read
You can automate bookmarks with the tinykoi API using a handful of short scripts and an API key. This post gives you five: save from an RSS feed, build a weekly digest, merge duplicate tags, back up your library, and save from the command line. Every route used here is in the public API, and the limits come straight from the plans.
If you have not made a key yet, the REST API quick start takes ten minutes. The scripts below use Python's standard library, so there is nothing to install apart from jq for the shell one.
A shared helper
Every script calls the same small function. It sends the bearer token, parses JSON, and waits when it hits a rate limit.
# tinykoi.py
import json, os, time, urllib.error, urllib.parse, urllib.request
BASE = "https://tinykoi.com/api/v1"
KEY = os.environ["TINYKOI_KEY"]
def call(method, path, params=None, body=None):
url = BASE + path + ("?" + urllib.parse.urlencode(params) if params else "")
data = json.dumps(body).encode() if body is not None else None
headers = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}
while True:
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req) as res:
return json.load(res)
except urllib.error.HTTPError as err:
if err.code != 429:
raise
detail = json.load(err).get("data") or {}
wait = err.headers.get("retry-after") or detail.get("retryAfterSeconds") or 10
time.sleep(int(wait))
A 429 carries a retry-after header, and the hourly saves limit puts retryAfterSeconds in the body, so the loop sleeps for whichever it finds and tries again. Requests are counted per account across all keys: 20 a minute on Free and 120 on Pro. Keep that in mind when you size a loop. See pricing for the plan limits.
1. Save from a feed
Say you follow a few blogs and want every new post saved to a collection. This reads an RSS 2.0 feed and posts each link.
import sys, time, urllib.request
import xml.etree.ElementTree as ET
from tinykoi import call
feed = urllib.request.urlopen(sys.argv[1]).read()
for item in ET.fromstring(feed).iter("item"):
link = item.findtext("link")
if not link:
continue
out = call("POST", "/bookmarks", body={"url": link, "tags": ["feed"]})
print("saved" if out["created"] else "already had", link)
time.sleep(3.1)
POST /bookmarks returns created: false and the existing bookmark when you already saved that page, so running this on a schedule never makes duplicates. The sleep keeps you under the Free limit of 20 requests a minute. On Pro you can drop it to a second.
New saves also count against the saves-an-hour limit: 120 on Free, 600 on Pro. Past that, the API returns 429 with RATE_LIMITED and data.retryAfterSeconds. The helper waits it out, which can mean a long sleep, so for a big first run you may prefer to stop and finish tomorrow.
2. A weekly digest
Print everything saved in the last seven days as Markdown, ready to paste into a newsletter or a notes app.
from datetime import datetime, timedelta, timezone
from tinykoi import call
cutoff = datetime.now(timezone.utc) - timedelta(days=7)
cursor = None
while True:
params = {"scope": "all", "sort": "created_desc", "limit": 100}
if cursor:
params["cursor"] = cursor
page = call("GET", "/bookmarks", params)
for b in page["items"]:
if datetime.fromisoformat(b["createdAt"].replace("Z", "+00:00")) < cutoff:
raise SystemExit
print(f"- [{b['title']}]({b['url']}) {' '.join('#' + t for t in b['tags'])}")
cursor = page["nextCursor"]
if not cursor:
break
Sorted newest first, the loop stops at the first bookmark older than the cutoff. Add a cron entry for Monday morning and mail the output to yourself.
3. Tidy duplicate tags
Tags drift: design, Design, designs. GET /tags returns each tag's id, name and count, and POST /tags/{to}/merge folds a list of tags into one.
from collections import defaultdict
from tinykoi import call
groups = defaultdict(list)
for tag in call("GET", "/tags"):
groups[tag["name"].lower().rstrip("s")].append(tag)
for tags in groups.values():
if len(tags) < 2:
continue
keep = max(tags, key=lambda t: t["count"])
rest = [t["id"] for t in tags if t["id"] != keep["id"]]
print("merging into", keep["name"], [t["name"] for t in tags])
call("POST", f"/tags/{keep['id']}/merge", body={"from": rest})
The tag with the most bookmarks wins. Run it once with the call line commented out first and read what it would merge. The crude plural rule will join bus with bu, so check the output. A merge accepts up to 50 tags in from.
4. Back up your library
Settings already exports HTML, CSV and a Markdown file of highlights. An API backup adds something different: a JSON file with notes, tags, collection ids and capture status, written wherever you like.
import json, datetime
from tinykoi import call
items, cursor = [], None
while True:
params = {"scope": "all", "limit": 100}
if cursor:
params["cursor"] = cursor
page = call("GET", "/bookmarks", params)
items += page["items"]
cursor = page["nextCursor"]
if not cursor:
break
name = f"tinykoi-{datetime.date.today()}.json"
json.dump({"bookmarks": items, "collections": call("GET", "/collections")}, open(name, "w"))
print(len(items), "bookmarks ->", name)
A library of 2,000 bookmarks is 21 requests with the collections call, so on Free (20 a minute) the helper may pause once for the limit to reset. On Pro, GET /bookmarks/{bookmarkId}/archive returns a signed url and downloadUrl for the archived copy, valid for a short time (the response includes expiresAt). On Free it answers 402 with PLAN_REQUIRED. You can loop over bookmarks whose archiveStatus is ok and download each file.
5. Save from the shell
For the command line, a short function in your shell profile is enough. It needs jq.
tk() {
local url="$1"; shift
jq -n --arg url "$url" '{url: $url, tags: $ARGS.positional}' --args "$@" |
curl -s -X POST "https://tinykoi.com/api/v1/bookmarks" \
-H "Authorization: Bearer $TINYKOI_KEY" \
-H "Content-Type: application/json" \
-d @- | jq -r '.bookmark.title'
}
Run tk https://example.com/post reading postgres and the page is saved with two tags. The title it prints may be the domain at first, because the real title is fetched in the background after the save.
Practical notes for automating bookmarks
- Use a read-only key for the digest and backup scripts. A read key can call every
GETroute, so it cannot change anything. - Use a separate named key per script if you can, so you can delete one without breaking the rest. Free holds 1 key and Pro holds 10.
- Keep keys out of source control. They start with
tinykoi_, which makes them easy to scan for. - Uploads, imports, billing and key management are not in the API.
Next
The full list of routes is in the API reference. Sign up free to get a key, no card needed.
tinykoi