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 interactive Swagger documentation for testing your APIs. 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)))))
Clone this wiki locally