Compare commits

...

2 Commits

Author SHA1 Message Date
Chris Lacina cba96c8685
Update configuration.py 4 years ago
Chris Lacina 5dcc0f4f39 Fixed invalid code 4 years ago
  1. 245
      demo_with_comments.py
  2. 1
      flowroutenumbersandmessaging/configuration.py
  3. 43
      flowroutenumbersandmessaging/controllers/base_controller.py
  4. 2
      flowroutenumbersandmessaging/controllers/messages_controller.py
  5. 6
      flowroutenumbersandmessaging/controllers/routes_controller.py
  6. 9
      flowroutenumbersandmessaging/flowroutenumbersandmessaging_client.py

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

@ -5,7 +5,6 @@
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ) This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io )
""" """
from .api_helper import APIHelper
class Configuration(object): class Configuration(object):

@ -33,9 +33,7 @@ class BaseController(object):
http_call_back = None http_call_back = None
global_headers = { global_headers = {"user-agent": "Flowroute SDK v3.0"}
'user-agent': 'Flowroute SDK v3.0'
}
def __init__(self, client=None, call_back=None): def __init__(self, client=None, call_back=None):
if client is not None: if client is not None:
@ -53,8 +51,7 @@ class BaseController(object):
""" """
for name, value in kwargs.items(): for name, value in kwargs.items():
if value is None: if value is None:
raise ValueError("Required parameter {} cannot be None.". raise ValueError("Required parameter {} cannot be None.".format(name))
format(name))
def execute_request(self, request, binary=False): def execute_request(self, request, binary=False):
"""Executes an HttpRequest. """Executes an HttpRequest.
@ -74,12 +71,14 @@ class BaseController(object):
self.http_call_back.on_before_request(request) self.http_call_back.on_before_request(request)
# Add global headers to request # Add global headers to request
request.headers = APIHelper.merge_dicts(self.global_headers, request.headers = APIHelper.merge_dicts(self.global_headers, request.headers)
request.headers)
# Invoke the API call to fetch the response. # Invoke the API call to fetch the response.
func = self.http_client.execute_as_binary if binary else \ func = (
self.http_client.execute_as_string self.http_client.execute_as_binary
if binary
else self.http_client.execute_as_string
)
response = func(request) response = func(request)
context = HttpContext(request, response) context = HttpContext(request, response)
@ -97,9 +96,8 @@ class BaseController(object):
context (HttpContext): The HttpContext of the API call. context (HttpContext): The HttpContext of the API call.
""" """
if (context.response.status_code < 200) or \ if (context.response.status_code < 200) or (context.response.status_code > 208):
(context.response.status_code > 208): raise APIException("HTTP response not OK.", context)
raise APIException('HTTP response not OK.', context)
# Process request and status code and response text # Process request and status code and response text
def handle_request_and_response(self, request): def handle_request_and_response(self, request):
@ -108,17 +106,22 @@ class BaseController(object):
# Endpoint and global error handling using HTTP status codes. # Endpoint and global error handling using HTTP status codes.
if context.response.status_code == 401: if context.response.status_code == 401:
raise ErrorException('Unauthorized – There was an issue with your ' raise ErrorException(
'API credentials.', context) "Unauthorized – There was an issue with your " "API credentials.",
context,
)
elif context.response.status_code == 403: elif context.response.status_code == 403:
raise ErrorException('Forbidden – You don\'t have permission to ' raise ErrorException(
'access this resource.', context) "Forbidden – You don't have permission to " "access this resource.",
context,
)
elif context.response.status_code == 404: elif context.response.status_code == 404:
raise ErrorException('The specified resource was not found', raise ErrorException("The specified resource was not found", context)
context)
elif context.response.status_code == 422: elif context.response.status_code == 422:
raise ErrorException('Unprocessable Entity - You tried to enter an' raise ErrorException(
' incorrect value.', context) "Unprocessable Entity - You tried to enter an" " incorrect value.",
context,
)
self.validate_response(context) self.validate_response(context)
return APIHelper.json_deserialize(context.response.raw_body) return APIHelper.json_deserialize(context.response.raw_body)

@ -159,7 +159,7 @@ class MessagesController(BaseController):
# Prepare and execute request # Prepare and execute request
_request = self.http_client.post(_query_url, _request = self.http_client.post(_query_url,
headers=_headers, headers=_headers,
parameters=APIHelper.json_serialize(json.loads(body))) parameters=APIHelper.json_serialize(body))
return self.handle_request_and_response(_request) return self.handle_request_and_response(_request)

@ -52,7 +52,7 @@ class RoutesController(BaseController):
# Prepare and execute request # Prepare and execute request
_request = self.http_client.post(_query_url, _request = self.http_client.post(_query_url,
headers=_headers, headers=_headers,
parameters=APIHelper.json_serialize(json.loads(body))) parameters=APIHelper.json_serialize(body))
return self.handle_request_and_response(_request) return self.handle_request_and_response(_request)
@ -135,7 +135,7 @@ class RoutesController(BaseController):
# Prepare and execute request # Prepare and execute request
_request = self.http_client.patch(_query_url, _request = self.http_client.patch(_query_url,
parameters=APIHelper.json_serialize(json.loads(body))) parameters=APIHelper.json_serialize(body))
return self.handle_request_and_response(_request) return self.handle_request_and_response(_request)
@ -176,7 +176,7 @@ class RoutesController(BaseController):
_query_url = APIHelper.clean_url(_query_builder) _query_url = APIHelper.clean_url(_query_builder)
# Prepare and execute request # Prepare and execute request
_request = self.http_client.patch(_query_url, parameters=APIHelper.json_serialize(json.loads(body))) _request = self.http_client.patch(_query_url, parameters=APIHelper.json_serialize(body))
return self.handle_request_and_response(_request) return self.handle_request_and_response(_request)

@ -15,6 +15,7 @@ from .controllers.cnams_controller import CNAMsController
from .controllers.porting_controller import PortingController from .controllers.porting_controller import PortingController
from .controllers.cdrs_controller import CDRsController from .controllers.cdrs_controller import CDRsController
class FlowroutenumbersandmessagingClient(object): class FlowroutenumbersandmessagingClient(object):
config = Configuration config = Configuration
@ -47,10 +48,8 @@ class FlowroutenumbersandmessagingClient(object):
def cdrs(self): def cdrs(self):
return CDRsController() return CDRsController()
def __init__(self, def __init__(self, basic_auth_user_name=None, basic_auth_password=None):
basic_auth_user_name = None, if basic_auth_user_name is not None:
basic_auth_password = None):
if basic_auth_user_name != None:
Configuration.basic_auth_user_name = basic_auth_user_name Configuration.basic_auth_user_name = basic_auth_user_name
if basic_auth_password != None: if basic_auth_password is not None:
Configuration.basic_auth_password = basic_auth_password Configuration.basic_auth_password = basic_auth_password

Loading…
Cancel
Save