Refactored logic out of the API controller