A simple RESTful service in Common Lisp using caveman2 and datafly
See Caveman2 and datafly for more details.
(ql:quickload '(clack caveman2 datafly sxql))
(in-package :cl-user)
(defpackage rest-test
(:use :cl
:clack
:caveman2
:datafly
:sxql))
(in-package :rest-test)
(defparameter *web* (make-instance '<app>))
(syntax:use-syntax :annot)
(connect-toplevel :mysql :database-name "database" :username "user" :password "pass")
(defun render-json (object)
(setf (getf (response-headers *response*) :content-type) "application/json")
(encode-json object))
;;; Retrieve all the rows of a table author
(defun all-authors ()
(retrieve-all
(select :*
(from :authors))))
;;; this is the endpoint itself.
(defroute "/authors" ()
(let ((authors (all-authors)))
(render-json authors)))
;;; the server start/stop code
(defvar *handler* nil)
(defun start (&rest args &key server port debug &allow-other-keys)
(declare (ignore server port debug))
(when *handler*
(restart-case (error "Server is already running.")
(restart-server ()
:report "Restart the server"
(stop))))
(setf *handler*
(apply #'clackup *web* args)))
(defun stop ()
(prog1
(clack:stop *handler*)
(setf *handler* nil)))
Then, the server can be started using:
(start :port 8080)
or
(start :server :woo :port 8080)