Check a reference URL before an image edit: HTTPS, HEAD, content type

Sume rejects non-public or non-HTTPS reference URLs with a 400. A 15-line Python preflight checks scheme, HEAD status and image content type before you spend.

5 min readSume
All posts

Check three things before you attach a URL as input_references on Sume: it is https, a HEAD request returns 200, and the content type starts with image/. Sume requires public HTTPS reference URLs and rejects private-network or non-HTTPS ones with a 400, as the Image API docs describe. A preflight in your own code finds a dead link before you submit, and a failed request is not billed anyway.

It is a cheap guard for batches, where one stale URL in a list of 16 would otherwise fail the whole call.

What does the preflight look like?

It uses requests and returns only the URLs that pass.

import requests
from urllib.parse import urlparse

def usable(urls):
    ok = []
    for u in urls:
        if urlparse(u).scheme != "https":
            continue
        try:
            r = requests.head(u, allow_redirects=True, timeout=10)
        except requests.RequestException:
            continue
        kind = r.headers.get("content-type", "")
        if r.status_code == 200 and kind.startswith("image/"):
            ok.append(u)
    return ok

refs = usable(["https://example.com/packshot.png"])
print(len(refs), "usable")

What does this not catch?

Some hosts reject HEAD or need signed URLs that expire before Sume fetches them. Use a URL that stays valid for a few minutes. If a reference still fails, the 400 names the cause.

Sources

Related posts

More in Developers

All Developers posts

Written by Sume