Last active
February 23, 2018 14:09
-
-
Save jmhdez/bef0d14a8da26abf2c4e to your computer and use it in GitHub Desktop.
Using the Marvel API from clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; required deps [clj-http "0.9.2"] | |
(ns marvel-clj.core | |
(:require [clj-http.client :as http] | |
[clj-http.util :as util] | |
[clojure.string :as str]) | |
(:gen-class)) | |
(def public-key "YOUR_PUBLIC_KEY_HERE") | |
(def private-key "YOUR_PRIVATE_KEY_HERE") | |
(def base-url "http://gateway.marvel.com/v1/public") | |
(defn md5 [text] | |
(let [d (.. (doto (java.security.MessageDigest/getInstance "MD5") | |
.reset | |
(.update (.getBytes text))) | |
digest)] | |
(apply str (map (partial format "%02x") d)))) | |
(defn keyword-to-url-param [kw] | |
(let [ws (str/split (name kw) #"-")] | |
(apply str (cons (first ws) (map str/capitalize (rest ws)))))) | |
(defn encode-params [params] | |
(if (empty? params) | |
"" | |
(str/join (map (fn [[k v]] (str "&" (keyword-to-url-param k) "=" (util/url-encode (str v)))) params)))) | |
(defn build-url [path params] | |
(let [ts (quot (System/currentTimeMillis) 1000) | |
hash (md5 (str ts private-key public-key))] | |
(str base-url path "?ts=" ts "&apikey=" public-key "&hash=" hash (encode-params params)))) | |
(defn get-json [path params] | |
(get-in (http/get (build-url path params) {:as :json}) [:body :data])) | |
(defn get-comics [params] | |
(get-json "/comics" params)) | |
(defn get-characters [params] | |
(get-json "/characters" params)) | |
(defn get-character [id params] | |
(get-json (str "/characters/" id) params)) | |
;; Usage | |
;; (get-comics {:offset 30 :limit 10 :name-starts-with "s" :order-by "name" }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment