Skip to content

Commit b4fa1c3

Browse files
committed
The source for the first release of the SP REST API Cookbook
1 parent b83a6a6 commit b4fa1c3

22 files changed

+4397
-2
lines changed

README.md

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,30 @@
1-
# sp-rest-api-cookbook
2-
A document with examples of using the Arbor SP REST API, intended as a supplement to the online REST API documentation
1+
# Using the Arbor Networks SP REST API: SP v8.3 API v2
2+
3+
This repository contains the source material for a document that is
4+
intended to be a gentle, user-facing introduction to the Arbor
5+
Networks SP REST API.
6+
7+
## Formatting
8+
9+
The file `sp-rest-api-tutorial.txt` is formatted according to
10+
[Emacs Orgmode](http://orgmode.org/guide/) formatting rules. You
11+
don't need Emacs or Orgmode to edit this file; the examples in the
12+
file should be sufficient guidance for adding to it and the link to
13+
the [Orgmode Guide](http://orgmode.org/guide/) may also help.
14+
15+
## Contributing
16+
17+
All contributions are greatly appreciated; pull requests, emailed
18+
patches, emailed edits, printed and written-on paper, whatever works
19+
easiest for you.
20+
21+
## Rendering
22+
23+
If you want to render this you can use Emacs+Orgmode's Export (`C-e`)
24+
command to produce HTML, PDF, etc.
25+
26+
## Releases
27+
28+
Rendered versions will be released periodically at this Github site;
29+
unless you are intending to contribute or want to render your own
30+
version, the rendered releases are probably the best option for you.

code-examples/BI-to-MO.py

Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
from __future__ import print_function
2+
import csv
3+
import json
4+
import requests # version: 2.18.4
5+
import sys
6+
7+
CERTFILE="../certfile"
8+
9+
def api_request(URL, key, body=None):
10+
""" Creates and makes a post request to an SP
11+
api service
12+
13+
Args:
14+
URL: A URL including an SP leader and
15+
SP resource
16+
key: An api key generated on the given
17+
SP leader
18+
body: JSON formatted string to be supplied
19+
as the request's body
20+
21+
Returns:
22+
'data' value of an SP api response
23+
"""
24+
25+
headers = {
26+
'X-Arbux-APIToken': key,
27+
'Content-Type': 'application/vnd.api+json'
28+
}
29+
30+
api_response = requests.post(
31+
URL,
32+
data=body,
33+
headers=headers,
34+
verify=CERTFILE
35+
)
36+
37+
try:
38+
api_response.raise_for_status()
39+
except requests.exceptions.HTTPError as err:
40+
print(
41+
'An HTTP {} Error Occured:{}'.format(
42+
str(err),
43+
api_response.text),
44+
file=sys.stderr
45+
)
46+
47+
return api_response.json()
48+
49+
try:
50+
return api_response.json()['data']
51+
except ValueError as err:
52+
return {}
53+
54+
55+
def get_request_body(managed_object):
56+
"""Map a row in a csv to a nested dictionary
57+
that SP will accept as a managed object
58+
59+
Args:
60+
managed_object: flat dictionary from csv
61+
representing a single managed object
62+
63+
Returns:
64+
Nested dictionary representing a
65+
managed object in SP
66+
67+
"""
68+
69+
return {
70+
'data': {
71+
'attributes': {
72+
'name': managed_object['name'],
73+
'family': 'customer',
74+
'match_type': 'cidr_block',
75+
'match': managed_object['prefix'],
76+
'tags': ['api']
77+
},
78+
'relationships': {
79+
'mitigation_template': {
80+
'data': {
81+
'id': '2',
82+
'type': 'mitigation_template'
83+
}
84+
}
85+
}
86+
}
87+
}
88+
89+
90+
def get_managed_objects_from_csv(filename):
91+
""" Get a handler for managed object data
92+
from a csv file
93+
94+
Args:
95+
filename: path / name for a csv file
96+
containing managed_object configurations.
97+
The first line of the csv is a header,
98+
containing "name,prefix". Similarly,
99+
subsequent lines represent managed objects.
100+
E.g., "Wind,74.182.59.3/32".
101+
102+
Returns:
103+
A generator returning managed objects in
104+
nested dict form
105+
"""
106+
107+
with open(filename) as listings:
108+
for row in csv.DictReader(listings):
109+
yield get_request_body(row)
110+
111+
112+
def create_managed_object(leader, key, managed_object):
113+
""" Crafts and makes an api request to create
114+
an SP managed object
115+
116+
Args:
117+
leader: hostname of an SP leader
118+
key: api key, as generated by the
119+
SP leader
120+
managed_object: nested dict representing
121+
the managed_object being
122+
created
123+
124+
Returns:
125+
Id as string of new managed object, or
126+
None if request was unsuccessful
127+
"""
128+
129+
object_json = json.dumps(managed_object)
130+
131+
response = api_request(
132+
'https://{}/api/sp/managed_objects/'.format(leader),
133+
key,
134+
object_json
135+
)
136+
137+
if 'errors' in response:
138+
print(
139+
'Could not create managed object...',
140+
file=sys.stderr
141+
)
142+
return None
143+
144+
return response["id"]
145+
146+
147+
def commit_config(leader, key):
148+
""" Crafts and makes an api request to commit an
149+
SP configuration
150+
151+
Args:
152+
leader: hostname of an SP leader
153+
key: api key, as generated by said SP leader
154+
155+
Returns:
156+
boolean indicating the success of the
157+
operation
158+
"""
159+
print ("Committing configuration.")
160+
commit_msg = json.dumps({
161+
'data': {
162+
'attributes': {
163+
'commit_log_message':
164+
'Added managed objects to deployment via SP API'
165+
}
166+
}
167+
})
168+
169+
response = api_request(
170+
'https://{}/api/sp/config/'.format(leader),
171+
key,
172+
commit_msg
173+
)
174+
175+
if 'errors' in response:
176+
print(
177+
"Could not commit configuration...",
178+
file=sys.stderr
179+
)
180+
return False
181+
182+
print("Committed configuration.")
183+
return True
184+
185+
186+
def main():
187+
LEADER = "leader.example.com"
188+
KEY = "eFvokphdyGHA_M4oLlLtfDnlIf9bpjFnn0mWlDqw"
189+
190+
for listing in get_managed_objects_from_csv('main.csv'):
191+
create_managed_object(LEADER, KEY, listing)
192+
193+
commit_config(LEADER, KEY)
194+
195+
196+
if __name__ == "__main__":
197+
main()

code-examples/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
The files in this directory are included in the main document via
3+
org-mode `#INCLUDE:` directives.
4+
5+
All source examples should be committed here, and then described and
6+
included in the document `sp-rest-api-tutorial.txt` so that when that
7+
is rendered as a PDF or HTML or ebook or whatever, the code is
8+
included and has been given some context.

0 commit comments

Comments
 (0)