Skip to content
John Berry edited this page Jan 16, 2017 · 13 revisions

compojure-api provides a powerful and easy to use way to build web APIs declaratively, with all kinds of fun stuff for free, like Schema validation and interactive Swagger docs. We're going to get started by building a simple API for rolling dice on the internet.

Getting Started

compojure-api provides a handy Leiningen template, so to start off with, let's run lein:

lein new compojure-api dice-api

If we navigate into our newly created dice-api directory, it should look something like this:

.
├── README.md
├── project.clj
└── src
    └── dice_api
        └── handler.clj

Let's open up handler.clj in our editor and take a look at what we start off with.

(ns dice-api.handler
  (:require [compojure.api.sweet :refer :all]
            [ring.util.http-response :refer :all]
            [schema.core :as s]))

(s/defschema Pizza
  {:name s/Str
   (s/optional-key :description) s/Str
   :size (s/enum :L :M :S)
   :origin {:country (s/enum :FI :PO)
            :city s/Str}})

(def app
  (api
    {:swagger
     {:ui "/"
      :spec "/swagger.json"
      :data {:info {:title "Dice-api"
                    :description "Compojure Api example"}
             :tags [{:name "api", :description "some apis"}]}}}

    (context "/api" []
      :tags ["api"]

      (GET "/plus" []
        :return {:result Long}
        :query-params [x :- Long, y :- Long]
        :summary "adds two numbers together"
        (ok {:result (+ x y)}))

      (POST "/echo" []
        :return Pizza
        :body [pizza Pizza]
        :summary "echoes a Pizza"
        (ok pizza)))))

That's a lot of stuff, and a good starting example in and of itself. We can see already an example of a lot of the stuff compojure-api can do. You can see, for instance, the Pizza schema, which we've used to define both an incoming and outgoing query schema for out /echo path.

Let's see how this all works. In your shell, run the following command to fire up the server:

lein ring server

Once it's started, it should open up a browser tab right to the Swagger docs, but if not, you can go to http://localhost:3000/index.html in your browser.

Clone this wiki locally