Search code examples
clojurecompojurecompojure-api

How do I set default values for path parameters?


In the below example, how can I set a default value for the path parameter item-id?

(POST "/:id" [item-id]
  :path-params [item-id :- Int]
  :body [body Body]
  :query-params [{item-name :- Str nil}]
                 :summary "Create or update a item."
                 (ok ...))

Solution

  • You should match the path-parameter name to the string placeholder. Path-params don't need defaults - if there is no path-parameter present, the route doesn't match. Here's a working example:

    (require '[compojure.api.sweet :refer :all])
    (require '[ring.util.http-response :refer :all])
    (require '[schema.core :as s])
    (require '[muuntaja.core :as m])
    
    (def app
      (api
        (POST "/:item-id" []
          :path-params [item-id :- s/Int]
          :query-params [{item-name :- s/Str nil}]
          :summary "Create or update a item."
          (ok {:item-id item-id
               :item-name item-name}))))
    
    (->> {:request-method :post
          :uri "/123"
          :query-params {"item-name" "kikka"}}
         (app)
         :body
         (m/decode m/instance "application/json"))
    ; => {:item-name "kikka", :item-id 123}