A minimal REST API written in Clojure
Unlike most Clojure backend projects, clojuREST only uses one 3rd party library to set up a web server with routing. Typically you see a lot of projects using Ring and Compojure which are great and really streamline server development but they introduce a lot of dependencies. clojuREST gets around this by using http-kit. You have to write a little extra code but in return you get more control over data flow.
clojuREST is not a library, nor does it have any use as standalone software. It’s merely a proof of concept that someone may use to create an API with minimal dependencies. Feel free to download and modify as needed.
By default, http-kit starts a server at localhost:8090
. Aside from the index /
(which returns Hello, World!
), there are two built-in web services:
-
Test
- endpoint:
/test
- supported methods: any
- accepted body: any
- prints
testing
to the commandline - used for verifying other services (which may fail if written incorrectly)
- endpoint:
-
Secret
- endpoint:
/secret
- supported methods: GET, PUT
- accepted body: any JSON-formatted data
- reads/writes the file “secret”
- a crude example of a stateful service
- endpoint:
These are handled by the functions test-service
and secret-service
respectively.
In addition to the services, there are two other functions in core.clj:
-
respond
- takes an optional body to return in an HTTP response
- prints the body to the commandline
- returns the body, HTTP status 200, and some headers used by cljs-ajax(another minimalist library I use)
-
handler
- a callback used by the http-kit server
- captures the received request in the parameter
request
- parses the body using
clojure.data.json/read-str
- handles routing with nested
case
expressions
- Get Leiningen
cd
to project directorylein uberjar
- this will create two jars:clojurest-0.0.1.jar
- smaller, but only runs on the build computerclojurest-0.0.1-standalone.jar
- larger, but works on any computer
- Run with Leiningen (in project directory):
lein run
- Run with Java:
java -jar clojurest-0.0.1-standalone.jar
*you may need admin privileges to allow the application through your firewall