0

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 ...))
Freid001
  • 2,580
  • 3
  • 29
  • 60

2 Answers2

0

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}
Tommi Reiman
  • 268
  • 1
  • 6
  • I would like to allow users to both create and update records via the same route `/:item-id` at the minute users can only update because the route needs a `:item-id` to be present otherwise it doesn't match. Is there away that I can set a default value of null if the item-id is missing from the route so that the route `/` is also valid? Or should I just create a separate route? – Freid001 Oct 24 '18 at 10:30
  • you need to create a separate route for the "/". – Tommi Reiman Oct 24 '18 at 16:57
0

The default value is used if no value is present in the URL for the parameter. Path parameters are made optional by appending a question mark (?) to the end of the parameter name. For example, id?. The difference between optional values and default route parameters is: A route parameter with a default value always produces a value. An optional parameter has a value only when a value is provided by the request URL. Path parameters may have constraints that must match the route value bound from the URL. Adding : and constraint name after the route parameter name