Extract and unify duplicated code in the api.ts files

Uncategorized