Move API layer query code into API