How to handle `Link` header with Ballerina http client?

69 Views Asked by At

Some APIs return the next page information (in pagination) as the Link header. Is there a way in Ballerina to parse the Link header and refer the different links?

An example set of Link headers are below:

Link: <https://[hostname]/config/v2/menus?pageSize=1>; rel="first"1
Link: <https://[hostname]/config/v2/menus?pageSize=1&page=5>; rel="self"2
Link: <https://[hostname]/config/v2/menus?pageSize=1&page=4>; rel="prev"3
Link: <https://[hostname]/config/v2/menus?pageSize=1&page=6>; rel="next"4
Link: <https://[hostname]/config/v2/menus?pageSize=1&page=10>; rel="last"

PS: Ballerina already supports links in the body (HATEOAS)

1

There are 1 best solutions below

0
Tharmigan Krishnananthalingam On

In Ballerina, the Link header is treated similarly to any other HTTP headers since how you want to handle the Link header depends on your application's specific requirements. Therefore, you can use the http:parseHeader() function to parse the Link header.

Here's an example:

public function main() returns error? {
    http:Response res = new;
    res.addHeader("Link", "<https://[hostname]/v2/menus?pageSize=1>; rel=\"first\"");

    string linkHeader = check res.getHeader("Link");
    var parsedLinkHeader = check http:parseHeader(linkHeader);
    // [
    //     {
    //         "value": "<https://[hostname]/v2/menus?pageSize=1>",
    //         "params": {
    //             "rel": "first"
    //         }
    //     }
    // ]
}

In the above example, the resulting parsed link header is an array of header values, each of which has a value field and a params field. The value field contains the actual link URL, and the params field contains any other parameters specified in the Link header.