Compojure: optional URL parameter

I want to define a resource in Compojure as follows:

(ANY "myres/:id" [id] (handler))

and I want: id to be optional (depending on whether the ID is specified, my API will behave differently).

This works fine if I try to access

http://mydomain/myres/12

However, if I try to access

http://mydomain/myres

without specifying an identifier, I get 404.

Is there a way for the: id parameter to be optional?

Thank!

+5
source share
1 answer

How about creating two different routes with id and the other without it and calling your handler from both routes, as shown below:

(defn handler
    ([] "Response without id")
    ([id] (str "Response with id - " id)))

(defroutes my-routes
    (ANY "myres" [] (handler))
    (ANY "myres/:id" [id] (handler id)))
+8
source

All Articles