Skip to content

Generate UUID in Clojure

Since Clojure is a JVM-based language, we can use the same libraries and methods we would have used in Java to generate UUIDs, as long as we do so in Clojure syntax. The following code snippet produces a valid version 4 UUID:

clojure
(import java.util.UUID)
(UUID/randomUUID)

If you need to generate a specific UUID version, you need to use a third-party library such as uuid-creator which offers more flexible options:

clojure
(import com.github.f4b6a3.uuid.UuidCreator)
(import com.github.f4b6a3.uuid.enums.UuidLocalDomain)
(import com.github.f4b6a3.uuid.enums.UuidNamespace)

;;generate UUID version 1
(UuidCreator/getTimeBased)

;;generate UUID version 2
(UuidCreator/getDceSecurity UuidLocalDomain/LOCAL_DOMAIN_PERSON 1234)

;;generate UUID version 3
(UuidCreator/getNameBasedMd5 UuidNamespace/NAMESPACE_URL "https://github.com/")

;;generate UUID version 4
(UuidCreator/getRandomBased)

;;generate UUID version 5
(UuidCreator/getNameBasedSha1 UuidNamespace/NAMESPACE_URL "https://github.com/")

;;generate UUID version 6
(UuidCreator/getTimeOrdered)

;;generate UUID version 7
(UuidCreator/getTimeOrderedEpoch)

Installation & Setup

Leiningen (project.clj):

clojure
:dependencies [[com.github.f4b6a3/uuid-creator "5.3.2"]]

deps.edn:

clojure
{:deps {com.github.f4b6a3/uuid-creator {:mvn/version "5.3.2"}}}

Advanced Clojure Usage

UUID Utility Functions:

clojure
(ns uuid-service
  (:import [java.util UUID]
           [com.github.f4b6a3.uuid UuidCreator]))

(defn generate-v4 []
  (str (UUID/randomUUID)))

(defn generate-v7 []
  (str (UuidCreator/getTimeOrderedEpoch)))

(defn valid-uuid? [uuid-str]
  (try
    (UUID/fromString uuid-str)
    true
    (catch IllegalArgumentException _
      false)))

(defn parse-uuid [uuid-str]
  (try
    (UUID/fromString uuid-str)
    (catch IllegalArgumentException _
      nil)))

(defn uuid-version [uuid-str]
  (when-let [uuid (parse-uuid uuid-str)]
    (.version uuid)))

;; Usage examples
(def my-uuid (generate-v4))
(println "Valid:" (valid-uuid? my-uuid))
(println "Version:" (uuid-version my-uuid))

Ring/Compojure Web Service:

clojure
(ns uuid-web-service
  (:require [compojure.core :refer :all]
            [compojure.route :as route]
            [ring.middleware.json :refer [wrap-json-response wrap-json-body]]
            [ring.util.response :refer [response]]
            [uuid-service :as uuid])
  (:import [java.time Instant]))

(defroutes app-routes
  (GET "/api/uuid" []
    (response {:uuid (uuid/generate-v4)
               :timestamp (str (Instant/now))}))
  
  (GET "/api/uuid/:name" [name]
    (let [namespace (UUID/fromString "6ba7b810-9dad-11d1-80b4-00c04fd430c8")
          named-uuid (UUID/nameUUIDFromBytes (.getBytes (str namespace name)))]
      (response {:uuid (str named-uuid)
                 :name name
                 :deterministic true})))
  
  (route/not-found "Not Found"))

(def app
  (-> app-routes
      wrap-json-response
      wrap-json-body))

Pedestal Service:

clojure
(ns uuid-pedestal-service
  (:require [io.pedestal.http :as http]
            [io.pedestal.http.route :as route]
            [io.pedestal.http.body-params :as body-params]
            [uuid-service :as uuid])
  (:import [java.time Instant]))

(defn generate-uuid-handler [request]
  {:status 200
   :headers {"Content-Type" "application/json"}
   :body {:uuid (uuid/generate-v4)
          :timestamp (str (Instant/now))}})

(defn generate-named-uuid-handler [request]
  (let [name (get-in request [:path-params :name])
        namespace (UUID/fromString "6ba7b810-9dad-11d1-80b4-00c04fd430c8")
        named-uuid (UUID/nameUUIDFromBytes (.getBytes (str namespace name)))]
    {:status 200
     :headers {"Content-Type" "application/json"}
     :body {:uuid (str named-uuid)
            :name name
            :deterministic true}}))

(def routes
  (route/expand-routes
    #{["/api/uuid" :get generate-uuid-handler :route-name :generate-uuid]
      ["/api/uuid/:name" :get generate-named-uuid-handler :route-name :generate-named-uuid]}))

Testing with clojure.test:

clojure
(ns uuid-service-test
  (:require [clojure.test :refer :all]
            [uuid-service :as uuid]))

(deftest test-uuid-generation
  (testing "UUID v4 generation"
    (let [uuid (uuid/generate-v4)]
      (is (string? uuid))
      (is (uuid/valid-uuid? uuid))
      (is (= 4 (uuid/uuid-version uuid)))))
  
  (testing "UUID validation"
    (is (uuid/valid-uuid? "550e8400-e29b-41d4-a716-446655440000"))
    (is (not (uuid/valid-uuid? "invalid-uuid")))
    (is (not (uuid/valid-uuid? nil))))
  
  (testing "UUID parsing"
    (is (some? (uuid/parse-uuid "550e8400-e29b-41d4-a716-446655440000")))
    (is (nil? (uuid/parse-uuid "invalid-uuid")))))

UUID Version Comparison

Choose the right version for your Clojure application:

  • Version 1 - Time-based, includes MAC address
  • Version 3 - MD5 namespace-based, deterministic
  • Version 4 - Random, most popular choice
  • Version 5 - SHA-1 namespace-based, more secure than v3
  • Version 6 - Time-ordered, better than v1 for databases
  • Version 7 - Modern time-based with improved sorting

For Clojure applications:

  • Web APIs: Use Version 4 for stateless functional programming
  • Data processing: Consider Version 5 for deterministic transformations
  • Event sourcing: Use Version 7 for time-ordered event streams

How do I generate UUID in other languages?

JVM ecosystem:

  • Java - Enterprise applications
  • Scala - Functional programming and big data
  • Kotlin - Modern JVM development

Functional programming:

← Back to Online UUID Generator