Optional query parameters (with default value) with compojure-api

Viewed 4031

What is the proper way to declare an optional query parameter, with default value, when using compojure-api?

One of my route elements is as follows (after reading this):

(GET "/:id/descendants" [id]
     :return [d/CategoryTreeElement]
     :path-params [id :- Long]
     :query-params [context-type :- d/ContextType
                    levels :- Integer
                    {tenant :- d/Tenant :DEF_TENANT}
                    {show-future :- Boolean false}
                    {show-expired :- Boolean false}
                    {show-suppressed :- Boolean false}
     :summary "Fetch category descendants"
     (ok ...))

At first the boolean params where defined as the other ones (e.g. show-future Boolean) but the generated Swagger UI presented them as a combobox with true value as default. In the present form the UI shows a combobox with no option selected. The same happens with tenant.

One side question: when I use Swagger generated UI to send a request and error is returned: "levels": "(not (instance? java.lang.Integer \"2\"))". Why is that? Isn't the library supposed to coerce/convert string values to the designated types declared by the API?

Thanks in advance.

2 Answers

If you use clojure.spec and you want as a default value false in your swagger documentation for a boolean variable you can use spec tool library and do something like :

(s/def ::show-future 
  (st/spec {:spec boolean?
            :json-schema/example false
            :json-schema/default false}))

Then, in your query params :

:query-params [{show-future :- ::show-future false}]
Related