Search code examples
kdb

Is there a way to set headers for GET requests in KDB?


I'm trying to make get requested with .Q.hg (HTTP get), but I need to edit the request headers to provide API keys. How can I do this?


Solution

  • You can try this function I wrote a few years back for a POC (similar reason - I needed to supply multiple headers). It's based on .Q.hmb which underpins .Q.hp/hg. Please note - it was never extensively tested & there are likely better alternatives out there, but it will perhaps work as a quick solution.

    k)req:{[url;method;hd;bd]d:s,s:"\r\n";url:$[10=@url;url;1_$url];p:{$[#y;y;x]}/getenv`$_:\("HTTP";"NO"),\:"_PROXY";u:.Q.hap@url;t:~(~#*p)||/(*":"\:u 2)like/:{(("."=*x)#"*"),x}'","\:p 1;a:$[t;p:.Q.hap@*p;u]1;(4+*r ss d)_r:(`$":",,/($[t;p;u]0 2))($method)," ",$[t;url;u 3]," HTTP/1.1",s,(s/:("Connection: close";"Host: ",u 2),((0<#a)#,$[t;"Proxy-";""],"Authorization: Basic ",.Q.btoa a),($[#hd;(!hd),'": ",/:. hd;()])),($[#bd;(s,"Content-length: ",$#bd),d,bd;d])}
    

    It takes 4 arguments:

    1. Resource URL
    2. HTTP method
    3. Dictionary of headers
    4. Message body as JSON object

    Sending a request to a test server..

    q).j.k req["https://httpbin.org/get";`GET;("Content-Type";"someOtherHeader")!(.h.ty`json;"blah");""] // no body so pass empty string
    args   | (`symbol$())!()
    headers| `Content-Type`Host`Someotherheader`X-Amzn-Trace-Id!("application/jso..
    url    | "https://httpbin.org/get"