Tidying up code and abstracting out API callback function