githubEdit

Fetch JSON

Grabbing JSON from some url is very easy.

strandio includes the +fetch-json function which will handle the HTTP request, response, and parsing, producing JSON.

The following thread fetches the current Bitcoin price from the CoinGecko APIarrow-up-right in the specified currency and prints it to the terminal.

/ted/btc-price.hoon
/+  *strandio
=,  dejs-soft:format
|=  arg=vase
=/  m  (strand:rand ,vase)
^-  form:m
=/  url
  "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies="
=/  cur  !<((unit @tas) arg)
?~  cur  (strand-fail:rand %no-arg ~)
=.  u.cur  (crip (cass (trip u.cur)))
?.  ((sane %tas) u.cur)  (strand-fail:rand %bad-currency-format ~)
;<  =json  bind:m  (fetch-json (weld url (trip u.cur)))
=/  price=(unit @ta)  ((ot ~[bitcoin+(ot [u.cur no]~)]) json)
?~  price  ((slog 'Currency not found.' ~) (pure:m !>(~)))
%-  (slog leaf+"{(trip u.price)} {(cuss (trip u.cur))}" ~)
(pure:m !>(~))

Save it as /ted/btc-price.hoon in the %base desk of a fake ship, |commit %base and run it with -btc-price %usd. You should see something like:

You can try with other currencies as well:

Analysis

The thread takes a @tas as its argument, which the dojo wraps in a $unit. We extract the $vase and check it's not empty:

We then convert it to lowercase and check it's a valid @tas:

Next, we use the +fetch-json function in strandio like so:

We convert the currency to a $tape and +weld it to the end of the url, which we give as an argument to +fetch-json. The +fetch-json function will make the request to the URL, receive the result, parse the JSON and produce the result as a $json structure.

The JSON the API produces looks like:

Since it's an object in an object, we decode them using nested ot:dejs-soft:format functions, and the price itself using no:dejs-soft:format to produce a (unit @ta):

Finally, we check if the $unit is null and either print an error or print the price to the terminal with +slog functions (the thread itself produces ~):

For more information about working with $json, see the JSON Guide.

Last updated