Search code examples
kdb

How to create HTTP GET and POST methods in kdb


What is the best way to set up HTTP GET and POST methods with a kdb database?

I'd like to be able to extract the column names from a kdb table to create a simple form with fillable fields in the browser, allow users to input text into the fields, and then upsert and save that text to my table.

For example if I had the following table...

t:([employeeID:`$()]fName:`$(); mName:`$(); lName:`$())

So far I know how to open a port \p 9999 and then view that table in browser by connecting to the local host http://localhost:9999 and I know how to get only the column names:cols t.

Though I'm unsure how to build a useful REST API from this table that achieves the above objective, mainly updating the table with the inputted data. I'm aware of .Q.hg and .Q.hp from this blog post and the Kx reference. But there is little information and I'm still unsure how to get it to work for my particular purpose.


Solution

  • Depending upon your front-end(client) technology, you can either use HTTP request or WebSockets. Using HTTP request will require extra work to customize the output of the request as by default it returns HTML data.

    If your client supports Websockets like Javascript then it would be easy to use it.

    Basically, you need to do 2 things to setup WebSockets:

    1) Start your KDB server and setup handler function for WebSocket request. Function for that is .z.ws. For eample simple function would be something like below:

      q) .z.ws:{neg[.z.w].Q.s @[value;x;{`$ "'",x}]}
    

    2) Setup message handler function on the client side, open websocket connection from the client and send a request to KDB server.

    Details: https://code.kx.com/v2/wp/websockets/

    Example: https://code.kx.com/v2/wp/websockets/#a-simpledemohtml