Parsing pagination links with Postman

Under Tests, I’m trying to parse the header response pagination link header for the “next” link. (So that I can set it as a variable that I’ll use to set the next URL request.) But I’m stuck on parsing it. The API I’m interacting with doesn’t return it in JSON. I can get as far as returning the entire link header contents:

pm.response.headers.get(“link”)
console.log(link)

That gets me this block of text:
<https://example.com/stuff?limit=5&offset=0&filter=status%3D%27active%27>;rel="prev",<https://example.com/stuff?limit=5&offset=5&filter=status%3D%27active%27>;rel="next",<https://example.com/stuff?limit=5&offset=0&filter=status%3D%27active%27>;rel="first",<https://example.com/stuff?limit=5&offset=10&filter=status%3D%27active%27>;rel="last"

I want to parse so that I end up only with the “next” link:
https://example.com/stuff?limit=5&offset=5&filter=status%3D’active’

Thanks for your thoughts!

Can you post the actual body of the response? To see what is being returned if its not JSON. (Text maybe).

Is the pagination information anywhere in the response (or is it just contained in the header).

Oh, sure. To clarify, the response itself is JSON, but does not contain the pagination information. The pagination information is contained only in the header, and always in the format of the example given here.

The following approach seems to work.

Split the response into an array, using “,” as the seperator.

Then use the JavaScript find function to link the array element that includes “next”.

var link = "<https://example.com/stuff?limit=5&offset=0&filter=status%3D%27active%27>;rel=\"prev\",<https://example.com/stuff?limit=5&offset=5&filter=status%3D%27active%27>;rel=\"next\",<https://example.com/stuff?limit=5&offset=0&filter=status%3D%27active%27>;rel=\"first\",<https://example.com/stuff?limit=5&offset=10&filter=status%3D%27active%27>;rel=\"last\""

var array = link.split(',');
const search = array.find(array => array.includes("next"));
console.log(search); // "<https://example.com/stuff?limit=5&offset=5&filter=status%3D%27active%27>;rel="next""

image

Excellent, thank you!

To take it one step further, what’s the best way to strip the leading < and trailing >;rel="next" out for a final result of https://example.com/stuff?limit=5&offset=5&filter=status%3D%27active%27

Use the JavaScript replace function (twice).

console.log(search.replace('<', '').replace('>;rel="next"',''));

That does the trick! Thank you!