Fix duplicated code in API controllers