Thursday, 3 October 2019

How to get Link Headers (for pagination) from API using PHP cURL

I'm querying an API for a list of results, using PHP and cURL.

In order to enable pagination, the API returns links to the next and previous pages of results, in the header, as HTTP Link Headers. https://www.w3.org/wiki/LinkHeader

When I print_r the object I get back from curl_exec, the links in the header (between angled brackets) are empty. I verify that I should be being returned links, by looking in the Swagger docs. (see example). In the Swagger docs, the links are returned within angle brackets - is there something about the way cURL is getting/returning the headers that means content within angle brackets is lost?

Source code:

$curl = curl_init("https://api.mendeley.com/datasets?limit=3");
curl_setopt($curl, CURLOPT_HEADER, 1); 
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
$rest = curl_exec($curl);
print_r($rest);

Expected output (from Swagger docs):

"link": "<https://api.mendeley.com/datasets?marker=0027ea1f-bec6-4581-a967-9a8c75dfba5f&limit=3&fields=results.id&reverse=false&_=1505585347125&order=asc>; rel=\"next\"",

Actual output:

Link: ; rel="next" 


from How to get Link Headers (for pagination) from API using PHP cURL

No comments:

Post a Comment