#!/usr/bin/env python

import requests
import codecs
import json
import sys
import os

# Some of these examples require a Github OAUTH token stored in
# the environment variable GITHUB_OAUTH_TOKEN
# See
# https://github.com/OpenTreeOfLife/api.opentreeoflife.org#using-the-api
# for details about generating the token

if len(sys.argv) > 1:
    apihost = sys.argv[1]
else:
    apihost = "http://127.0.0.1:8000"

headers = {
    'content-type' : 'application/json',
    'accept' : 'application/json',
}

def example_get(study_id=9):
    url  = "%s/api/default/%s%s" % (apihost, "v1/study/", study_id)
    print "Requesting GET %s" % url
    resp = requests.get(url, headers=headers, allow_redirects=True)
    print "Got status code: %s" % resp.status_code

    try:
        json_response = resp.json()
        print json_response
    except:
        text = resp.text
        print text

def example_put(study_id=9):
    url  = "%s/api/default/%s%s" % (apihost, "v1/study/", study_id)
    print "Requesting PUT %s" % url

    study_file = codecs.open("study.json", "rU", encoding="utf-8")
    nexson     = json.load(study_file)

    data = { 'nexson' : nexson,
            'auth_token': os.environ.get('GITHUB_OAUTH_TOKEN', 'bogus_token'),
    }

    resp = requests.put(url, data=json.dumps(data), headers=headers, allow_redirects=True)

    print "Got status code: %s" % resp.status_code

    try:
        json_response = resp.json()
        print json_response
    except:
        text = resp.text
        print text

# Read a study
example_get()

# Modify a study
example_put()

@@ -516,32 +516,59 @@
 et(study_id=9):%0A
+    %22Read a study via GET%22%0A
     url  = %22%25s/a
@@ -778,167 +778,91 @@
 ode%0A
-%0A
     
-try:%0A        json_response = resp.json()%0A        print json_response%0A    except:%0A        text = resp.text%0A        print text%0A%0Adef example_put(study_id=9):
+show_response(resp)%0A%0Adef example_put(study_id=9):%0A    %22Update a study via PUT%22%0A
 %0A   
@@ -1279,16 +1279,552 @@
 s=True)%0A
+    show_response(resp)%0A%0Adef example_post():%0A    %22Create a study via POST%22%0A    url  = %22%25s/api/default/%25s%22 %25 (apihost, %22v1/study/%22)%0A    print %22Requesting POST %25s%22 %25 url%0A%0A    study_file = codecs.open(%22study.json%22, %22rU%22, encoding=%22utf-8%22)%0A    nexson     = json.load(study_file)%0A%0A    data = %7B 'nexson' : nexson,%0A            'auth_token': os.environ.get('GITHUB_OAUTH_TOKEN', 'bogus_token'),%0A    %7D%0A%0A    resp = requests.post(url, data=json.dumps(data), headers=headers, allow_redirects=True)%0A    show_response(resp)%0A%0A%0Adef show_response(resp):
 %0A    pri
@@ -2055,12 +2055,49 @@
 ample_put()%0A
+%0A# Create a new study%0Aexample_post()%0A

Add sample client code for creating a new study via a POST request