REST API url page takes forever to load

I'm using REST API to populate my data to my DHTMLXGantt chart. It took around 1 minute to display. Even when I try to access the API URL it took forever to load, why is this happening? The code is confidential so I can't paste it here, but has several if else and for loop condition in it and i assuming that's one of the reason, Is there anyway i can optimize the loading speed? any help is much appreciated. Does pagination helps to populate the data into smaller chunks? Any help is much appreciated