API Documentation¶
This is the primary API client to make API calls. It deals with constructing and executing XML-RPC calls against the SoftLayer API. Below are some links that will help to use the SoftLayer API.
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env(username="username", api_key="api_key")
>>> resp = client.call('Account', 'getObject')
>>> resp['companyName']
'Your Company'
Getting Started¶
You can pass in your username and api_key when creating a SoftLayer client instance. However, you can also set these in the environmental variables ‘SL_USERNAME’ and ‘SL_API_KEY’.
Creating a client instance by passing in the username/api_key:
import SoftLayer
client = SoftLayer.create_client_from_env(username='YOUR_USERNAME', api_key='YOUR_API_KEY')
Creating a client instance with environmental variables set:
$ export SL_USERNAME=YOUR_USERNAME
$ export SL_API_KEY=YOUR_API_KEY
$ python
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env()
Below is an example of creating a client instance with more options. This will create a client with the private API endpoint (only accessible from the SoftLayer private network) and a timeout of 4 minutes.
client = SoftLayer.create_client_from_env(username='YOUR_USERNAME',
api_key='YOUR_API_KEY'
endpoint_url=SoftLayer.API_PRIVATE_ENDPOINT,
timeout=240)
Managers¶
For day-to-day operation, most users will find the managers to be the most convenient means for interacting with the API. Managers abstract a lot of the complexities of using the API into classes that provide a simpler interface to various services. These are higher-level interfaces to the SoftLayer API.
from SoftLayer import VSManager, Client
client = Client(...)
vs = VSManager(client)
vs.list_instances()
[...]
Available managers:
- SoftLayer.account
AccountManager
- SoftLayer.autoscale
AutoScaleManager
- SoftLayer.block
BlockStorageManager
- SoftLayer.cdn
CDNManager
- SoftLayer.dedicatedhost
DedicatedHostManager
- SoftLayer.dns
DNSManager
- SoftLayer.email
EmailManager
- SoftLayer.event_log
EventLogManager
- SoftLayer.file
FileStorageManager
- SoftLayer.firewall
FirewallManager
has_firewall()
- SoftLayer.hardware
HardwareManager
find_item_in_package()
get_item_price()
- SoftLayer.image
ImageManager
- SoftLayer.ipsec
IPSECManager
- SoftLayer.load_balancer
LoadBalancerManager
- SoftLayer.metadata
MetadataManager
metadata.METADATA_ATTRIBUTES
- SoftLayer.network
NetworkManager
- SoftLayer.ordering
OrderingManager
- SoftLayer.sshkey
SshKeyManager
- SoftLayer.ssl
SSLManager
- SoftLayer.ticket
TicketManager
- SoftLayer.vs
VSManager
- SoftLayer.vs_capacity
CapacityManager
- SoftLayer.vs_placement
PlacementManager
If you need more power or functionality than the managers provide, you can make direct API calls as well.
Making API Calls¶
For full control over your account and services, you can directly call the SoftLayer API. The SoftLayer API client for python leverages SoftLayer’s XML-RPC API. It supports authentication, object masks, object filters, limits, offsets, and retrieving objects by id. The following section assumes you have an initialized client named ‘client’.
The best way to test our setup is to call the getObject method on the SoftLayer_Account service.
client.call('Account', 'getObject')
For a more complex example we’ll retrieve a support ticket with id 123456 along with the ticket’s updates, the user it’s assigned to, the servers attached to it, and the datacenter those servers are in. To retrieve our extra information using an object mask.
Retrieve a ticket using object masks.
ticket = client.call('Ticket', 'getObject',
id=123456, mask="updates, assignedUser, attachedHardware.datacenter")
Now add an update to the ticket with Ticket.addUpdate. This uses a parameter, which translate to positional arguments in the order that they appear in the API docs.
update = client.call('Ticket', 'addUpdate', {'entry' : 'Hello!'}, id=123456)
Let’s get a listing of virtual guests using the domain example.com
client.call('Account', 'getVirtualGuests',
filter={'virtualGuests': {'domain': {'operation': 'example.com'}}})
This call gets tickets created between the beginning of March 1, 2013 and March 15, 2013. More information on Object Filters.
- NOTE
The value field for startDate and endDate is in [], if you do not put the date in brackets the filter will not work.
client.call('Account', 'getTickets',
filter={
'tickets': {
'createDate': {
'operation': 'betweenDate',
'options': [
{'name': 'startDate', 'value': ['03/01/2013 0:0:0']},
{'name': 'endDate', 'value': ['03/15/2013 23:59:59']}
]
}
}
}
)
SoftLayer’s XML-RPC API also allows for pagination.
from pprint import pprint
page1 = client.call('Account', 'getVirtualGuests', limit=10, offset=0) # Page 1
page2 = client.call('Account', 'getVirtualGuests', limit=10, offset=10) # Page 2
#Automatic Pagination (v5.5.3+), default limit is 100
result = client.call('Account', 'getVirtualGuests', iter=True, limit=10)
pprint(result)
# Using a python generator, default limit is 100
results = client.iter_call('Account', 'getVirtualGuests', limit=10)
for result in results:
pprint(result)
- NOTE
client.call(iter=True) will pull all results, then return. client.iter_call() will return a generator, and only make API calls as you iterate over the results.
Here’s how to create a new Cloud Compute Instance using SoftLayer_Virtual_Guest.createObject. Be warned, this call actually creates an hourly virtual server so this will have billing implications.
client.call('Virtual_Guest', 'createObject', {
'hostname': 'myhostname',
'domain': 'example.com',
'startCpus': 1,
'maxMemory': 1024,
'hourlyBillingFlag': 'true',
'operatingSystemReferenceCode': 'UBUNTU_LATEST',
'localDiskFlag': 'false'
})
Debugging¶
If you ever need to figure out what exact API call the client is making, you can do the following:
NOTE the print_reproduceable method produces different output for REST and XML-RPC endpoints. If you are using REST, this will produce a CURL call. IF you are using XML-RPC, it will produce some pure python code you can use outside of the SoftLayer library.
# Setup the client as usual
client = SoftLayer.Client()
# Create an instance of the DebugTransport, which logs API calls
debugger = SoftLayer.DebugTransport(client.transport)
# Set that as the default client transport
client.transport = debugger
# Make your API call
client.call('Account', 'getObject')
# Print out the reproduceable call
for call in client.transport.get_last_calls():
print(client.transport.print_reproduceable(call))
Dealing with KeyError Exceptions¶
One of the pain points in dealing with the SoftLayer API can be handling issues where you expected a property to be returned, but none was.
The hostname property of a SoftLayer_Billing_Item is a good example of this.
For example.
# Uses default username and apikey from ~/.softlayer
client = SoftLayer.create_client_from_env()
# iter_call returns a python generator, and only makes another API call when the loop runs out of items.
result = client.iter_call('Account', 'getAllBillingItems', iter=True, mask="mask[id,hostName]")
print("Id, hostname")
for item in result:
# will throw a KeyError: 'hostName' exception on certain billing items that do not have a hostName
print("{}, {}".format(item['id'], item['hostName']))
The Solution¶
Using the python dictionary’s .get() is great for non-nested items.
print("{}, {}".format(item.get('id'), item.get('hostName')))
Otherwise, this SDK provides a util function to do something similar. Each additional argument passed into utils.lookup will go one level deeper into the nested dictionary to find the item requested, returning None if a KeyError shows up.
itemId = SoftLayer.utils.lookup(item, 'id')
itemHostname = SoftLayer.utils.lookup(item, 'hostName')
print("{}, {}".format(itemId, itemHostname))
API Reference¶
SoftLayer Python API Client¶
SoftLayer API bindings
Usage:
>>> import SoftLayer
>>> client = SoftLayer.create_client_from_env(username="username",
api_key="api_key")
>>> resp = client.call('Account', 'getObject')
>>> resp['companyName']
'Your Company'
- license
MIT, see LICENSE for more details.
SoftLayer.API¶
SoftLayer API bindings
- license
MIT, see LICENSE for more details.
- class SoftLayer.API.BaseClient(auth=None, transport=None, config_file=None)[source]¶
Base SoftLayer API client.
- Parameters
auth – auth driver that looks like SoftLayer.auth.AuthenticationBase
transport – An object that’s callable with this signature: transport(SoftLayer.transports.Request)
- authenticate_with_password(username, password, security_question_id=None, security_question_answer=None)[source]¶
Performs Username/Password Authentication
- Parameters
username (string) – your SoftLayer username
password (string) – your SoftLayer password
security_question_id (int) – The security question id to answer
security_question_answer (string) – The answer to the security question
- call(service, method, *args, **kwargs)[source]¶
Make a SoftLayer API call.
- Parameters
method – the method to call on the service
*args – (optional) arguments for the remote call
id – (optional) id for the resource
mask – (optional) object mask
filter (dict) – (optional) filter dict
headers (dict) – (optional) optional XML-RPC headers
compress (boolean) – (optional) Enable/Disable HTTP compression
raw_headers (dict) – (optional) HTTP transport headers
limit (int) – (optional) return at most this many results
offset (int) – (optional) offset results by this many
iter (boolean) – (optional) if True, returns a generator with the results
verify (bool) – verify SSL cert
cert – client certificate path
- Usage:
>>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> client.call('Account', 'getVirtualGuests', mask="id", limit=10) [...]
- iter_call(service, method, *args, **kwargs)[source]¶
A generator that deals with paginating through results.
- Parameters
service – the name of the SoftLayer API service
method – the method to call on the service
limit (integer) – result size for each API call (defaults to 100)
*args – same optional arguments that
Service.call
takes**kwargs – same optional keyword arguments that
Service.call
takes
- SoftLayer.API.Client(**kwargs)[source]¶
Get a SoftLayer API Client using environmental settings.
Deprecated in favor of create_client_from_env()
- class SoftLayer.API.IAMClient(auth=None, transport=None, config_file=None)[source]¶
IBM ID Client for using IAM authentication
- Parameters
auth – auth driver that looks like SoftLayer.auth.AuthenticationBase
transport – An object that’s callable with this signature: transport(SoftLayer.transports.Request)
- authenticate_with_iam_token(a_token, r_token=None)[source]¶
Authenticates to the SL API with an IAM Token
- Parameters
a_token (string) – Access token
r_token (string) – Refresh Token, to be used if Access token is expired.
- authenticate_with_passcode(passcode)[source]¶
Performs IBM IAM SSO Authentication
- Parameters
passcode (string) – your IBMid password
- authenticate_with_password(username, password, security_question_id=None, security_question_answer=None)[source]¶
Performs IBM IAM Username/Password Authentication
- Parameters
username (string) – your IBMid username
password (string) – your IBMid password
- class SoftLayer.API.Service(client, name)[source]¶
A SoftLayer Service.
- Parameters
client – A SoftLayer.API.Client instance
str (name) – The service name
- call(name, *args, **kwargs)[source]¶
Make a SoftLayer API call
- Parameters
service – the name of the SoftLayer API service
method – the method to call on the service
*args – same optional arguments that
BaseClient.call
takes**kwargs – same optional keyword arguments that
BaseClient.call
takesservice – the name of the SoftLayer API service
- Usage:
>>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> client['Account'].getVirtualGuests(mask="id", limit=10) [...]
- iter_call(name, *args, **kwargs)[source]¶
A generator that deals with paginating through results.
- Parameters
method – the method to call on the service
chunk (integer) – result size for each API call
*args – same optional arguments that
Service.call
takes**kwargs – same optional keyword arguments that
Service.call
takes
- Usage:
>>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> gen = client.call('Account', 'getVirtualGuests', iter=True) >>> for virtual_guest in gen: ... virtual_guest['id'] ... 1234 4321
- SoftLayer.API.create_client_from_env(username=None, api_key=None, endpoint_url=None, timeout=None, auth=None, config_file=None, proxy=None, user_agent=None, transport=None, verify=True)[source]¶
Creates a SoftLayer API client using your environment.
Settings are loaded via keyword arguments, environemtal variables and config file.
- Parameters
username – an optional API username if you wish to bypass the package’s built-in username
api_key – an optional API key if you wish to bypass the package’s built in API key
endpoint_url – the API endpoint base URL you wish to connect to. Set this to API_PRIVATE_ENDPOINT to connect via SoftLayer’s private network.
proxy – proxy to be used to make API calls
timeout (integer) – timeout for API requests
auth – an object which responds to get_headers() to be inserted into the xml-rpc headers. Example: BasicAuthentication
config_file – A path to a configuration file used to load settings
user_agent – an optional User Agent to report when making API calls if you wish to bypass the packages built in User Agent string
transport – An object that’s callable with this signature: transport(SoftLayer.transports.Request)
verify (bool) – decide to verify the server’s SSL/TLS cert. DO NOT SET TO FALSE WITHOUT UNDERSTANDING THE IMPLICATIONS.
Usage:
>>> import SoftLayer >>> client = SoftLayer.create_client_from_env() >>> resp = client.call('Account', 'getObject') >>> resp['companyName'] 'Your Company'
SoftLayer.exceptions¶
Exceptions used throughout the library
- license
MIT, see LICENSE for more details.
- exception SoftLayer.exceptions.ApplicationError(fault_code, fault_string, *args)[source]¶
Application Error.
- exception SoftLayer.exceptions.IAMError(fault_code, fault_string, url=None)[source]¶
Errors from iam.cloud.ibm.com
- exception SoftLayer.exceptions.InternalError(fault_code, fault_string, *args)[source]¶
Internal Server Error.
- exception SoftLayer.exceptions.InvalidCharacter(fault_code, fault_string, *args)[source]¶
There was an invalid character.
- exception SoftLayer.exceptions.InvalidMethodParameters(fault_code, fault_string, *args)[source]¶
Invalid method paramters.
- exception SoftLayer.exceptions.MethodNotFound(fault_code, fault_string, *args)[source]¶
Method name not found.
- exception SoftLayer.exceptions.NotWellFormed(fault_code, fault_string, *args)[source]¶
Request was not well formed.
- exception SoftLayer.exceptions.RemoteSystemError(fault_code, fault_string, *args)[source]¶
System Error.
- exception SoftLayer.exceptions.SoftLayerAPIError(fault_code, fault_string, *args)[source]¶
SoftLayerAPIError is an exception raised during API errors.
Provides faultCode and faultString properties.
- exception SoftLayer.exceptions.SpecViolation(fault_code, fault_string, *args)[source]¶
There was a spec violation.
- exception SoftLayer.exceptions.TransportError(fault_code, fault_string, *args)[source]¶
Transport Error.
- exception SoftLayer.exceptions.UnsupportedEncoding(fault_code, fault_string, *args)[source]¶
Encoding not supported.
SoftLayer.decoration¶
Handy decorators to use
- license
MIT, see LICENSE for more details.
- SoftLayer.decoration.retry(ex=(<class 'SoftLayer.exceptions.ServerError'>, <class 'SoftLayer.exceptions.ApplicationError'>, <class 'SoftLayer.exceptions.RemoteSystemError'>), tries=4, delay=5, backoff=2, logger=None)[source]¶
Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
- Parameters
ex – the exception to check. may be a tuple of exceptions to check
tries – number of times to try (not retry) before giving up
delay – initial delay between retries in seconds. A random 0-5s will be added to this number to stagger calls.
backoff – backoff multiplier e.g. value of 2 will double the delay each retry
logger – logger to use. If None, print
SoftLayer.utils¶
Utility function/classes.
- license
MIT, see LICENSE for more details.
- class SoftLayer.utils.IdentifierMixin[source]¶
Mixin used to resolve ids from other names of objects.
This mixin provides an interface to provide multiple methods for converting an ‘indentifier’ to an id
- class SoftLayer.utils.NestedDict[source]¶
This helps with accessing a heavily nested dictionary.
Dictionary where accessing keys that don’t exist will return another NestedDict object.
- SoftLayer.utils.build_filter_orderby(orderby)[source]¶
Builds filters using the filter options passed into the CLI.
It only supports the orderBy option, the default value is DESC.
- SoftLayer.utils.clean_string(string)[source]¶
Returns a string with all newline and other whitespace garbage removed.
Mostly this method is used to print out objectMasks that have a lot of extra whitespace in them because making compact masks in python means they don’t look nice in the IDE.
- Parameters
string – The string to clean.
- Returns string
A string without extra whitespace.
- SoftLayer.utils.clean_time(sltime, in_format='%Y-%m-%dT%H:%M:%S%z', out_format='%Y-%m-%d %H:%M')[source]¶
Easy way to format time strings
- Parameters
sltime (string) – A softlayer formatted time string
in_format (string) – Datetime format for strptime
out_format (string) – Datetime format for strftime
- SoftLayer.utils.console_color_themes(theme)[source]¶
Colors in https://rich.readthedocs.io/en/stable/appendix/colors.html?highlight=light_pink1#standard-colors
- SoftLayer.utils.days_to_datetime(days)[source]¶
Returns the datetime value of last N days.
- Parameters
days (int) – From 0 to N days
- Returns int
The datetime of last N days or datetime.now() if days <= 0.
- SoftLayer.utils.decode_stacked(document, pos=0, decoder=<json.decoder.JSONDecoder object>)[source]¶
Used for converting CLI output to JSON datastructures. Specially for unit tests
https://stackoverflow.com/questions/27907633/how-to-extract-multiple-json-objects-from-one-file
Example:
split_output = [] # Converts Rich JSON output to actual JSON data. JSON UTIL for table in utils.decode_stacked(result.output): split_output.append(table)
- SoftLayer.utils.dict_merge(dct1, dct2)[source]¶
Recursively merges dct2 and dct1, ideal for merging objectFilter together.
- Parameters
dct1 – A dictionary
dct2 – A dictionary
- Returns
dct1 + dct2
- SoftLayer.utils.event_log_filter_between_date(start, end, utc)[source]¶
betweenDate Query filter that SoftLayer_EventLog likes
- Parameters
start (string) – lower bound date in mm/dd/yyyy format
end (string) – upper bound date in mm/dd/yyyy format
utc (string) – utc offset. Defaults to ‘+0000’
- SoftLayer.utils.event_log_filter_greater_than_date(date, utc)[source]¶
greaterThanDate Query filter that SoftLayer_EventLog likes
- Parameters
date (string) – lower bound date in mm/dd/yyyy format
utc (string) – utc offset. Defaults to ‘+0000’
- SoftLayer.utils.event_log_filter_less_than_date(date, utc)[source]¶
lessThanDate Query filter that SoftLayer_EventLog likes
- Parameters
date (string) – upper bound date in mm/dd/yyyy format
utc (string) – utc offset. Defaults to ‘+0000’
- SoftLayer.utils.format_comment(comment, max_line_length=60)[source]¶
Return a string that is length long, added a next line and keep the table format.
- Parameters
comment (string) – String you want to add next line
max_line_length (int) – max length for the string
- SoftLayer.utils.format_event_log_date(date_string, utc)[source]¶
Gets a date in the format that the SoftLayer_EventLog object likes.
- Parameters
date_string (string) – date in mm/dd/yyyy format
utc (string) – utc offset. Defaults to ‘+0000’
- SoftLayer.utils.is_ready(instance, pending=False)[source]¶
Returns True if instance is ready to be used
- Parameters
instance (Object) – Hardware or Virt with transaction data retrieved from the API
pending (bool) – Wait for ALL transactions to finish?
- Returns bool
- SoftLayer.utils.lookup(dic, key, *keys)[source]¶
A generic dictionary access helper.
This helps simplify code that uses heavily nested dictionaries. It will return None if any of the keys in *keys do not exist.
>>> lookup({'this': {'is': 'nested'}}, 'this', 'is') nested >>> lookup({}, 'this', 'is') None
- SoftLayer.utils.query_filter(query)[source]¶
Translate a query-style string to a ‘filter’.
Query can be the following formats:
- Case Insensitive
‘value’ OR ‘= value’ Contains ‘value’ OR ‘^= value’ Begins with value ‘value’ OR ‘$= value’ Ends with value ‘*value’ OR ‘_= value’ Contains value
- Case Sensitive
‘~ value’ Contains ‘!~ value’ Does not contain ‘> value’ Greater than value ‘< value’ Less than value ‘>= value’ Greater than or equal to value ‘<= value’ Less than or equal to value
- Parameters
query (string) – query string
- SoftLayer.utils.query_filter_date(start, end)[source]¶
Query filters given start and end date.
:param start:YY-MM-DD :param end: YY-MM-DD
- SoftLayer.utils.query_filter_orderby(sort='ASC')[source]¶
Returns an object filter operation for sorting
- Parameters
sort (string) – either ASC or DESC
- SoftLayer.utils.resolve_ids(identifier, resolvers)[source]¶
Resolves IDs given a list of functions.
- Parameters
identifier (string) – identifier string
resolvers (list) – a list of functions
- Returns list