Merge pull request #8 from flowroute/doc-updates

Doc updates
e911_addr
Maria Bermudez 7 years ago committed by GitHub
commit 8c26653985
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 616
      README.md
  2. 6
      cnam_demo.py
  3. 220
      demo_with_comments.py
  4. 52
      flowroutenumbersandmessaging/controllers/cnams_controller.py

@ -1,7 +1,7 @@
Flowroute Python Library v3 Flowroute Python Library v3
===================== =====================
The Flowroute Python library v3 provides methods for interacting with [Numbers v2](https://developer.flowroute.com/api/numbers/v2.0/) and [Messages v2.1](https://developer.flowroute.com/api/messages/v2.1/) of the [Flowroute](https://www.flowroute.com) API. The Flowroute Python Library v3 provides methods for interacting with [Numbers v2](https://developer.flowroute.com/api/numbers/v2.0/) and [Messages v2.1](https://developer.flowroute.com/api/messages/v2.1/) of the [Flowroute](https://www.flowroute.com) API.
**Topics** **Topics**
@ -35,24 +35,24 @@ The Flowroute Python library v3 provides methods for interacting with [Numbers v
* [look_up_a_set_of_messagesstart_date](#look_up_a_set_of_messagesstart_date) * [look_up_a_set_of_messagesstart_date](#look_up_a_set_of_messagesstart_date)
* [look_up_a_message_detail_record](#look_up_a_message_detail_recordmessage_id) * [look_up_a_message_detail_record](#look_up_a_message_detail_recordmessage_id)
* [E911 Address Management](#e911-management) * [E911 Address Management](#e911-address-management)
* [list_e911s](#) * [list_e911s](#list_e911s)
* [get_e911](#) * [get_e911](#get_e911e911_id)
* [validate_address](#) * [validate_address](#validate_addresse911_attributes)
* [create_address](#) * [create_address](#create_addresse911_attributes)
* [update_address](#) * [update_address](#e911_ide911_attribute)
* [associate](#) * [associate](#associatee911_id-number_id)
* [list_dids_for_e911](#) * [list_dids_for_e911](#list_dids_for_e911e911_id)
* [disconnect](#) * [disconnect](#disconnectnumber_id)
* [delete_address](#) * [delete_address](#delete_addresse911_id)
* [CNAM Record Management](#cnam-management) * [CNAM Record Management](#cnam-management)
* [list_cnams](#) * [list_cnams](#list_cnams)
* [get_cnam](#) * [get_cnam](#get_cnamcnam_id)
* [create_cnam_record](#) * [create_cnam_record](#create_cnam_recordcnam_value)
* [associate_cnam](#) * [associate_cnam](#associatecnam_id-number_id)
* [unassociate_cnam](#) * [unassociate_cnam](#unassociate_cnamnumber_id)
* [remove_cnam](#) * [remove_cnam](#remove_cnamcnam_id)
* [Messaging](#messaging) * [Messaging](#messaging)
* [send_a_message](#send_a_messagemessage_body) * [send_a_message](#send_a_messagemessage_body)
@ -91,7 +91,7 @@ Depending on your `pip` permissions, you may be required to preface each `pip` c
* * * * * *
Usage Usage
------------ ------------
In Flowroute's approach to building the Python library v3, HTTP requests are handled by controllers named after the API resources they represent: **Numbers**, **Routes**, **E911s**, **CNAMs**, and **Messages**. These controllers contain the methods used to perform messaging, number management, route management, E911 address management, and CNAM record management within the Python library. In Flowroute's approach to building the Python Library v3, HTTP requests are handled by controllers named after the API resources they represent: **Numbers**, **Routes**, **E911s**, **CNAMs**, and **Messages**. These controllers contain the methods used to perform messaging, number management, route management, E911 address management, and CNAM record management within the Python library.
## Controllers ## Controllers
@ -128,13 +128,14 @@ Contains the methods required to send an MMS or SMS, and review a specific Messa
Contains all of the methods necessary to create, update, and validate new and existing E911 addresses, retrieve all of the E911 records, activate and deactive E911 service for long code and toll-free numbers on your account, view all of the phone numbers associated with an E911 record, and remove an E911 address from your account once it is no longer associated with any of your Flowroute phone numbers. Contains all of the methods necessary to create, update, and validate new and existing E911 addresses, retrieve all of the E911 records, activate and deactive E911 service for long code and toll-free numbers on your account, view all of the phone numbers associated with an E911 record, and remove an E911 address from your account once it is no longer associated with any of your Flowroute phone numbers.
* [list\_e911s()](#list_e911s) \- Returns a list of all E911 records on your account by default. All request parameters are optional. If you don't specify a limit, results are limited to the first 10 items. * [list\_e911s()](#list_e911s) \- Returns a list of all E911 records on your account by default. All request parameters are optional. If you don't specify a limit, results are limited to the first 10 items.
* [get\_e911(e911\_id)](#get_e911) \- Returns details on a specified E911 record. * [get\_e911(e911\_id)](#get_e911e911_id) \- Returns details on a specified E911 record.
* [validate\_address(e911\_attributes)](#validate_address) \- Lets you validate new and existing E911 addresses on your account. * [validate\_address(e911\_attributes)](#validate_addresse911_attributes) \- Lets you validate new and existing E911 addresses on your account.
* [create\_address(e911\_attributes)](#create_address) \- Lets you create and validate an E911 address within the US and Canada which can then be assigned to any of the long code or toll­free numbers on your account. To assign an E911 address to your number, see the [associate](#associate) method. * [create\_address(e911\_attributes)](#create_addresse911_attributes) \- Lets you create and validate an E911 address within the US and Canada which can then be assigned to any of the long code or toll­free numbers on your account. To assign an E911 address to your number, see the [associate](#associatee911_id-number_id) method.
* [update\_address(e911\_id, e911\_attributes)](#update_address) \- Lets you update and validate an existing E911 address on your account. You must create the E911 address first by following the [create\_address](#create_address) method. * [update\_address(e911\_id, e911\_attributes)](#update_addresse911_id-e911_attributes) \- Lets you update and validate an existing E911 address on your account. You must create the E911 address first by following the [create\_address](#create_address) method.
* [associate(e911\_id, number\_id)](#associate) \- Lets you update and validate an existing E911 address on your account. You must create the E911 address first by following the [create\_address](#create_address) method. * [associate(e911\_id, number\_id)](#associatee911_id-number_id) \- Lets you assign a valid E911 address to a specific long code or toll-free phone number in your account. This method calls an endpoint which does not return an error for subsequent attempts at associating a phone number with the same E911 record. The E911 record assignment charge only occurs on the first successful attempt. Note that you can later assign a different `e911_id` to the same phone number and will be charged accordingly.
* [disconnect(number\_id)](#disconnect) \- Lets you deactivate the current E911 service for your phone number. * [list\_dids\_for\_e911(e911\_id)](#list_dids_for_e911number_id) \- Returns a list of your Flowroute long code or toll-free phone numbers associated with a specified E911 record.
* [delete\_address(e911\_id)](#list_dids_for_e911) \- Lets you delete an E911 address associated with your account. You must remove all phone number associations first before you can successfully delete the specified E911 record. * [disconnect(number\_id)](#disconnectnumber_id) \- Lets you deactivate the current E911 service for your phone number.
* [delete\_address(e911\_id)](#delete_addresse911_id) \- Lets you delete an E911 address associated with your account. You must remove all phone number associations first before you can successfully delete the specified E911 record.
### CNAMsController ### CNAMsController
@ -146,7 +147,7 @@ Contains all of the methods necessary to create and delete CNAM records, view al
* [unassociate(number\_id)](#disconnect) \- Lets you unassign a CNAM record associated with a specified long code number on your account without deleting the CNAM record itself. * [unassociate(number\_id)](#disconnect) \- Lets you unassign a CNAM record associated with a specified long code number on your account without deleting the CNAM record itself.
* [remove\_cnam(cnam\_id)](#remove_cnam) \- Lets you delete a CNAM record from your account. Note that this will automatically disassociate all numbers associated with the deleted CNAM record. * [remove\_cnam(cnam\_id)](#remove_cnam) \- Lets you delete a CNAM record from your account. Note that this will automatically disassociate all numbers associated with the deleted CNAM record.
The following shows an example of a single Python file that imports the Flowroute API client and all the required modules. The Python library v3 comes with three example demo files — **number_route_message_demo.py**, **e911_demo.py**, **cnam_demo.py** — files that you can edit and run for demonstration and testing purposes. The following shows an example of a single Python file that imports the Flowroute API client and all the required modules. The Python Library v3 comes with three example demo files — **number_route_message_demo.py**, **e911_demo.py**, **cnam_demo.py** — files that you can edit and run for demonstration and testing purposes.
```python ```python
import pprint import pprint
@ -167,7 +168,7 @@ basic_auth_password = os.environ.get('FR_SECRET_KEY')
mobile_number = "YOUR_MOBILE_NUMBER" mobile_number = "YOUR_MOBILE_NUMBER"
``` ```
#### Instantiate API Client and Controllers #### Instantiate API Client and Controllers
Next, instantiate the API Client and its controllers. Next, instantiate the API Client and its controllers. In the following example, we are only instantiating the necessary controllers for the Numbers,Messages, and Routes resources. The E911 and CNAM demo files come with their own set of required controllers to interact with the associated methods for E911 and CNAM record management.
```python ```python
# Instantiate API client and create controllers for Numbers, Messages, and Routes # Instantiate API client and create controllers for Numbers, Messages, and Routes
@ -181,7 +182,9 @@ The following section will demonstrate the capabilities of Numbers v2, Messaging
### Number Management ### Number Management
The Flowroute Python library v3 allows you to make HTTP requests to the `numbers` resource of Flowroute API v2: `https://api.flowroute.com/v2/numbers` The Flowroute Python Library v3 allows you to make HTTP requests to the `numbers` resource of Flowroute API v2: `https://api.flowroute.com/v2/numbers`.
All of the number management methods are encapsulated in `number_route_message_demo.py`.
#### list\_available\_area\_codes() #### list\_available\_area\_codes()
@ -561,7 +564,9 @@ On success, the HTTP status code in the response header is `200 OK` and the resp
### Route Management ### Route Management
The Flowroute Python library v3 allows you to make HTTP requests to the `routes` resource of Flowroute API v2: `https://api.flowroute.com/v2/routes` The Flowroute Python Library v3 allows you to make HTTP requests to the `routes` resource of Flowroute API v2: `https://api.flowroute.com/v2/routes`.
All of the route management methods are encapsulated in `number_route_message_demo.py`.
#### create\_an\_inbound\_route(route\_body) #### create\_an\_inbound\_route(route\_body)
@ -724,7 +729,9 @@ On success, the HTTP status code in the response header is `204 No Content` whic
### Messaging ### Messaging
The Flowroute Python library v3 allows you to make HTTP requests to the `messages` resource of Flowroute API v2.1: `https://api.flowroute.com/v2.1/messages` The Flowroute Python Library v3 allows you to make HTTP requests to the `messages` resource of Flowroute API v2.1: `https://api.flowroute.com/v2.1/messages`.
All of the messaging methods are encapsulated in `number_route_message_demo.py`.
#### send\_a\_message(message\_body) #### send\_a\_message(message\_body)
@ -883,17 +890,554 @@ On success, the HTTP status code in the response header is `200 OK` and the resp
} }
} }
``` ```
#### Errors ### E911 Address Management
In cases of method errors, the Python library raises an exception which includes the HTTP Response code, an error message, and the HTTP body that was received in the request. The Flowroute Python Library v3 allows you to make HTTP requests to the `e911s` resource of Flowroute API v2: `https://api.flowroute.com/v2/e911s`.
##### Example Error All of the E911 address management methods are encapsulated in `e911_demo.py`.
| API Reference Pages |
| ------------------- |
| The E911 and CNAM API reference pages are currently restricted to our beta customers, which means that all API reference links below currently return a `404 Not Found`. They will be publicly available during our E911 and CNAM APIs GA launch in a few weeks. |
#### list\_e911s()
The method accepts `limit`, `offset`, and `state` as parameters which you can learn more about in the [API reference](https://developer.flowroute.com/api/e911s/v2.0/list-account-e911-addresses/).
##### Example Request
```python
print("--List E911 Records")
limit = 2
offset = None
result = e911s_controller.list_e911s(limit, offset)
pprint.pprint(result)
```
##### Example Response
On success, the HTTP status code in the response header is `200 OK` and the response body contains an array of e911 objects in JSON format.
```
--List E911 Records
{'data': [{'attributes': {'address_type': 'Lobby',
'address_type_number': '12',
'city': 'Seattle',
'country': 'USA',
'first_name': 'Maria',
'label': 'Example E911',
'last_name': 'Bermudez',
'state': 'WA',
'street_name': '20th Ave SW',
'street_number': '7742',
'zip': '98106'},
'id': '20930',
'links': {'self': 'https://api.flowroute.com/v2/e911s/20930'},
'type': 'e911'},
{'attributes': {'address_type': 'Apartment',
'address_type_number': '12',
'city': 'Seattle',
'country': 'US',
'first_name': 'Something',
'label': '5th E911',
'last_name': 'Someone',
'state': 'WA',
'street_name': 'Main St',
'street_number': '645',
'zip': '98104'},
'id': '20707',
'links': {'self': 'https://api.flowroute.com/v2/e911s/20707'},
'type': 'e911'}],
'links': {'next': 'https://api.flowroute.com/v2/e911s?limit=2&offset=2',
'self': 'https://api.flowroute.com/v2/e911s?limit=2&offset=0'}}
```
#### get\_e911(e911_id)
The method accepts an `e911_id` as a path parameter which you can learn more about in the [API reference](https://developer.flowroute.com/api/e911s/v2.0/list-e911-record-details/).
##### Example Request
```python
e911_id = None
# If the user has any E911 records, pull one up
for e in result['data']:
e911_id = e['id']
break
if e911_id:
print("\n--Get Details for a specific E911 Record")
result = e911s_controller.get_e911(e911_id)
pprint.pprint(result)
```
##### Example Response
On success, the HTTP status code in the response header is `200 OK` and the response body contains a detailed e911 object in JSON format.
```
--Get Details for a specific E911 Record
{'data': {'attributes': {'address_type': 'L',
'address_type_number': '12',
'city': 'Seattle',
'country': 'USA',
'first_name': 'Maria',
'label': 'Example E911',
'last_name': 'Bermudez',
'state': 'WA',
'street_name': '20th Ave SW',
'street_number': '7742',
'zip': '98106'},
'id': '20930',
'links': {'self': 'https://api.flowroute.com/v2/e911s/20930'},
'type': 'e911'}}
```
#### validate_address(e911_attributes)
The method accepts the different attributes of an E911 address as parameters: `label`, `first_name`, `last_name`, `street_name`, `street_number`, `city`, `state`, `country`, and `zipcode`. Learn more about the different E911 attributes in the [API reference](https://developer.flowroute.com/api/e911s/v2.0/validate-e911-address/). Note that this method doesn't accept the `address_type` and `address_type_number` which are acceptable but not required E911 address attributes by the API.
##### Example Request
```
print("\n--Validate an Address")
try:
result = e911s_controller.validate_address(
label="Test Address",
first_name="Chris",
last_name="Smith",
street_name="3rd Ave",
street_number="1182",
city="Seattle",
state="WA",
country="CA",
zipcode="98101")
pprint.pprint(result)
except Exception as e:
print(str(e))
```
##### Example Response
On success, the HTTP status code in the response header is `204 No Content` which means that the server successfully processed the request and is not returning any content. On error, a printable representation of the detailed API response is displayed.
```
--Validate an Address
HTTP response not OK.
{"errors":[{"detail":"Could not geocode this address. Please check the validity of your address.","id":"7fcfd1cd-486b-4159-8484-b710bd4bbab4","status":400,"title":"Client Error"}]}
```
#### create_address(e911_attributes)
The method accepts the different attributes of an E911 address as parameters: `label`, `first_name`, `last_name`, `street_name`, `street_number`, `city`, `state`, `country`, and `zipcode`. Learn more about the different E911 attributes in the [API reference](https://developer.flowroute.com/api/e911s/v2.0/create-and-validate-new-e911-address/). Note that this method doesn't accept the `address_type` and `address_type\_number` which are acceptable but not required E911 address attributes by the API.
##### Example Request
```
print("\n--Create and Validate an Address")
try:
result = e911s_controller.create_address(
label="E911 Test",
first_name="Chris",
last_name="Smith",
street_name="3rd Ave",
street_number="1218",
city="Seattle",
state="WA",
country="US",
zipcode="98101")
pprint.pprint(result)
except Exception as e:
print(str(e))
print(e.context.response.raw_body)
```
##### Example Response
On success, the HTTP status code in the response header is `201 Created` and the response body contains the newly created e911 object in JSON format. On error, a printable representation of the detailed API response is displayed.
```
--Create and Validate an Address
{'data': {'attributes': {'city': 'Seattle',
'country': 'US',
'first_name': 'Chris',
'label': 'E911 Test',
'last_name': 'Smith',
'state': 'WA',
'street_name': '3rd Ave',
'street_number': '1218',
'zip': '98101'},
'id': '21301',
'links': {'self': 'https://api.flowroute.com/v2/e911s/21301'},
'type': 'e911'}}
```
#### update_address(e911_id, e911_attributes)
The method accepts an E911 record id and the different attributes of an E911 address as parameters: `label`, `first_name`, `last_name`, `street_name`, `street_number`, `city`, `state`, `country`, and `zipcode`. Learn more about the different E911 attributes that you can update in the [API reference](https://developer.flowroute.com/api/e911s/v2.0/update-and-validate-existing-e911-address/). Note that this method doesn't accept the `address_type` and `address_type_number` which are acceptable but not required E911 address attributes by the API. In the following example, we will retrieve the record ID of our newly created E911 address and assign it to a variable, `record_id`. We then update the `last_name` of our selected E911 address to "Wiley".
##### Example Request
```
# Pull the ID from the newly created record
if len(result):
record_id = result['data']['id']
print("\n--Update an E911 Address")
try:
result = e911s_controller.update_address(record_id, last_name='Wiley')
pprint.pprint(result)
except Exception as e:
print(str(e))
print(e.context.response.raw_body)
```
##### Example Response
On success, the HTTP status code in the response header is `200 OK` and the response body contains the newly updated e911 object in JSON format. On error, a printable representation of the detailed API response is displayed.
```
--Update an E911 Address
{'data': {'attributes': {'city': 'Seattle',
'country': 'US',
'first_name': 'Chris',
'label': 'E911 Test 2',
'last_name': 'Wiley',
'state': 'WA',
'street_name': '3rd Ave',
'street_number': '1218',
'zip': '98104'},
'id': '21306',
'links': {'self': 'https://api.flowroute.com/v2/e911s/21306'},
'type': 'e911'}}
```
#### associate(e911_id, number_id)
The method accepts an E911 record id and a phone number as parameters which you can learn more about in the [API reference](https://developer.flowroute.com/api/e911s/v2.0/assign-valid-e911-address-to-phone-number/). In the following example, we call the [list_account_phone_numbers](#list_account_phone_numbers) covered under Number Management and [list_e911s](#list_e911s), extract the values of the first items in the returned JSON arrays into variables `e911_id` and `did` then make the association between them.
##### Example Request
```
# Get our DIDs
did_list = numbers_controller.list_account_phone_numbers()
did = did_list['data'][0]['attributes']['value']
# Get our E911s
e911_list = e911s_controller.list_e911s()
e911_id = e911_list['data'][0]['id']
# Associate them
print("--Associate an E911 Record and a DID")
try:
result = e911s_controller.associate(e911_id, did)
pprint.pprint(result)
except Exception as e:
print(str(e))
print(e.context.response.raw_body)
```
##### Example Response
On success, the HTTP status code in the response header is `204 No Content` which means that the server successfully processed the request and is not returning any content.
`204: No Content`
#### list_dids_for_e911(e911_id)
The method accepts an E911 record id as a parameter which you can learn more about in the [API reference](https://developer.flowroute.com/api/e911s/v2.0/list-phone-numbers-associated-with-e911-record/). In the following example, we retrieve the list of phone numbers associated with our previously assigned `e911_id`.
##### Example Request
```
print("\n--List all DIDs associated with an E911 Record")
result = e911s_controller.list_dids_for_e911(e911_id)
pprint.pprint(result)
```
##### Example Response
On success, the HTTP status code in the response header is `200 OK` and the response body contains an array of related number objects in JSON format.
```
--List all DIDs associated with an E911 Record
{
"data": [
{
"attributes": {
"alias": null,
"value": "12062011682"
},
"id": "12062011682",
"links": {
"self": "https://api.flowroute.com/v2/numbers/12062011682"
},
"type": "number"
}
],
"links": {
"self": "https://api.flowroute.com/v2/e911s/21330/relationships/numbers?limit=10&offset=0"
}
}
```
disconnect(number\_id)](#disconnectnumber_id)
#### disconnect(number_id)
The method accepts a phone number as a parameter which you can learn more about in the [API reference](https://developer.flowroute.com/api/e911s/v2.0/deactivate-e911-service-for-phone-number/). In the following example, we deactivate the E911 service for our previously assigned `did`.
##### Example Request
```
# Dis-Associate them
try:
print("\n--Un-associate the address")
result = e911s_controller.disconnect(12062011682)
pprint.pprint(result)
except Exception as e:
print(str(e))
print(e.context.response.raw_body)
```
##### Example Response
On success, the HTTP status code in the response header is `204 No Content` which means that the server successfully processed the request and is not returning any content.
```
--Un-associate the address
''
```
#### delete_address(e911_id)
The method accepts an E911 record ID as a parameter which you can learn more about in the [API reference](https://developer.flowroute.com/api/e911s/v2.0/remove-e911-address-from-account/). Note that all phone number associations must be removed first before you are able to delete the specified `e911_id`. In the following example, we will attempt to delete the previously assigned `e911_id`.
##### Example Request
```
try:
print("\n--Delete an E911 Address")
result = e911s_controller.delete_address(e911_id)
pprint.pprint(result)
except Exception as e:
print(str(e))
print(e.context.response.raw_body)
```
##### Example Response
On success, the HTTP status code in the response header is `204 No Content` which means that the server successfully processed the request and is not returning any content.
```
--Delete an E911 Address
''
```
### CNAM Record Management
The Flowroute Python Library v3 allows you to make HTTP requests to the `cnams` resource of Flowroute API v2: `https://api.flowroute.com/v2/cnams`.
All of the CNAM record management methods are encapsulated in `cnam_demo.py`.
| API Reference Pages |
| ------------------- |
| The E911 and CNAM API reference pages are currently restricted to our beta customers, which means that all API reference links below currently return a `404 Not Found`. They will be publicly available during our E911 and CNAM APIs GA launch in a few weeks. |
#### list\_cnams()
The method accepts `limit`, `offset`, and `is_approved` as parameters which you can learn more about in the [API reference](https://developer.flowroute.com/api/cnams/v2.0/list-account-cnam-records/).
##### Example Request
```python
print("--List CNAM Records")
limit = 10
offset = None
result = cnams_controller.list_cnams(limit, offset)
pprint.pprint(result)
``` ```
raise ErrorException('403 Forbidden – The server understood the request but refuses to authorize it.', _context)
##### Example Response
On success, the HTTP status code in the response header is `200 OK` and the response body contains an array of cnam objects in JSON format.
``` ```
--List CNAM Records
{'data': [{'attributes': {'approval_datetime': None,
'creation_datetime': None,
'is_approved': True,
'rejection_reason': '',
'value': 'TEST, MARIA'},
'id': '17604',
'links': {'self': 'https://api.flowroute.com/v2/cnams/17604'},
'type': 'cnam'},
{'attributes': {'approval_datetime': '2018-04-16 '
'16:20:32.939166+00:00',
'creation_datetime': '2018-04-12 '
'19:08:39.062539+00:00',
'is_approved': True,
'rejection_reason': None,
'value': 'REGENCE INC'},
'id': '22671',
'links': {'self': 'https://api.flowroute.com/v2/cnams/22671'},
'type': 'cnam'},
{'attributes': {'approval_datetime': '2018-04-23 '
'17:04:30.829341+00:00',
'creation_datetime': '2018-04-19 '
'21:03:04.932192+00:00',
'is_approved': True,
'rejection_reason': None,
'value': 'BROWN BAG'},
'id': '22790',
'links': {'self': 'https://api.flowroute.com/v2/cnams/22790'},
'type': 'cnam'},
{'attributes': {'approval_datetime': '2018-05-23 '
'18:58:46.052602+00:00',
'creation_datetime': '2018-05-22 '
'23:38:27.794911+00:00',
'is_approved': True,
'rejection_reason': None,
'value': 'LEATHER REBEL'},
'id': '23221',
'links': {'self': 'https://api.flowroute.com/v2/cnams/23221'},
'type': 'cnam'},
{'attributes': {'approval_datetime': '2018-05-23 '
'18:58:46.052602+00:00',
'creation_datetime': '2018-05-22 '
'23:39:24.447054+00:00',
'is_approved': True,
'rejection_reason': None,
'value': 'LEATHER REBELZ'},
'id': '23223',
'links': {'self': 'https://api.flowroute.com/v2/cnams/23223'},
'type': 'cnam'},
{'attributes': {'approval_datetime': '2018-05-23 '
'18:58:46.052602+00:00',
'creation_datetime': '2018-05-22 '
'23:42:00.786818+00:00',
'is_approved': True,
'rejection_reason': None,
'value': 'MORBO'},
'id': '23224',
'links': {'self': 'https://api.flowroute.com/v2/cnams/23224'},
'type': 'cnam'}],
'links': {'self': 'https://api.flowroute.com/v2/cnams?limit=10&offset=0'}}
```
#### get_cnam(cnam_id)
The method accepts a CNAM record ID as a parameter which you can learn more about in the [API reference](https://developer.flowroute.com/api/cnams/v2.0/list-cnam-record-details/). In the following example, we query for approved CNAM records on your account and then extract the ID of the first record returned and retrieve the details of that specific CNAM record.
##### Example Request
```
print("\n--List Approved CNAM Records")
result = cnams_controller.list_cnams(is_approved=True)
pprint.pprint(result)
if len(result['data']):
cnam_id = result['data'][0]['id']
print("\n--List CNAM Detail")
result = cnams_controller.get_cnam(cnam_id)
pprint.pprint(result)
```
##### Example Response
On success, the HTTP status code in the response header is `200 OK` and the response body contains a detailed cnam object in JSON format. For the sake of brevity, we will omit the response to the approved CNAM record query.
```
--List CNAM Detail
{'data': {'attributes': {'approval_datetime': None,
'creation_datetime': None,
'is_approved': True,
'rejection_reason': '',
'value': 'TEST, MARIA'},
'id': '17604',
'links': {'self': 'https://api.flowroute.com/v2/cnams/17604'},
'type': 'cnam'}}
```
#### create_cnam_record(cnam_value)
The method accepts a Caller ID value as a parameter which you can learn more about in the [API reference](https://developer.flowroute.com/api/cnams/v2.0/create-a-new-cnam-record/). In the following example, we reuse the `random_generator()` function to generate a four-character random string which we will concatenate with FR and assign as our CNAM value.
##### Example Request
```
# Helper function for random strings
def random_generator(size=4, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
print("\n--Create a CNAM Record")
cnam_value = 'FR ' + random_generator()
result = cnams_controller.create_cnam_record(cnam_value)
pprint.pprint(result)
print("\nNOTE: Newly created CNAM records need to be approved first before they can be associated with your long code number.")
```
##### Example Response
On success, the HTTP status code in the response header is `201 Created` and the response body contains the newly created cnam object in JSON format.
```
--Create a CNAM Record
{'data': {'attributes': {'approval_datetime': None,
'creation_datetime': '2018-06-01 '
'00:09:52.513092+00:00',
'is_approved': False,
'rejection_reason': None,
'value': 'FR H5K8'},
'id': '23454',
'links': {'self': 'https://api.flowroute.com/v2/cnams/23454'},
'type': 'cnam'}}
NOTE: Newly created CNAM records need to be approved first before they can be associated with your long code number.
```
#### associate_cnam(cnam_id, number_id)
The method accepts a CNAM record ID and a phone number as parameters which you can learn more about in the [API reference](https://developer.flowroute.com/api/cnams/v2.0/assign-cnam-record-to-phone-number/). In the following example, we will call `list_account_phone_numbers()` and associate the first number in the returned array with our previously assigned `cnam_id`.
##### Example Request
```
print("\n--Associate a CNAM Record to a DID")
our_numbers = numbers_controller.list_account_phone_numbers()
did_id = our_numbers['data'][0]['id']
if cnam_id is None:
print("Create some CNAM records and wait for approval before trying"
" to associate them with a DID")
else:
result = cnams_controller.associate_cnam(cnam_id, did_id)
pprint.pprint(result)
```
##### Example Response
On success, the HTTP status code in the response header is `202 Accepted` and the response body contains an attributes dictionary containing the `date_created` field and the assigned cnam object in JSON format. This request will fail if the CNAM you are trying to associate has not yet been approved.
```
--Associate a CNAM Record to a DID
{'data': {'attributes': {'date_created': 'Fri, 01 Jun 2018 00:17:52 GMT'},
'id': 17604,
'type': 'cnam'}}
```
#### unassociate_cnam(number_id)
The method accepts a phone number as a parameter which you can learn more about in the [API reference](https://developer.flowroute.com/api/cnams/v2.0/unassign-a-cnam-record-from-phone-number/). In the following example, we will disassociate the same phone number that we've used in `associate_cnam()`.
##### Example Request
```
print("\n--Unassociate a CNAM Record from a DID")
result = cnams_controller.unassociate_cnam(did_id)
pprint.pprint(result)
```
##### Example Response
On success, the HTTP status code in the response header is `202 Accepted` and the response body contains an attributes object with the date the CNAM was requested to be deleted, and the updated cnam object in JSON format.
```
--Unassociate a CNAM Record from a DID
{'data': {'attributes': {'date_created': 'Fri, 01 Jun 2018 00:17:52 GMT'},
'id': None,
'type': 'cnam'}}
```
#### remove_cnam(cnam_id)
The method accepts a CNAM record ID as a parameter which you can learn more about in the [API reference](https://developer.flowroute.com/api/cnams/v2.0/remove-cnam-record-from-account/). In the following example, we will be deleting our previously extracted `cnam_id` from the "List Approved CNAM Records" function call.
##### Example Request
```
print("\n--Remove a CNAM Record from your account")
result = cnams_controller.remove_cnam(cnam_id)
pprint.pprint(result)
```
##### Example Response
On success, the HTTP status code in the response header is `204 No Content` which means that the server successfully processed the request and is not returning any content.
```
--Remove a CNAM Record from your account
''
```
#### Errors
In cases of method errors, the Python library raises an exception which includes an error message and the HTTP body that was received in the request.
##### Example Error
` raise ErrorException('403 Forbidden – The server understood the request but refuses to authorize it.', _context) `
## Testing ## Testing
Once you are done configuring your Flowroute API credentials and updating the function parameters, run the file to see the demo in action: Once you are done configuring your Flowroute API credentials and updating the function parameters, you can run any of the demo files to see them in action. The Flowroute library demo files are named after the resource they represent: <resource_name>_demo.py.
` python demo.py ` ` python cnam_demo.py `

@ -35,12 +35,6 @@ if len(result['data']):
print("\n--List CNAM Detail") print("\n--List CNAM Detail")
result = cnams_controller.get_cnam(cnam_id) result = cnams_controller.get_cnam(cnam_id)
pprint.pprint(result) pprint.pprint(result)
if len(result['data']):
cnam_id = result['data']['id']
print("\n--Search for CNAM Record")
result = cnams_controller.search_cnams(contains='CHRIS')
pprint.pprint(result)
print("\n--Create a CNAM Record") print("\n--Create a CNAM Record")
cnam_value = 'FR ' + random_generator() cnam_value = 'FR ' + random_generator()

@ -0,0 +1,220 @@
#!/usr/bin/env python
import pprint
import os
import json
import random
import string
import configuration
import credentials
from flowroutenumbersandmessaging.flowroutenumbersandmessaging_client import FlowroutenumbersandmessagingClient
print("Number/Route Management v2 & Messaging v2.1 Demo")
'''
# Set up your api credentials and test mobile number for outbound SMS or MMS
basic_auth_user_name = os.environ.get('FR_ACCESS_KEY')
basic_auth_password = os.environ.get('FR_SECRET_KEY')
mobile_number = "YOUR_MOBILE_NUMBER"
'''
#Using files credentials.py and configuration.py for user-dependent variables.
default_fr_creds = credentials.FLOWROUTE_API_KEY
default_config = configuration.FLOWROUTE_DEFAULT_DIDS
basic_auth_user_name = default_fr_creds["USERNAME"]
basic_auth_password = default_fr_creds["PASSWORD"]
test_from_number = default_config["FROM"]
test_to_number = default_config["TO"]
# Instantiate API client and create controllers for Numbers, Messages, and Routes.
client = FlowroutenumbersandmessagingClient(basic_auth_user_name, basic_auth_password)
numbers_controller = client.numbers
routes_controller = client.routes
messages_controller = client.messages
#Use the numbers controller to list available area codes currently in inventory.
print("--List Available Area Codes")
max_setup_cost = 3.25
limit = 3
offset = None
result = numbers_controller.list_available_area_codes(limit, offset, max_setup_cost)
pprint.pprint(result)
#Use the numbers controller to list numbers in the specified area code that are currently in inventory.
print("--List Available Exchange Codes")
limit = 3
offset = None
max_setup_cost = None
areacode = 206
result = numbers_controller.list_available_exchange_codes(limit, offset, max_setup_cost, areacode)
pprint.pprint(result)
#Search for vanity and/or local numbers in numbers currently in inventory.
print("--Search for Purchasable Phone Numbers")
starts_with = 1
contains = 0
ends_with = 007
limit = 3
offset = None
rate_center = None
state = None
print("Searching for vanity numbers with the specified patterns")
result = numbers_controller.search_for_purchasable_phone_numbers(starts_with, contains, ends_with, limit, offset, rate_center, state)
pprint.pprint(result)
#Use the numbers controller to purchase a phone number from inventory.
print("--Purchase a Phone Number")
'''
Uncomment the result line below to allow the demo script to purchase the first number returned by the query above.
If you are not running the number search above, please specify
a purchasable_number before running the purchase a number request.
'''
purchasable_number = result['data'][0]['id']
if purchasable_number == None :
print("Please assign purchasable_number to an available number you wish to purchase")
else :
print("Uncomment the result line below to allow the demo to purchase a number")
#result = numbers_controller.purchase_a_phone_number(purchasable_number)
#Use the numbers controller to list phone numbers currently on your account
print("--List Account Phone Numbers")
starts_with = 1
ends_with = None
contains = None
limit = 5
offset = None
result = numbers_controller.list_account_phone_numbers(starts_with, ends_with, contains, limit, offset)
pprint.pprint(result)
#Use the numbers controller to list the details for a number on your account.
print("--List Phone Number Details")
#You can only get details for a number currently on your account.
number_id = result['data'][0]['id']
if number_id == None :
print ("Please assign number_id to a number to get details for")
else :
result = numbers_controller.list_phone_number_details(number_id)
pprint.pprint(result)
#Use the numbers controller to create an inbound route. Each inbound route created has a unique id, even if the route is identical.
print("---Create an Inbound Route")
# Function to generate six-character random string. If you attempt to create a route already on your account you will receive a 403 error.
def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
new_route = id_generator() + '.sonsofodin.com'
alias = id_generator()
for i in range(10):
alias += str(i)
#request_body is what a JSON body looks like!
request_body = '{ \
"data": { \
"type": "route", \
"attributes": { \
"route_type": "host", \
"value": "' + new_route +'", \
"alias": "' + alias + '" \
} \
} \
}'
result = routes_controller.create_an_inbound_route(request_body)
pprint.pprint(result)
#Use the numbers controller to list inbound routes currently on your account.
print ("---List Inbound Routes")
limit = 3
result = routes_controller.list_inbound_routes(limit)
pprint.pprint(result)
#assigns your primary_inbound_route_id variable to be the [0] first result from the querey above.
#The first result will always be sip-reg with a route id of 0.
primary_inbound_route_id = result['data'][0]['id']
if primary_inbound_route_id == None :
print("Please assign a primary_inbound_route_id")
#assigns the failover_route_id variable to be the [1] second result from the querey above.
failover_route_id = result['data'][1]['id']
if failover_route_id == None :
print("Please assign a failover_route_id")
#Use the routes controller to assign a primary route to a number currently on your account.
#create the primary route JSON request:
request_body = '{ \
"data": { \
"type": "route", \
"id": "' + str(primary_inbound_route_id) +'" \
} \
}'
#update the route!
print("---Update Primary Voice Route")
result = routes_controller.update_primary_voice_route(number_id, request_body)
if result is None:
print("204: No Content")
else:
print (result)
#Use the routes controller to assign a failover route to a number currently on your account.
#create the failover route JSON request:
request_body = '{ \
"data": { \
"type": "route", \
"id": "' + str(failover_route_id) +'" \
} \
}'
#update the route!
print("---Update Failover Voice Route")
result = routes_controller.update_failover_voice_route(number_id, request_body)
if result is None:
print("204: No Content")
else:
print (result)
#Use the messaging controller to send a MMS message using a number currently on your account.
#Create the JSON request:
request_body = '{ \
"data": { \
"type": "message", \
"attributes": { \
"to": "' + str(test_to_number) + '", \
"from": "' + str(test_from_number) + '", \
"body": "greetings hooman!!", \
"is_mms": "true", \
"media_urls": ["http://s3.amazonaws.com/barkpost-assets/50+GIFs/37.gif"] \
} \
} \
}'
#send the message!
print("---Send A Message")
print("Please uncomment the following two lines to send an MMS message")
#result = messages_controller.send_a_message(request_body)
#pprint.pprint(result)
#Use the messages controller to look up the MDRs for a set of messages.
print("---Look Up A Set Of Messages")
start_date = "2017-12-01"
end_date = "2018-01-08"
limit = 2
result = messages_controller.look_up_a_set_of_messages(start_date, end_date, limit)
pprint.pprint(result)
#Use the messages controller to look up the report for an MDR.
print ("---Look Up A Message Detail Record")
message_id = result['data'][0]['id']
if message_id == None :
print("You need to have sent a message within the specified date range to get its MDR.")
result = messages_controller.look_up_a_message_detail_record(message_id)
pprint.pprint(result)

@ -96,58 +96,6 @@ class CNAMsController(BaseController):
return self.handle_request_and_response(_request) return self.handle_request_and_response(_request)
def search_cnams(self, limit=10, offset=0, starts_with=None, contains=None,
ends_with=None):
"""Does a GET request to /v2/cnams?.
Searches for CNAM Records that match the criteria
Args:
limit (int, optional): Limits the number of items to retrieve. A
maximum of 200 items can be retrieved.
offset (int, optional): Offsets the list of cnams by your
specified value. For example, if you have 4 cnam records and
you entered 1 as your offset value, then only 3 of your cnams
will be displayed in the response.
starts_with (string, optional): matching value must start with
these characters
contains (string, optional): matching value must contain these
characters
ends_with (string, optional): matching value must end with
these characters
Returns:
mixed: Response from the API. A JSON object of of an CNAM record
that satisfy your search criteria.
Raises:
APIException: When an error occurs while fetching the data from
the remote API. This exception includes the HTTP Response
code, an error message, and the HTTP body that was received in
the request.
"""
# Prepare query URL
_query_builder = Configuration.base_uri
_query_builder += '/v2/cnams'
_query_parameters = {
'limit': limit,
'offset': offset
}
if starts_with is not None:
_query_parameters['starts_with'] = starts_with
if contains is not None:
_query_parameters['contains'] = contains
if ends_with is not None:
_query_parameters['ends_with'] = ends_with
_query_url = APIHelper.clean_url(_query_builder)
# Prepare and execute request
_request = self.http_client.get(_query_url)
return self.handle_request_and_response(_request)
def create_cnam_record(self, value): def create_cnam_record(self, value):
"""Does a POST request to /v2/cnams. """Does a POST request to /v2/cnams.

Loading…
Cancel
Save