Skip to content

Commit 593e3c6

Browse files
committed
Move example code to README and trim white space
Temporarily moving example code to README.md until wiki for documentation has been created. Also trimming trailing white space now just because.
1 parent 3596f3c commit 593e3c6

4 files changed

Lines changed: 122 additions & 119 deletions

File tree

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
ox_*.py
2-
*.pyc
2+
*.pyc

README.md

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,87 @@
11
#OX3-Python-API-Client - Python class to access OpenX Enterprise API
22
OX3-Python-API-Client is a small class to help demonstrate how to connect to the OpenX Enterprise API. It depends on the [simplegeo/python-oauth2](https://github.com/simplegeo/python-oauth2) module.
33

4-
It currently supports Python 2.7 and will be updated to support Python 3.x.
4+
It currently supports Python 2.7 and will be updated to support Python 3.x.
5+
6+
````python
7+
import datetime
8+
import ox3apiclient
9+
10+
# User credentials
11+
email_address = ''
12+
password = ''
13+
14+
# OAuth credentials. These will be supplied by your Account Manager or Support.
15+
domain = ''
16+
realm = ''
17+
consumer_key = ''
18+
consumer_secret = ''
19+
20+
21+
ox = ox3apiclient.OX3APIClient(domain, realm, consumer_key, consumer_secret)
22+
23+
# Step 1. Fetch temporary request token.
24+
ox.fetch_request_token()
25+
26+
# Step 2. Log in to SSO server and authorize token.
27+
ox.authorize_token(email_address, password)
28+
29+
# Step 3. Swap temporary request token for permanent access token.
30+
# If you need to store the access token yourself you can do so with something
31+
# similar to:
32+
# token_str = ox.fetch_access_token()
33+
# access_token = urlparse.parse_qs(token_str)['oauth_token'][0]
34+
ox.fetch_access_token()
35+
36+
# Step 4. Validate your access token.
37+
# You'll more than likely want to call the validate_session method, but you can
38+
# manually validate your access token if needed. You will be resonpsible for
39+
# passing the requisite openx3_access_token for all successive API requests. A
40+
# method might look like the following:
41+
# token_str = ox.fetch_access_token()
42+
# access_token = urlparse.parse_qs(token_str)['oauth_token'][0]
43+
# cookie_header = {'Cookie': 'openx3_access_token=' + access_token}
44+
# ox.request(url='http://youruidomain.com/ox/3.0/a/session/validate',
45+
# method='PUT',
46+
# headers=cookie_header)
47+
ox.validate_session()
48+
49+
50+
# Now that we have connected let's try making a few API requests.
51+
# Print out account names. We use overload=medium to get more than just a
52+
# listing of ids.
53+
accounts = ox.get('/a/account?overload=medium')
54+
for account in accounts:
55+
msg = 'Account ID: %s, Account Name: %s'
56+
print(msg % (account['id'], account['name']))
57+
58+
# We won't test object creation with accounts because they can't be deleted
59+
# currently. Instead, we will create an order under an advertiser account.
60+
account_id = 0 #<= Replace with a valid advertiser account id for your instance.
61+
62+
if account_id:
63+
64+
# You can check to see what fields are required for the create action.
65+
# required_fields = ox.get('/a/order/requiredFields?action=create')
66+
# print(required_fields) #=> {u'status': u'string', u'name': u'string', u'account_id': u'int', u'start_date': u'datetime'}
67+
68+
# OX3APIClient methods accept Python dicts for data parameters, so we can
69+
# define an order as a normal dict.
70+
order = {
71+
'status': 'Active',
72+
'name': 'OX3APIClient Object Creation Test',
73+
'account_id': account_id,
74+
'start_date': datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S'),
75+
}
76+
77+
new_order = ox.post('/a/order', data=order)
78+
# print(order) #=> {u'id': 12345}
79+
print('Created order id %s' % new_order['id'])
80+
81+
# Let's get all the details on the order we just created.
82+
existing_order = ox.get('/a/order/%s' % new_order['id'])
83+
print(existing_order)
84+
85+
# Log out.
86+
ox.delete('/a/session')
87+
````

example.py

Lines changed: 0 additions & 80 deletions
This file was deleted.

ox3apiclient.py

Lines changed: 37 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
HTTP_METHOD_OVERRIDES = ['DELETE', 'PUT']
1515

1616
class OX3APIClient(object):
17-
17+
1818
def __init__(self, domain, realm, consumer_key, consumer_secret,
1919
callback_url='oob',
2020
scheme='http',
@@ -23,9 +23,9 @@ def __init__(self, domain, realm, consumer_key, consumer_secret,
2323
authorization_url=AUTHORIZATION_URL,
2424
api_path=API_PATH):
2525
"""
26-
26+
2727
domain -- Your UI domain. The API is accessed off this domain.
28-
realm -- Your sso realm. While not necessary for all OAuth
28+
realm -- Your sso realm. While not necessary for all OAuth
2929
implementations, it is a requirement for OpenX Enterprise
3030
consumer_key -- Your consumer key.
3131
consumer_secret -- Your consumer secret.
@@ -46,31 +46,31 @@ def __init__(self, domain, realm, consumer_key, consumer_secret,
4646
self.access_token_url = access_token_url
4747
self.authorization_url = authorization_url
4848
self.api_path = api_path
49-
49+
5050
# You shouldn't need to access the oauth2 consumer and token objects
5151
# directly so we'll keep them "private".
5252
self._consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
5353
self._token = None
54-
54+
5555
# Similarly you probably won't need to access the cookie jar directly,
5656
# so it is private as well.
5757
self._cookie_jar = cookielib.LWPCookieJar()
5858
opener = \
5959
urllib2.build_opener(urllib2.HTTPCookieProcessor(self._cookie_jar))
60-
60+
6161
urllib2.install_opener(opener)
62-
62+
6363
def _sign_request(self, req):
6464
"""Utility method to sign a request."""
6565
parameters = {'oauth_callback': self.callback_url}
6666
headers = req.headers
6767
data = req.data
68-
68+
6969
# Add any (POST) data to the parameters to be signed in the OAuth
7070
# request.
7171
if data:
7272
parameters.update(data)
73-
73+
7474
# Create a temporary oauth2 Request object and sign it so we can steal
7575
# the Authorization header.
7676
oauth_req = oauth.Request.from_consumer_and_token(
@@ -80,80 +80,80 @@ def _sign_request(self, req):
8080
http_url=req.get_full_url(),
8181
parameters=parameters,
8282
is_form_encoded=True)
83-
83+
8484
oauth_req.sign_request(
8585
oauth.SignatureMethod_HMAC_SHA1(),
8686
self._consumer,
8787
self._token)
88-
88+
8989
# Update our original requests headers to include the OAuth Authorization
9090
# header and return it.
9191
req.headers.update(oauth_req.to_header(realm=self.realm))
9292
return \
9393
urllib2.Request(req.get_full_url(), headers=req.headers, data=data)
94-
94+
9595
def request(self, url, method='GET', headers={}, data=None, sign=False):
9696
"""Helper method to make a (optionally OAuth signed) HTTP request."""
97-
97+
9898
# Since we are using a urllib2.Request object we need to assign a value
9999
# other than None to "data" in order to make the request a POST request,
100100
# even if there is no data to post.
101101
if method == 'POST':
102102
data = data if data else ''
103-
103+
104104
req = urllib2.Request(url, headers=headers, data=data)
105-
105+
106106
# We need to set the request's get_method function to return a HTTP
107107
# method for any values other than GET or POST.
108108
if method in HTTP_METHOD_OVERRIDES:
109109
req.get_method = lambda: method
110-
110+
111111
if sign:
112112
req = self._sign_request(req)
113-
113+
114114
# Stringify data.
115115
if data:
116116
req.add_data(urllib.urlencode(req.get_data()))
117-
117+
118118
return urllib2.urlopen(req)
119-
119+
120120
def fetch_request_token(self):
121121
"""Helper method to fetch and set request token.
122-
122+
123123
Returns token string.
124124
"""
125125
res = self.request(url=self.request_token_url, method='POST', sign=True)
126126
self._token = oauth.Token.from_string(res.read())
127127
return self._token
128-
128+
129129
def authorize_token(self, email, password):
130130
"""Helper method to authorize."""
131131
data = {
132132
'email': email,
133133
'password': password,
134134
'oauth_token': self._token.key}
135-
135+
136136
res = self.request(
137137
url=self.authorization_url,
138138
method='POST',
139139
data=data,
140140
sign=True)
141-
141+
142142
verifier = urlparse.parse_qs(res.read())['oauth_verifier'][0]
143143
self._token.set_verifier(verifier)
144-
144+
145145
def fetch_access_token(self):
146146
"""Helper method to fetch and set access token.
147-
147+
148148
Returns token string.
149149
"""
150150
res = self.request(url=self.access_token_url, method='POST', sign=True)
151151
self._token = oauth.Token.from_string(res.read())
152152
return self._token
153-
153+
154154
def validate_session(self):
155155
"""Validate an API session."""
156-
156+
157157
# We need to store our access token as the openx3_access_token cookie.
158158
# This cookie will be passed to all future API requests.
159159
cookie = cookielib.Cookie(
@@ -173,38 +173,38 @@ def validate_session(self):
173173
comment=None,
174174
comment_url=None,
175175
rest={})
176-
176+
177177
self._cookie_jar.set_cookie(cookie)
178-
179-
url = '%s://%s%s/a/session/validate' % (self.scheme,
178+
179+
url = '%s://%s%s/a/session/validate' % (self.scheme,
180180
self.domain,
181181
self.api_path)
182-
182+
183183
res = self.request(url=url, method='PUT')
184184
return res.read()
185-
185+
186186
def _resolve_url(self, url):
187187
""""""
188188
parse_res = urlparse.urlparse(url)
189189
if not parse_res.scheme:
190190
url ='%s://%s%s%s' % (self.scheme, self.domain, self.api_path,
191191
parse_res.path)
192192
url = url + '?' + parse_res.query if parse_res.query else url
193-
193+
194194
return url
195-
195+
196196
def get(self, url):
197197
""""""
198198
res = self.request(self._resolve_url(url), method='GET')
199199
return json.loads(res.read())
200-
200+
201201
def post(self, url, data=None):
202202
""""""
203203
res = self.request(self._resolve_url(url), method='POST', data=data)
204204
return json.loads(res.read())
205-
205+
206206
def delete(self, url):
207207
""""""
208208
res = self.request(self._resolve_url(url), method='DELETE')
209209
return json.loads(res.read())
210-
210+

0 commit comments

Comments
 (0)