Search code examples
clojurecompojure

Optional query parameters with default value with Compojure (without swagger)?


I what the idiomatic way of handling optional query parameters in Compojure and assign undefined query parameters to a default value.

I've tried this (which perhaps obviously doesn't work):

(GET "/something/:id" [id q :<< as-int :or {q (System/currentTimeMillis)}]
    ....)

I'd like this route to match both:

curl /something/123

and

curl /something/123?q=234542345

(Note a similar question has been posted here but it uses Swagger)


Solution

  • There are lots of options you could take. This is one I might choose.

    (GET "/something/:id" req
      (let [{:keys [id q] :or {q (System/currentTimeMillis)}} (:params req)]
    
        ,,,))
    

    Ultimately, though, which one I chose would depend on whatever led to the most readable (a subjective measurement, but that's the way it goes) code.