Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 380
Nico Balestra Avatar asked Apr 06 '13 16:04

Nico Balestra


1 Answers

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)))
like image 89
Ankur Avatar answered Sep 20 '22 10:09

Ankur