API to list top level domains
Looks like ICANN does provide a computer-readable list of all valid TLDs:
https://data.iana.org/TLD/tlds-alpha-by-domain.txt (found via this page)
I'm not sure how frequently it's updated, but the couple times I've checked it's not been older than 24 hours.
I don't know how often you can query it without bothering them, so I wouldn't do it too often. It's not like the list changes frequently.
You can get this information directly from IANA. The data is here http://www.iana.org/domains/root/db and the HTML looks fairly easy to scrape.