Skip to content

Instantly share code, notes, and snippets.

@tormaroe
Created November 23, 2010 14:44
Show Gist options
  • Save tormaroe/711862 to your computer and use it in GitHub Desktop.
Save tormaroe/711862 to your computer and use it in GitHub Desktop.
Simple client implemented in clojure demonstrating how to use the PSWinCom Intouch REST API.
(ns intouch
(:use clojure.contrib.json)
(:require [clojure.contrib.http.agent :as http]
[clojure.contrib.base64 :as b64 ]))
;; Configuration ------------------------------------------------------------------
(def username "user@domain")
(def password "password")
(def base-url "http://intouchapi.pswin.com/1/")
;; --------------------------------------------------------------------------------
(defn authorization []
"Prepares/encodes token for basic authentication"
(->> (str username ":" password)
b64/encode-str
(str "Basic ")))
(def api-headers { "Authorization" (authorization)
"Accept" "application/json"
"Content-Type" "application/json" })
(defn api
"Main API function which can be used on any resource with any http verb."
([resource ] (api resource "GET" nil))
([resource verb ] (api resource verb nil))
([resource verb body]
(let [agnt (http/http-agent (str base-url resource)
:method verb
:body (if (map? body)
(json-str body)
body)
:headers api-headers)]
; Calling result on agnt below is a fix to a bug, see:
; http://www.mail-archive.com/clojure@googlegroups.com/msg20018.html
(http/result agnt)
(if (= "application/json"
((http/headers agnt) :content-type))
(read-json (http/string agnt))
(http/string agnt)))))
(defn api-update
"Does a GET on resource, merges in new values,
then PUTs the result back to the same resource."
[resource new-values]
(api resource "PUT"
(json-str (merge (api resource)
new-values))))
;; Sample usage ----------------------------------------------------------------
(comment
(api "groups") ; returns all groups..
(api "groups/45") ; returns group 45
(api "groups/45/contacts") ; returns all contacts in group 45
(api "groups/45/contacts/2039" "DELETE") ; removed contact 2039 from group 45
(api "contacts" "POST"
{ :CPAAccepted false
:Description "Some description"
:Firstname "William"
:Lastname "Gates"
:IsPrivate false
:PhoneNumber "90555812" }) ; creates a new contact
(api-update "contacts/345"
{ :Description "Updated description"
:Email "bill@microsoft.com" }) ; updates contact 345
) ; end comment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment