Skip to content
Dave Liepmann edited this page Feb 3, 2017 · 3 revisions

Endpoints

  • GET, POST, PUT, HEAD, PATCH, DELETE, OPTIONS and ANY

Compojure-api has it's own versions of Compojure http endpoint macros in compojure.api.core (and also in compojure.api.sweet). They can be used just like the originals, but they also support the compojure-api restructuring syntax.

(require '[compojure.api.sweet :refer :all])
(require '[ring.util.http-response :refer :all])

;; vanilla compojure app
(def app
  (GET "/ping" []
    (ok {:ping "pong"})))

(app {:request-method :get, :uri "/ping"})
; => {:status 200, :headers {}, :body {:ping "pong"}}

Routes and Contexts

  • routes can be used to group routes together (match-first)
  • context allows routes to be grouped under a common path prefix
(def app
  (routes
    (GET "/ping" []
      (ok {:ping "pong"}))
    (context "/api" []
      (GET "/kikka" []
        (ok {:kikka true}))
      (POST "/kukka" []
        (ok {:kukka true})))))

(app {:request-method :get, :uri "/ping"})
; {:status 200, :headers {}, :body {:ping "pong"}}

(app {:request-method :get, :uri "/api/kikka"})
; {:status 200, :headers {}, :body {:kikka true}}

(app {:request-method :post, :uri "/api/kukka"})
; {:status 200, :headers {}, :body {:kukka true}}

Restructuring

Both context and all endpoint macros can have a extra restructuring map (or pairs of keyword key + value) after the 3 compojure-params before the actual body of a handler function. Restructuring is applied at macro-expansion time, enabling new code to be emitted into the handler. A multimethod compojure.api.meta/restructure-param is used as restructuring key dispatch. Compojure-api ships with a set of predefined resturcture dispatch keys, for things like validation, api-docs and more.

;; keys & vals
(GET "/ping" []
  :summary "this is a ping endpoint"
  (ok {:ping "pong"}))

;; as map
(GET "/ping" []
  {:summary "this is a ping endpoint"}
  (ok {:ping "pong"}))

A more useful example, with typed & automatically coerced query-parameters and response, producing also relevant swagger-docs.

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

Out-of-the-box restructurings

See Inline Help.

Create your own restructuring

See Creating your own metadata handlers