doapi Class¶
-
class
doapi.doapi(api_token, endpoint='https://api.digitalocean.com', timeout=None, wait_interval=2, wait_time=None, per_page=None)[source]¶ The primary class for interacting with the DigitalOcean API, used for creating and fetching resources. The resource objects returned by these methods have methods of their own for manipulating them individually.
Parameters: - api_token (str) – the API token to use for authentication
- endpoint (string) – the URL relative to which requests will be made
- timeout (float, tuple, or
None) – thetimeoutvalue to use when making requests - wait_interval (number) – the default number of seconds that “wait” operations will sleep for between requests
- wait_time – the default number of seconds after which “wait”
operations will return, or
Noneor a negative number to wait indefinitely - per_page (integer or
None) – the default number of objects thatpaginate()will fetch on each request, orNoneto leave unspecified
-
DEFAULT_ENDPOINT= 'https://api.digitalocean.com'¶ The official DigitalOcean API endpoint
-
api_token= None¶ The API token used for authentication
-
endpoint= None¶ The API endpoint URL relative to which requests will be made
-
timeout= None¶ The
timeoutvalue to use when making requests; see the requests documentation for more information
-
wait_interval= None¶ The default number of seconds that
wait_droplets(),wait_actions(), and thewaitmethods ofAction,Droplet,FloatingIP, andImagewill sleep for between requests
-
wait_time= None¶ The default number of seconds after which “wait” operations will return, or
Noneor a negative number to wait indefinitely
-
per_page= None¶ The default number of objects that
paginate()will fetch on each request, orNoneto leave unspecified
-
last_response= None¶ The
requests.Responseobject returned for the most recent request, orNoneif no requests have been made yet
-
last_meta= None¶ The
metafield in the body of the most recent response, orNoneif there was no such field, no requests have been made yet, or the last response was an error
-
session= None¶ The
requests.Sessionobject through which all requests are performed
-
close()[source]¶ Close the session. All API methods will be unusable after calling this method.
Returns: None
-
request(url, params=None, data=None, method='GET')[source]¶ Perform an HTTP request and return the response body as a decoded JSON value
Parameters: - url (str) – the URL to make the request of. If
urlbegins with a forward slash,endpointis prepended to it; otherwise,urlis treated as an absolute URL. - params (dict) – parameters to add to the URL’s query string
- data – a value to send in the body of the request. If
datais not a string, it will be serialized as JSON before sending; either way, the Content-Type header of the request will be set to application/json. Note that adatavalue ofNonemeans “Don’t send any data”; to send an actualNonevalue, convert it to JSON (i.e., the string"null") first. - method (str) – the HTTP method to use:
"GET","POST","PUT", or"DELETE"(case-insensitive); default:"GET"
Returns: a decoded JSON value, or
Noneif no data was returnedReturn type: Raises: - ValueError – if
methodis an invalid value - DOAPIError – if the API endpoint replies with an error
- url (str) – the URL to make the request of. If
-
last_rate_limit¶ A
dictof the rate limit information returned in the most recent response, orNoneif no requests have been made yet. Thedictconsists of all headers whose names begin with"RateLimit"(case insensitive).The DigitalOcean API specifies the following rate limit headers:
Variables: - RateLimit-Limit (string) – the number of requests that can be made per hour
- RateLimit-Remaining (string) – the number of requests remaining until the limit is reached
- RateLimit-Reset (string) – the Unix timestamp for the time when the oldest request will expire from rate limit consideration
-
paginate(url, key, params=None)[source]¶ Fetch a sequence of paginated resources from the API endpoint. The initial request to
urland all subsequent requests must respond with a JSON object; the field specified bykeymust be a list, whose elements will be yielded, and the next request will be made to the URL in the.links.pages.nextfield until the responses no longer contain that field.Parameters: - url (str) – the URL to make the initial request of. If
urlbegins with a forward slash,endpointis prepended to it; otherwise,urlis treated as an absolute URL. - key (str) – the field on each page containing a list of values to yield
- params (dict) – parameters to add to the initial URL’s query
string. A
"per_page"parameter may be included to override the defaultper_pagesetting.
Return type: generator of decoded JSON values
Raises: - ValueError – if a response body is not an object or
keyis not one of its keys - DOAPIError – if the API endpoint replies with an error
- url (str) – the URL to make the initial request of. If
-
fetch_droplet(obj)[source]¶ Fetch a droplet by ID number
Parameters: obj (integer, dict, orDroplet) – the ID of the droplet, adictwith an"id"field, or aDropletobject (to re-fetch the same droplet)Return type: Droplet Raises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_droplets(tag_name=None)[source]¶ Returns a generator that yields all of the droplets belonging to the account
Changed in version 0.2.0:
tag_nameparameter addedParameters: tag_name (string or Tag) – if non-None, only droplets with the given tag are returnedReturn type: generator of DropletsRaises: DOAPIError – if the API endpoint replies with an error
-
create_droplet(name, image, size, region, ssh_keys=None, backups=None, ipv6=None, private_networking=None, user_data=None, **kwargs)[source]¶ Create a new droplet. All fields other than
name,image,size, andregionare optional and will be omitted from the API request if not specified.The returned
Dropletobject will represent the droplet at the moment of creation; the actual droplet may not be active yet and may not have even been assigned an IP address. To wait for the droplet to activate, use theDroplet’swait()method.Parameters: - name (str) – a name for the droplet
- image (integer, string, or
Image) – the image ID, slug, orImageobject representing the base image to use for the droplet - size (string or
Size) – the slug orSizeobject representing the size of the new droplet - region (string or
Region) – the slug orRegionobject representing the region in which to create the droplet - ssh_keys (iterable) – an iterable of SSH key resource IDs, SSH key
fingerprints, and/or
SSHKeyobjects specifying the public keys to add to the new droplet’s/root/.ssh/authorized_keysfile - backups (bool) – whether to enable automatic backups on the new droplet
- ipv6 (bool) – whether to enable IPv6 on the new droplet
- private_networking (bool) – whether to enable private networking for the new droplet
- user_data (str) – a string of user data/metadata for the droplet
- kwargs – additional fields to include in the API request
Returns: the new droplet resource
Return type: Raises: DOAPIError – if the API endpoint replies with an error
-
create_multiple_droplets(names, image, size, region, ssh_keys=None, backups=None, ipv6=None, private_networking=None, user_data=None, **kwargs)[source]¶ Create multiple new droplets at once with the same image, size, etc., differing only in name. All fields other than
names,image,size, andregionare optional and will be omitted from the API request if not specified.The returned
Dropletobjects will represent the droplets at the moment of creation; the actual droplets may not be active yet and may not have even been assigned IP addresses. To wait for the droplets to activate, use theirwait()method orwait_droplets.Parameters: - names (list of strings) – the names for the new droplets
- image (integer, string, or
Image) – the image ID, slug, orImageobject representing the base image to use for the droplets - size (string or
Size) – the slug orSizeobject representing the size of the new droplets - region (string or
Region) – the slug orRegionobject representing the region in which to create the droplets - ssh_keys (iterable) – an iterable of SSH key resource IDs, SSH key
fingerprints, and/or
SSHKeyobjects specifying the public keys to add to the new droplets’/root/.ssh/authorized_keysfiles - backups (bool) – whether to enable automatic backups on the new droplets
- ipv6 (bool) – whether to enable IPv6 on the new droplets
- private_networking (bool) – whether to enable private networking for the new droplets
- user_data (str) – a string of user data/metadata for the droplets
- kwargs – additional fields to include in the API request
Returns: the new droplet resources
Return type: list of
DropletsRaises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_droplet_neighbors()[source]¶ Returns a generator of all sets of multiple droplets that are running on the same physical hardware
Return type: generator of lists of DropletsRaises: DOAPIError – if the API endpoint replies with an error
-
wait_droplets(droplets, status=None, locked=None, wait_interval=None, wait_time=None)[source]¶ Poll the server periodically until all droplets in
dropletshave reached some final state, yielding eachDroplet’s final value when it’s done. Ifstatusis non-None,wait_dropletswill wait for each droplet’sstatusfield to equal the given value. Iflockedis non-None,wait_dropletswill wait for each droplet’slockedfield to equal (the truth value of) the given value. Exactly one ofstatusandlockedmust be non-None.If
wait_timeis exceeded, aWaitTimeoutError(containing any remaining in-progress droplets) is raised.If a
KeyboardInterruptis caught, any remaining droplets are returned immediately without waiting for completion.Changed in version 0.2.0: Raises
WaitTimeoutErroron timeoutChanged in version 0.2.0:
lockedparameter addedChanged in version 0.2.0: No longer waits for actions to complete
Parameters: - droplets (iterable) – an iterable of
Droplets and/or other values that are acceptable arguments tofetch_droplet() - status (string or
None) – When non-None, the desired value for thestatusfield of eachDroplet, which should be one ofDroplet.STATUS_ACTIVE,Droplet.STATUS_ARCHIVE,Droplet.STATUS_NEW, andDroplet.STATUS_OFF. (For the sake of forwards-compatibility, any other value is accepted as well.) - locked (
boolorNone) – When non-None, the desired value for thelockedfield of eachDroplet - wait_interval (number) – how many seconds to sleep between
requests; defaults to
wait_intervalif not specified orNone - wait_time (number) – the total number of seconds after which the
method will raise an error if any droplets have not yet completed,
or a negative number to wait indefinitely; defaults to
wait_timeif not specified orNone
Return type: generator of
DropletsRaises: - TypeError – if both or neither of
status&lockedare defined - DOAPIError – if the API endpoint replies with an error
- WaitTimeoutError – if
wait_timeis exceeded
- droplets (iterable) – an iterable of
-
fetch_action(obj)[source]¶ Fetch an action by ID number
Parameters: obj (integer, dict, orAction) – the ID of the action, adictwith an"id"field, or anActionobject (to re-fetch the same action)Return type: Action Raises: DOAPIError – if the API endpoint replies with an error
-
fetch_last_action()[source]¶ Fetch the most recent action performed on the account, or
Noneif no actions have been performed yet. If multiple actions were triggered simultaneously, the choice of which to return is undefined.Return type: ActionorNoneRaises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_actions()[source]¶ Returns a generator that yields all of the actions associated with the account
Return type: generator of ActionsRaises: DOAPIError – if the API endpoint replies with an error
-
wait_actions(actions, wait_interval=None, wait_time=None)[source]¶ Poll the server periodically until all actions in
actionshave either completed or errored out, yielding eachAction’s final value as it ends.If
wait_timeis exceeded, aWaitTimeoutError(containing any remaining in-progress actions) is raised.If a
KeyboardInterruptis caught, any remaining actions are returned immediately without waiting for completion.Changed in version 0.2.0: Raises
WaitTimeoutErroron timeoutParameters: - actions (iterable) – an iterable of
Actions and/or other values that are acceptable arguments tofetch_action() - wait_interval (number) – how many seconds to sleep between
requests; defaults to
wait_intervalif not specified orNone - wait_time (number) – the total number of seconds after which the
method will raise an error if any actions have not yet completed,
or a negative number to wait indefinitely; defaults to
wait_timeif not specified orNone
Return type: generator of
ActionsRaises: - DOAPIError – if the API endpoint replies with an error
- WaitTimeoutError – if
wait_timeis exceeded
- actions (iterable) – an iterable of
-
wait_actions_on_objects(objects, wait_interval=None, wait_time=None)[source]¶ New in version 0.2.0.
Poll the server periodically until the most recent action on each resource in
objectshas finished, yielding each resource’s final state when the corresponding action is done.If
wait_timeis exceeded, aWaitTimeoutError(containing any remaining in-progress actions) is raised.If a
KeyboardInterruptis caught, any remaining actions are returned immediately without waiting for completion.Parameters: - objects (iterable) – an iterable of resource objects that have
fetch_last_actionmethods - wait_interval (number) – how many seconds to sleep between
requests; defaults to
wait_intervalif not specified orNone - wait_time (number) – the total number of seconds after which the
method will raise an error if any actions have not yet completed,
or a negative number to wait indefinitely; defaults to
wait_timeif not specified orNone
Return type: generator of objects
Raises: - DOAPIError – if the API endpoint replies with an error
- WaitTimeoutError – if
wait_timeis exceeded
- objects (iterable) – an iterable of resource objects that have
-
fetch_ssh_key(obj)[source]¶ Fetch an SSH public key by ID number or fingerprint
Parameters: obj (integer, string, dict, orSSHKey) – the ID or fingerprint of the SSH key, adictwith an"id"or"fingerprint"field, or anSSHKeyobject (to re-fetch the same SSH key)Return type: SSHKey Raises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_ssh_keys()[source]¶ Returns a generator that yields all of the SSH public keys belonging to the account
Return type: generator of SSHKeysRaises: DOAPIError – if the API endpoint replies with an error
-
create_ssh_key(name, public_key, **kwargs)[source]¶ Add a new SSH public key resource to the account
Parameters: Returns: the new SSH key resource
Return type: Raises: DOAPIError – if the API endpoint replies with an error
-
fetch_image(obj)[source]¶ Fetch an image by ID number
Parameters: obj (integer, dict, orImage) – the ID of the image, adictwith an"id"field, or anImageobject (to re-fetch the same image)Return type: Image Raises: DOAPIError – if the API endpoint replies with an error
-
fetch_image_by_slug(slug)[source]¶ Fetch an image by its slug
Parameters: slug (str) – the slug of the image to fetch Return type: Image Raises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_images(type=None, private=None)[source]¶ Returns a generator that yields all of the images available to the account
Parameters: Return type: generator of
ImagesRaises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_distribution_images()[source]¶ Returns a generator that yields all of the distribution images available to the account
Return type: generator of ImagesRaises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_application_images()[source]¶ Returns a generator that yields all of the application images available to the account
Return type: generator of ImagesRaises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_private_images()[source]¶ Returns a generator that yields all of the user’s private images
Return type: generator of ImagesRaises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_regions()[source]¶ Returns a generator that yields all of the regions available to the account
Return type: generator of RegionsRaises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_sizes()[source]¶ Returns a generator that yields all of the sizes available to the account
Return type: generator of SizesRaises: DOAPIError – if the API endpoint replies with an error
-
fetch_account()[source]¶ Returns an
Accountobject representing the user’s accountReturn type: Account Raises: DOAPIError – if the API endpoint replies with an error
-
fetch_domain(obj)[source]¶ Fetch a domain by FQDN
Parameters: obj (string, dict, orDomain) – the domain name, adictwith a"name"field, or aDomainobject (to re-fetch the same domain)Return type: Domain Raises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_domains()[source]¶ Returns a generator that yields all of the domains belonging to the account
Return type: generator of DomainsRaises: DOAPIError – if the API endpoint replies with an error
-
create_domain(name, ip_address, **kwargs)[source]¶ Add a new domain name resource to the account.
Note that this method does not actually register a new domain name; it merely configures DigitalOcean’s nameservers to provide DNS resolution for the domain. See How To Set Up a Host Name with DigitalOcean for more information.
Parameters: - name (str) – the domain name to add
- ip_address (string or
FloatingIP) – the IP address to which the domain should point - kwargs – additional fields to include in the API request
Returns: the new domain resource
Return type: Raises: DOAPIError – if the API endpoint replies with an error
-
fetch_floating_ip(obj)[source]¶ Fetch a floating IP
Parameters: obj (string, integer, dict, orFloatingIP) – an IP address (as a string or 32-bit integer), adictwith an"ip"field, or aFloatingIPobject (to re-fetch the same floating IP)Return type: FloatingIP Raises: DOAPIError – if the API endpoint replies with an error
-
fetch_all_floating_ips()[source]¶ Returns a generator that yields all of the floating IPs belonging to the account
Return type: generator of FloatingIPsRaises: DOAPIError – if the API endpoint replies with an error
-
create_floating_ip(droplet_id=None, region=None, **kwargs)[source]¶ Create a new floating IP assigned to a droplet or reserved to a region. Either
droplet_idorregionmust be specified, but not both.The returned
FloatingIPobject will represent the IP at the moment of creation; if the IP address is supposed to be assigned to a droplet, the assignment may not have been completed at the time the object is returned. To wait for the assignment to complete, use theFloatingIP’swait_for_action()method.Parameters: Returns: the new floating IP
Return type: Raises: - TypeError – if both
droplet_id®ionor neither of them are defined - DOAPIError – if the API endpoint replies with an error
- TypeError – if both
-
fetch_tag(obj)[source]¶ New in version 0.2.0.
Fetch a tag by name
Parameters: obj (string, dict, orTag) – the name of the tag, adictwith a"name"field, or aTagobject (to re-fetch the same tag)Return type: Tag Raises: DOAPIError – if the API endpoint replies with an error
New in version 0.2.0.
Returns a generator that yields all of the tags belonging to the account
Return type: generator of TagsRaises: DOAPIError – if the API endpoint replies with an error
-
create_tag(name)[source]¶ New in version 0.2.0.
Add a new tag resource to the account
Parameters: name (str) – the name of the new tag Return type: Tag Raises: DOAPIError – if the API endpoint replies with an error