Skip to content

Commit

Permalink
adding the updated changes around code and documentation optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
Twarit Verma committed Sep 3, 2024
1 parent 7c05cd7 commit beb652e
Show file tree
Hide file tree
Showing 6 changed files with 517 additions and 290 deletions.
172 changes: 162 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
python_rest_api_client
======================
# UltraDNS REST API Client for Python

A sample Python client for communicating with the UltraDNS REST API
This is a Python client for communicating with the UltraDNS REST API. It provides a simple and intuitive interface for interacting with the UltraDNS services.

Dependencies and Installation
========================
Jump To:

* [Getting Started](#Getting-Started)
* [Usage](#Usage)
* [Functionality](#Functionality)
* [API Reference](#API-Reference)
* [Contributing](#Contributing)
* [License](#License)
* [Questions](#Questions)

## Getting Started

### Dependencies and Installation

This sample code depends on the requests library, which can be found at: http://docs.python-requests.org/en/latest/

Expand All @@ -14,13 +24,155 @@ If you have pip installed, you can add the client and requests to your environme
pip install ultra_rest_client
```

Functionality
=============
Once installed, you can use the `ultra_rest_client` module in your Python scripts:

```python
from ultra_rest_client import RestApiClient
client = RestApiClient(args)
```

## Usage

### Authentication

#### Authenticating using Username and Password

```python
from ultra_rest_client import RestApiClient

client = RestApiClient(your_username, your_password)

domain = "udns-python-rest-client-test.com."

# Get Zone Metadata
print(f"Get metadata for zone {domain}: {client.get_zone_metadata(domain)}")
```

#### Authenticating using Bearer Token and Refresh Token

```python
from ultra_rest_client import RestApiClient

client = RestApiClient(your_bearer_token, your_refresh_token, use_token=True)

domain = "udns-python-rest-client-test.com."

# Get Zone Metadata
print(f"Get metadata for zone {domain}: {client.get_zone_metadata(domain)}")
```

#### Authenticating using Bearer Token

```python
from ultra_rest_client import RestApiClient

client = RestApiClient(your_bearer_token, use_token=True)

domain = "udns-python-rest-client-test.com."

# Get Zone Metadata
print(f"Get metadata for zone {domain}: {client.get_zone_metadata(domain)}")
```

### Quick Examples
This example shows a complete working python file which will create a primary zone in UltraDNS. This example highlights how to get services using client and make requests.

```python
#!/usr/bin/env python3

from ultra_rest_client import RestApiClient
import sys

def create_zone(client, domain):
"""Create a zone in UltraDNS. This function will create a zone with the name specified in the domain argument.
It uses the accounts API to get the account name. This is required to create a zone.
Args:
- client (RestApiClient): An instance of the RestApiClient class.
- domain (str): The domain name to be created.
Returns:
- dict: The response body.
"""
account_details = client.get_account_details()
account_name = account_details['accounts'][0]['accountName']
return client.create_primary_zone(account_name, domain)

def create_a_record(client, domain):
"""Create an A record in UltraDNS. This function will create an A record with the name specified in the domain
Args:
- client (RestApiClient): An instance of the RestApiClient class.
- domain (str): The domain name.
"""
return client.create_rrset(domain, "A", domain, 300, "192.0.2.1")


def create_cname_record(client, domain):
"""Create a CNAME record in UltraDNS. This function will create a CNAME record with the name specified in the domain
Args:
- client (RestApiClient): An instance of the RestApiClient class.
- domain (str): The domain name.
Returns:
- dict: The response body.
"""
return client.create_rrset(domain, "CNAME", f"www.{domain}", 300, [domain])

def delete_zone(client, domain):
"""Delete the zone from UltraDNS.
Args:
- client (RestApiClient): An instance of the RestApiClient class.
- domain (str): The domain name.
"""
client.delete_zone(domain)
return "Zone deleted Successfully"

def main():
"""The main function. This is the entry point for the script. It parses the command line arguments and calls the
create_zone, create_a_record, and create_cname_record functions."""

username = sys.argv[1]
password = sys.argv[2]
domain = "ultra-rest-client-test.com."

# Create an instance of your client
client = RestApiClient(username, password)

# Create the domain
print(f"Creating zone {domain}: {create_zone(client, domain)}")

# Create an A record for the domain
print(f"Creating an A record pointing to 192.0.2.1: {create_a_record(client, domain)}")

# Create a CNAME record for the domain
print(f"Creating a 'www' CNAME pointing to {domain}: {create_cname_record(client, domain)}")

# Delete the domain
print(f"Deleting zone {domain}: {delete_zone(client, domain)}")

if __name__ == "__main__":
main()
```

## Functionality

The sample code does not attempt to implement a client for all available UltraDNS REST API functionality. It provides access to basic functionality. Adding additional functionality should be relatively straightforward, and any contributions from the UltraDNS community would be greatly appreciated. See [sample.py](sample.py) for an example of how to use this library in your own code.

## API Reference

For detailed API reference, please refer to the UltraDNS API documentation.

## Contributing

Contributions are always welcome! Please open a pull request with your changes, or open an issue if you encounter any problems or have suggestions.

The sample code does not attempt to implement a client for all available UltraDNS REST API functionality. It provides access to basic functionality. Adding additional functionality should be relatively straightforward, and any contributions from the UltraDNS community would be greatly appreciated. See sample.py for an example of how to use this library in your own code.
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.

Questions
=========
## Questions

Please contact UltraDNS support if you have any questions or encounter any issues with this code.

136 changes: 69 additions & 67 deletions sample.py
Original file line number Diff line number Diff line change
@@ -1,103 +1,105 @@
# Copyright 2023 - Vercara. All rights reserved.
# Copyright 2024 - Vercara. All rights reserved.
# Vercara, the Vercara logo and related names and logos are registered
# trademarks, service marks or tradenames of Vercara. All other
# product names, company names, marks, logos and symbols may be trademarks
# of their respective owners.
__author__ = 'UltraDNS'

import ultra_rest_client
from ultra_rest_client import RestApiClient
import sys
import time

if len(sys.argv) != 5 and len(sys.argv) != 3:
raise Exception("Expected use: python sample.py username password [use_http host:port]")
if len(sys.argv) != 6 and len(sys.argv) != 3:
raise Exception("Expected use: python sample.py username password [use_token use_http host:port]")

username = sys.argv[1]
password = sys.argv[2]
use_http = 'False'
use_token = 'False'
domain = 'restapi.ultradns.com'

if len(sys.argv) == 5:
use_http = sys.argv[3]
domain = sys.argv[4]
if len(sys.argv) == 6:
use_token = sys.argv[3]
use_http = sys.argv[4]
domain = sys.argv[5]

c = ultra_rest_client.RestApiClient(username, password, 'True' == use_http, domain)
print 'version %s' % c.version()
print 'status %s' % c.status()
account_details = c.get_account_details()
account_name = account_details[u'accounts'][0][u'accountName']
print 'account name %s' % account_name
print 'get zone metadata %s' % c.get_zone_metadata_v3("mjoy-example.com.")
print 'get first 5 primary zones with mjoy: %s' % c.get_zones_v3(limit=5, sort="NAME", reverse=False, q={"name":"mjoy", "zone_type":"PRIMARY"})
print '\n'
print 'get first 5 secondary zones: %s' % c.get_zones_v3(limit=5, sort="NAME", reverse=False, q={"zone_type":"SECONDARY"})
print '\n'
print 'get all zones with 20 zones per page. First page is returned by default: %s' % c.get_zones_v3(limit=20, q={"zone_status":"ALL"})
print '\n'
print 'get next page of zones with 20 zones per page. Cursor returned by above request is used: %s' % c.get_zones_v3(limit=20, cursor='MDAwMC10YW52aS1zaWduZWQuY29tLjpORVhU', q={"zone_status":"ALL"})
print 'create primary zone result %s' % c.create_primary_zone(account_name, "foo.invalid.")
print 'get zone metadata %s' % c.get_zone_metadata("foo.invalid.")
print 'delete zone %s ' % c.delete_zone("foo.invalid.")
all_zones = c.get_zones_of_account(account_name, offset=0, limit=5, reverse=True)
print all_zones
first_zone_name = all_zones[u'zones'][0][u'properties'][u'name']
print 'zone name %s ' % first_zone_name
print 'get_rrsets %s ' % c.get_rrsets(first_zone_name)
print 'create_rrset %s ' % c.create_rrset(first_zone_name, "A", "foo", 300, "1.2.3.4")
print 'get_rrsets %s ' % c.get_rrsets(first_zone_name)
print 'get_rrsets_by_type %s ' % c.get_rrsets_by_type(first_zone_name, "A")
print 'edit_rrset %s ' % c.edit_rrset(first_zone_name, "A", "foo", 100, ["10.20.30.40"])
print 'get_rrsets %s ' % c.get_rrsets(first_zone_name)
print 'get_rrsets_by_type %s ' % c.get_rrsets_by_type(first_zone_name, "A")
print 'get_rrsets_by_type_owner %s ' % c.get_rrsets_by_type_owner(first_zone_name, "A", "foo")
print 'delete_rrset %s ' % c.delete_rrset(first_zone_name, "A", "foo")
print 'get_rrsets %s ' % c.get_rrsets(first_zone_name)
print 'get_rrsets_by_type %s ' % c.get_rrsets_by_type(first_zone_name, "A")
print 'get_rrsets_by_type_owner %s ' % c.get_rrsets_by_type_owner(first_zone_name, "A", "foo")
print 'batch delete %s ' % c.batch([
{'method': 'DELETE', 'uri': '/v1/zones/' + first_zone_name + '/rrsets/A/foo2'},
{'method': 'DELETE', 'uri': '/v1/zones/' + first_zone_name + '/rrsets/A/foo3'},
])
test_zone_name='udns-python-rest-client-test.com.'

print 'get_rrsets_by_type %s ' % c.get_rrsets_by_type(first_zone_name, "A")
print 'get_rrsets_by_type_owner %s ' % c.get_rrsets_by_type_owner(first_zone_name, "A", "foo2")
print 'batch create %s ' % c.batch([
{'method': 'POST', 'uri': '/v1/zones/' + first_zone_name + '/rrsets/A/foo2', 'body': {'ttl': 100, 'rdata': ['2.4.6.8']}},
{'method': 'POST', 'uri': '/v1/zones/' + first_zone_name + '/rrsets/A/foo3', 'body': {'ttl': 100, 'rdata': ['20.40.60.80']}},
])
print 'get_rrsets_by_type %s ' % c.get_rrsets_by_type(first_zone_name, "A")
print 'get_rrsets_by_type_owner %s ' % c.get_rrsets_by_type_owner(first_zone_name, "A", "foo2")
print 'batch delete %s ' % c.batch([
{'method': 'DELETE', 'uri': '/v1/zones/' + first_zone_name + '/rrsets/A/foo2'},
{'method': 'DELETE', 'uri': '/v1/zones/' + first_zone_name + '/rrsets/A/foo3'},
])
print 'get_rrsets_by_type %s ' % c.get_rrsets_by_type(first_zone_name, "A")
print 'get_rrsets_by_type_owner %s ' % c.get_rrsets_by_type_owner(first_zone_name, "A", "foo2")
client = RestApiClient(username, password, 'True' == use_token, 'True' == use_http, domain)
print('version %s' % client.version())
print('status %s' % client.status())
account_details = client.get_account_details()
account_name = account_details['accounts'][0]['accountName']
print('account name %s' % account_name)
print('get zone metadata %s' % client.get_zone_metadata_v3("mjoy-example.com."))
print('sleeping for 20 mins')
print('get first 5 primary zones with mjoy: %s' % client.get_zones_v3(limit=5, sort="NAME", reverse=False, q={"name":"mjoy", "zone_type":"PRIMARY"}))
print('\n')
print('get first 5 secondary zones: %s' % client.get_zones_v3(limit=5, sort="NAME", reverse=False, q={"zone_type":"SECONDARY"}))
print('\n')
print('get all zones with 20 zones per page. First page is returned by default: %s' % client.get_zones_v3(limit=20, q={"zone_status":"ALL"}))
print('\n')
print('get next page of zones with 20 zones per page. Cursor returned by above request is used: %s' % client.get_zones_v3(limit=20, cursor='MDAwMC10YW52aS1zaWduZWQuY29tLjpORVhU', q={"zone_status":"ALL"}))
print('create primary zone result %s' % client.create_primary_zone(account_name, "foo.invalid."))
print('get zone metadata %s' % client.get_zone_metadata("foo.invalid."))
print('delete zone %s ' % client.delete_zone("foo.invalid."))
print('zone name %s ' % test_zone_name)
print('get_rrsets %s ' % client.get_rrsets(test_zone_name))
print('create_rrset %s ' % client.create_rrset(test_zone_name, "A", "foo", 300, "1.2.3.4"))
print('get_rrsets %s ' % client.get_rrsets(test_zone_name))
print('get_rrsets_by_type %s ' % client.get_rrsets_by_type(test_zone_name, "A"))
print('edit_rrset %s ' % client.edit_rrset(test_zone_name, "A", "foo", 100, ["10.20.30.40"]))
print('get_rrsets %s ' % client.get_rrsets(test_zone_name))
print('get_rrsets_by_type %s ' % client.get_rrsets_by_type(test_zone_name, "A"))
print('get_rrsets_by_type_owner %s ' % client.get_rrsets_by_type_owner(test_zone_name, "A", "foo"))
print('delete_rrset %s ' % client.delete_rrset(test_zone_name, "A", "foo"))
print('get_rrsets %s ' % client.get_rrsets(test_zone_name))
print('get_rrsets_by_type %s ' % client.get_rrsets_by_type(test_zone_name, "A"))
print('get_rrsets_by_type_owner %s ' % client.get_rrsets_by_type_owner(test_zone_name, "A", "foo"))
print('batch delete %s ' % client.batch([
{'method': 'DELETE', 'uri': '/v1/zones/' + test_zone_name + '/rrsets/A/foo2'},
{'method': 'DELETE', 'uri': '/v1/zones/' + test_zone_name + '/rrsets/A/foo3'},
]))

print('get_rrsets_by_type %s ' % client.get_rrsets_by_type(test_zone_name, "A"))
print('get_rrsets_by_type_owner %s ' % client.get_rrsets_by_type_owner(test_zone_name, "A", "foo2"))
print('batch create %s ' % client.batch([
{'method': 'POST', 'uri': '/v1/zones/' + test_zone_name + '/rrsets/A/foo2', 'body': {'ttl': 100, 'rdata': ['2.4.6.8']}},
{'method': 'POST', 'uri': '/v1/zones/' + test_zone_name + '/rrsets/A/foo3', 'body': {'ttl': 100, 'rdata': ['20.40.60.80']}},
]))
print('get_rrsets_by_type %s ' % client.get_rrsets_by_type(test_zone_name, "A"))
print('get_rrsets_by_type_owner %s ' % client.get_rrsets_by_type_owner(test_zone_name, "A", "foo2"))
print('batch delete %s ' % client.batch([
{'method': 'DELETE', 'uri': '/v1/zones/' + test_zone_name + '/rrsets/A/foo2'},
{'method': 'DELETE', 'uri': '/v1/zones/' + test_zone_name + '/rrsets/A/foo3'},
]))
print('get_rrsets_by_type %s ' % client.get_rrsets_by_type(test_zone_name, "A"))
print('get_rrsets_by_type_owner %s ' % client.get_rrsets_by_type_owner(test_zone_name, "A", "foo2"))

#getting zones with q, sort, offset, limit
print 'get first 5 primary zones with j: %s' % c.get_zones(offset=0, limit=5, sort="NAME", reverse=False, q={"name":"j", "zone_type":"PRIMARY"})
print('get first 5 primary zones with j: %s' % client.get_zones(offset=0, limit=5, sort="NAME", reverse=False, q={"name":"j", "zone_type":"PRIMARY"}))

#creating a zone with upload
result = c.create_primary_zone_by_upload(account_name, 'sample.client.me.', '../zone.txt')
print 'create zone via upload: %s' % result
result = client.create_primary_zone_by_upload(account_name, 'sample.client.me.', './zone.txt')
print('create zone via upload: %s' % result)

# check the task status
while True:
task_status = c.get_task(result['task_id'])
print 'task status: %s ' % c.get_task(result['task_id'])
task_status = client.get_task(result['task_id'])
print('task status: %s ' % client.get_task(result['task_id']))
if task_status['code'] != 'IN_PROCESS':
break
time.sleep(1)


#check all task status
print 'all task status: %s ' % c.get_all_tasks()
print('all task status: %s ' % client.get_all_tasks())

#delete task status
print 'delete task status: %s ' % c.clear_task(result['task_id'])
print('delete task status: %s ' % client.clear_task(result['task_id']))

#export zonefile in bind format
print('export zone: %s ' % c.export_zone('sample.client.me.'))
print(('export zone: %s ' % client.export_zone('sample.client.me.')))

#delete the zone
print 'delete zone: %s ' % c.delete_zone('sample.client.me.')
print('delete zone: %s ' % client.delete_zone('sample.client.me.'))
Loading

0 comments on commit beb652e

Please sign in to comment.