Rest Helpers
I extracted all the boilerplate to perform a REST get operation into rest-helpers
:
(defun get-json (url)
(let ((json))
(ignore-errors
(multiple-value-bind
(data status)
(drakma:http-request url)
(if (= 200 status)
(let* ((str (flexi-streams:octets-to-string data)))
(setq json (json:decode-json-from-string str))))))
(unless json (format t "~&Unable to fetch from ~A~%" url))
json))
Using both rest-helpers
and json-helpers
(from previous post), to get a list of astronauts in space requires much less code:
(defun get-astronauts ()
(mapcar #'format-astronaut
(get-json-value `(:people)
(get-json "http://api.open-notify.org/astros.json"))))
It is just as easy to get the weather in Singapore (the sunny island I come from):
(defvar *weather-endpoint* "http://api.openweathermap.org/data/2.5/weather")
(defvar *api-key* (uiop:getenv "OPEN_WEATHER_MAP_API_KEY"))
(defun make-request-url (query)
(concatenate 'string *weather-endpoint* "?q=" query "&APPID=" *api-key*))
(defun get-weather (query)
(get-json (make-request-url query)))
(print (get-weather "Singapore"))
Two more things I learnt this week:
- How to read environment variables using
(uiop:getenv ...)
form. - How to enable syntax highlighting for the lisp code snippets in this post.