Query Rest API with kdb+

My first post is going to be a light one. Today, I would like to share with you a useful tip. In my case, I have always struggled with kdb+ to use any Rest API, until I got this code working.

httpGet:{[cmd] (`$":http://hostname:port")"GET ",cmd," HTTP/1.0\r\nHost:hostname\r\n\r\n"};
res:httpGet[ "/entry/point" ];

In this code, we are setting a handle to the API host with a GET method. Note that POST would work too. The text following the handle is the header of the query. This function is an alternative version of curl where one can query any URI he would like.

In the following example, I am using the entry point of Prometheus for getting a health report of my services. The payload from this request is a json message. Therefore, I use the library .j.k to convert it into q language. The last two lines format the data into a readable table (not keyed).

httpGet:{[cmd] (`$":http://prometheus.loicbelec.com:9090")"GET ",cmd," HTTP/1.0\r\nHost:prometheus.loicbelec.com\r\n\r\n"};
res:httpGet[ "/api/v1/targets" ];
split:"\r\n" vs res;
parsed:.j.k last split;
labels:parsed[`data][`activeTargets]`labels;
status:([] health:parsed[`data][`activeTargets]`health);
labels,'status

I hope this code would help some people getting external data into their kdb+ code.

Leave a Reply

Your email address will not be published. Required fields are marked *