Search code examples
clojurecompojure

Compojure: optional URL parameter


I want to define a resource in Compojure like this:

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

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

This works ok if I try to access

http://mydomain/myres/12

However if I try to access

http://mydomain/myres

without specifying an ID, I get 404.

Is there any way to have the parameter :id to be optional?

Thanks!


Solution

  • What about creating 2 different route one with id and another without it and calling your handler from both route 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)))