smscx_client

The SMS Connexion API Python library provides convenient access to the SMS API of SMS.CX from applications written in Python language.
Using this library you can:
- send SMS (transactional, promotional) - single or bulk SMS
- receive SMS
- rent phone numbers
- validate phone numbers
- lookup phone numbers (HLR)
- send OTP SMS (2FA)
- create groups of contacts
- import contacts
- create short links
- and more
For more information, please visit https://sms.cx
Content:
Installation
Requirements
Python >=3.6
pip install
Install the python package using:
pip install smscx_client
(you may need to run pip
with root permission: sudo pip install smscx_client
)
Then import the package:
import smscx_client
Setuptools
Install via Setuptools.
python setup.py install --user
(or sudo python setup.py install
to install the package for all users)
Then import the package:
import smscx_client
Authentication
To use the library you must authenticate. SMS.CX PHP Library supports the authentication methods supported by the SMS Connexion API:
1. API Key
To create a new API Key go to SMS.CX Account > HTTP API > API Keys and click on New API Key.

Copy the API Key and use it in this client library.
2. Oauth2 Access Token
Access tokens are used by applications to make API requests.
To create a new application go to SMS.CX Account > HTTP API > Applications and click on New Application.
When you have the Application ID and Application Secret, you can use them to request an access token that you can use to make API calls.

Copy the APPLICATION_ID
and APPLICATION_SECRET
and use them to request an access token:
import time
import smscx_client
from smscx_client.api import oauth_api
from smscx_client.model.oauth_token_response import OauthTokenResponse
from pprint import pprint
configuration = smscx_client.Configuration(
username = "YOUR_APPLICATION_ID",
password = "YOUR_APPLICATION_SECRET"
)
api_instance = oauth_api.OauthApi(
smscx_client.ApiClient(configuration)
)
scope = "sms groups templates numbers shortlinks attachments"
try:
api_response = api_instance.get_access_token(scope=scope)
pprint(api_response)
access_token = api_response.access_token
expires_in = api_response.expires_in
except smscx_client.InvalidRequestException as e:
except smscx_client.InvalidCredentialsException as e:
except smscx_client.InvalidScopeException as e:
except smscx_client.ApiException as e:
print("Exception when calling OauthApi->get_access_token: %s\n" % e)
error_response = json.loads(e.body)
error_type = error_response['error']['type']
error_code = error_response['error']['code']
error_msg = error_response['error']['message']
http_code = e.status
Access tokens provide three main security benefits over using an API Key:
- Revocable access. Access tokens can be revoked, removing access for only that token without having to change your API Key everywhere.
- Limited access. Access tokens have access scopes which allow for more granular access to API resources. For instance, you can grant access only to send SMS but not to get groups of contacts.
- Short lifetime. Access tokens have an expire time (1 day, 1 week) which reduces the risk of the token being compromised.
Usage
The library needs to be configured with your account's Application ID & secret or API Key which are available in your SMS.CX Dashboard.
The following example will send SMS to a single phone number:
import time
import smscx_client
from smscx_client.api import sms_api
from smscx_client.model.send_sms_message_request import SendSmsMessageRequest
from smscx_client.model.send_sms_message_response import SendSmsMessageResponse
from pprint import pprint
configuration = smscx_client.Configuration(
api_key = "YOUR_API_KEY",
)
api_instance = sms_api.SmsApi(
smscx_client.ApiClient(configuration)
)
send_sms_message_request = SendSmsMessageRequest(
to=["+31612469xxx"],
_from = "InfoText",
text = "Your confirmation code is 15997",
)
try:
api_response = api_instance.send_sms(send_sms_message_request)
pprint(api_response)
for item in api_response.data:
except smscx_client.NoCoverageException as e:
except smscx_client.InvalidRequestException as e:
except smscx_client.InvalidPhoneNumberException as e:
except smscx_client.InsufficientBalanceException as e:
except smscx_client.ApiException as e:
print("Exception when calling SmsApi->send_sms: %s\n" % e)
error_response = json.loads(e.body)
error_response = json.loads(e.body)
error_type = error_response['error']['type']
error_code = error_response['error']['code']
error_msg = error_response['error']['message']
http_code = e.status
Example of bulk SMS sending (up to 25.000 destination phone numbers)
import time
import smscx_client
from smscx_client.api import sms_api
from smscx_client.model.send_sms_message_request import SendSmsMessageRequest
from smscx_client.model.send_sms_message_response import SendSmsMessageResponse
from pprint import pprint
configuration = smscx_client.Configuration(
api_key = "YOUR_API_KEY",
)
api_instance = sms_api.SmsApi(
smscx_client.ApiClient(configuration)
)
send_sms_message_request = SendSmsMessageRequest(
to=[
"+31612469xxx",
"+4474005085xx",
"+49151238353xx",
"+417811126xx",
"+3519123350xx",
"+4206016090xx",
"+359483059xx",
"+336127904xx",
"+436645595xx",
"+3519121385xx",
"+3069125917xx",
],
_from="InfoText",
text="Redeem this voucher and you will get 30% discount off all Summer Fashion {{optoutLink}}",
idempotency_id="bf325375-e030-fccb-a009-17317c574773",
transliteration=Transliteration(
alphabet="NONE",
remove_emojis=False,
),
)
try:
api_response = api_instance.send_sms(send_sms_message_request)
pprint(api_response)
for item in api_response.data:
except smscx_client.NoCoverageException as e:
except smscx_client.InvalidRequestException as e:
except smscx_client.InvalidPhoneNumberException as e:
except smscx_client.InsufficientBalanceException as e:
except smscx_client.ApiException as e:
print("Exception when calling SmsApi->send_sms: %s\n" % e)
error_response = json.loads(e.body)
error_type = error_response['error']['type']
error_code = error_response['error']['code']
error_msg = error_response['error']['message']
http_code = e.status
Handling errors
With this client library, you don’t need to check for non-200 HTTP responses. The library translates them as exceptions.
In some specific rare cases you may need to analyze the Error object for type
and code
properties.
To handle errors, use these two techniques:
- Catch Exceptions (recommended)
- Analyze and handle the Error object provided in the response body
1. Catch Exceptions
The SMS.CX Python library raises an exception for every error type. It is recommended to catch and handle exceptions.
To catch an exception, use Python’s try
/except
syntax. SMS Connexion provides many exception classes you can catch. Each one represents a different kind of error. When you catch an exception, you can use its class to choose a response.
General exceptions:
DuplicateIdException
- A resource with the same ID already exist
DuplicateValueException
- You are trying to create/update a resource that must be unique (eg. originators, group name, shortlinks, template name)
InsufficientScopeException
- Your application does not have the privilege to access a resource
InvalidCredentialsException
- Unable to authenticate you based on the information provided.
InvalidRequestException
- The parameters provided were invalid
InvalidScopeException
- The scope requested does not exist
RateLimitExcedeedException
- You made too many API calls in short period of time.
ResourceNotFoundException
- The ID of the requested resource was not found (eg. group, campaign, otp, shortlink, template, etc.)
ApiMethodNotAllowedException
- The target resource doesn’t support this HTTP method
AccessDeniedException
- You don’t have permission to perform an action (eg. editing a template that was locked, replying to an Whatsapp after more than 24 hours passed from client reply, etc.)
ServerErrorException
- Something went wrong on SMS Connexion’s side.
ApiException
- Something went wrong on SMS Connexion’s side
Exceptions for methods that validate numbers or incur costs (to send SMS, add phone numbers to groups, validate number, etc.):
InsufficientBalanceException
- Your request incurs charges in excess of your existing balance.
InvalidPhoneNumberException
- The phone number provided is not valid
Exceptions for methods that require network coverage (send SMS, Viber, Whatsapp):
NoCoverageException
- There is no coverage for the destination requested (these are rare)
Exceptions for Otp:
InvalidPinException
- The PIN provided does not verify with our records
OtpAlreadyVerifiedException
- The OTP was already verified
OtpCancelledException
- You cannot verify an OTP that was cancelled
OtpActionNotAllowedException
- You cannot cancel an OTP that has non-pending status (eg. was already verified, canceled, or expired)
OtpExpiredException
- You cannot verify an OTP that was expired
OtpFailedException
- The OTP verification has failed because the numbers of max attempts was reached
Exceptions for Viber/Whatsapp:
ChannelNotActiveException
- Channel is not active. You need to register Viber and Whatsapp by contacting us
TemplateNotApprovedException
- Template for sending Viber or Whatsapp is not approved
2. Analyze Error object
The error object ( Error ), which is present in all Exceptions, store information about failures.
If you don’t want to rely on our existing Exceptions, you might need to analyze the details of the Error object.
You can retrieve the error object and examine it to learn more about the failure. Choose an appropriate response according on the error type. Check the examples provided to learn how to get the HTTP code and the error object.
A range of different error types are returned by the API, correlated with their HTTP codes:
- HTTP 400 Bad Request for error type
invalid_param
, insufficient_credit
- HTTP 401 Unauthorized for
invalid_api_key
, invalid_client
- HTTP 404 Not Found for
not_found
- HTTP 429 Too Many Requests for
rate_limit
Read the complete list of error types and codes from the API specification.
Example of error handling
try:
except smscx_client.InvalidRequestException as e:
except smscx_client.RateLimitExcedeedException as e:
retry_after = e.headers['X-Rate-Limit-Reset'];
except smscx_client.ServerErrorException as e:
except smscx_client.ApiException as e:
error_response = json.loads(e.body)
error_type = error_response['error']['type']
error_code = error_response['error']['code']
error_msg = error_response['error']['message']
http_code = e.status
In special cases, when using methods to validate phone numbers in bulk or when adding phone numbers to an existing group, the Error
object will contain a list with invalid phone numbers (if the parameter allowInvalid
was not set to true or if not a single valid number was detected).
x = json.loads(e.body)
invalid_phone_numbers = x['error']['invalid'];
"""
Returns list of invalid numbers:
[
"+336123",
"+336123",
"+441589945xx",
"+396778143xx",
"+3362599873xx",
]
"""
Rate limit
To detect an API rate limit error, you can catch the Exception RateLimitExcedeedException
or check the Error object for error type rate_limit
or check if the HTTP code is 429
:
try:
except smscx_client.RateLimitExcedeedException as e:
retry_after = e.headers['X-Rate-Limit-Reset'];
Documentation
The docs folder provides detailed guides for using this library (methods, models, examples).
The examples folder provides an example for each method.
Full documentation of the API is available here.
Available methods
Read the documentation for each method to get more examples, complete parameter list, expected responses and list of error codes.
Class AccountApi
Class ApplicationsApi
Class AttachmentsApi
Class ConversationsApi
Class GroupsApi
Class MultichannelApi
Class NumbersApi
Class OauthApi
Class OptoutsApi
Class OriginatorsApi
Class OtpApi
Class ReportsApi
Class ShortlinksApi
Class SmsApi
Class TemplatesApi
Class ViberApi
Class WhatsappApi
Documentation For Authorization
ApiKeyAuth
- Type: API key
- API key parameter name: X-API-KEY
- Location: HTTP header
BasicAuth
- Type: HTTP basic authentication
BearerAuth
- Type: Bearer authentication
Author
dev@sms.cx
About this package
- Client library version:
0.1.13
- API version:
1.0.2
License
Apache 2.0 © 2022 SMS Connexion