Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,8 @@ UpgradeLog*.htm
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
FakesAssemblies/

#python builds
python/
*.pyc
84 changes: 84 additions & 0 deletions python/_0_header.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""
aWhere Code Samples
License: MIT
Author: Vince Buscarello ([email protected])

These code samples show a variety of different use cases and demonstrate
how to make API calls in Python using the Requests library.

Why use requests vs httplib2 --
http://docs.python-requests.org/en/master/community/faq/

Each file shows a different use case. It is currently designed so that if you
load the file to a browser and access it from a server, you will see
prettified results in HTML. I am hoping to add a flask example interface soon.

This file is the best place for your application specific configurations
like Key and Secret. Be sure to remove before commiting to any public repos!

This file also defines the functions to get the auth token and make API calls.
"""


import requests as rq
import base64

from _0_header_requests import GetOAuthToken

api_key = " "
api_secret = " "
auth_token = GetOAuthToken(api_key, api_secret)['access_token']

def GetOAuthToken(Key, Secret, test_it = False):
'''This function returns the OAuth token and its expiration.
it is only currently coded to define the function, which is imported
and used in other scripts.

It features an optional switch to print the Token to the console for
debugging purposes.
'''

encoded_key_secret = base64.b64encode('%s:%s' % (Key, Secret)).replace('\n', '')

auth_url = 'https://api.awhere.com/oauth/token'

auth_headers = {
"Authorization":"Basic %s" % encoded_key_secret,
'Content-Type':'application/x-www-form-urlencoded'
}

body="grant_type=client_credentials"

get_the_token = rq.post('https://api.awhere.com/oauth/token',
headers=auth_headers,
data=body)

# .json method is a requests lib method that decodes the response
if test_it:
print 'got token'
print get_the_token.json()

return get_the_token.json()


def MakeAPICall(verb, url, token, headers=None, body=None):
'''Takes result of the above as token,
and uses the verb to define a requests and return data.'''

# headers are defaulted to the most commonly used, can be overwritten
# by passing a headers keyword arg.
if not headers:
headers = {
'Authorization': 'Bearer %s' % token,
'Content-Type': 'application/json'
}

# I use lower() here for argument simplicity - if the user pases caps or
# lower case, or some combo, the request still runs smoothly.
if verb.lower() == 'get':
call = rq.get(url, headers = headers, data = body)

elif verb.lower() == 'post':
call = rq.post(url, headers = headers, data = body)

return call
27 changes: 27 additions & 0 deletions python/_1_get_fields_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""This script gets a list of fields you have under your app.

It uses functions defined in _0_header.py
"""

import json

from _0_header import MakeAPICall, auth_token

url = 'https://api.awhere.com/v2/fields'

try:
get_fields = MakeAPICall('GET',
url = 'https://api.awhere.com/v2/fields',
token = auth_token)

except Exception as responseException:
print responseException

print "<h2> attempting to get list of fields.... </h2>"

if get_fields.status_code == 200 :
print "<p> got fields! </p>"
print get_fields.content

else:
print "ERROR: ", get_fields.status_code," \n - \n ", get_fields.content
38 changes: 38 additions & 0 deletions python/_2_create-field.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""This script adds a field to your app.

It uses
- functions defined in _0_header.py
- data defined in testvars.py
"""

import json

import testvars
from _0_header import MakeAPICall, auth_token

print "<h2>attempting to create a field</h2>"
print "<hr>"

host = 'https://api.awhere.com/'

try:
new_field_post = makeAPICall('POST',
url = host + '/v2/fields',
token = auth_token,
body = testvars.test_field_dict)

except Exception as responseException:
print responseException


if new_field_post.statusCode == 201 :
print "request returned success!"
print "<hr>"
print "Request: " new_field_post.request.method, new_field_post.request.body
elif statusCode == 409 :
print "<hr>"
print "A field with ID ",testvars.test_field_dict,
print "already exists in your account, so it could not be created again."
print new_field_post.content
else:
print "ERROR: ", new_field_post.status_code," \n - \n ", new_field_post.content
84 changes: 84 additions & 0 deletions python/_3_get_forecasts_agronomics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""This script gets field agronomic and weather data.

It uses
- functions defined in _0_header.py
- field data retrieved by the call in _1_get_fields_list
"""

import json
import datetime

from _0_header import MakeAPICall, auth_token
from _1_get_fields_list import get_fields
from testvars import forecast_start, forecast_end

field_data_urls = get_fields.json()['fields'][0]['_links']

try:
print '<h2> you have access to...'
print field_data_urls
print '</h2>'

except Exception as fields_except:
print 'Not much, since get fields failed or is undefined,'+\
'create a field then get fields first.\n--\n'
print 'here is the error \n'
print fields_except

print "<hr>"
print "<hr>"

try:
agronms = MakeAPICall('GET',
url = 'https://api.awhere.com'+\
field_data_urls['awhere:agronomics']['href']+\
'/' + forecast_start + ',' + forecast_end,
token = auth_token)
print agronms.url
print agronms.content

except Exception as agronms_except:
print 'get for agronimic data failed with the following \n--\n'
print agronms_except


try:
forecasts = MakeAPICall('GET',
url ='https://api.awhere.com'+\
field_data_urls['awhere:forecasts']['href'],
token = auth_token)

print forecasts.url
print forecasts.content

except Exception as forecasts_except:
print 'get for forecast data failed with the following \n--\n'
print forecasts_except




''' Other fields for more advanced data sets
{
u'awhere:agronomics':
{u'href': u'/v2/agronomics/fields/mynewfield/agronomicvalues'},

u'awhere:forecasts':
{u'href': u'/v2/weather/fields/mynewfield/forecasts'},

u'awhere:observations':
{u'href': u'/v2/weather/fields/mynewfield/observations'},

u'awhere:plantings':
{u'href': u'/v2/agronomics/fields/mynewfield/plantings'},

u'curies':
[
{u'href': u'http://awhere.com/rels/{rel}',
u'name': u'awhere',
u'templated': True}
],
u'self':
{u'href': u'/v2/fields/mynewfield'}
}
'''
82 changes: 0 additions & 82 deletions python/create-field.py

This file was deleted.

46 changes: 0 additions & 46 deletions python/get-fields-list.py

This file was deleted.

Loading