Package: nexmo
Nexmo Client Library for PythonThis is the Python client library for Nexmo's API. To use it you'll
need a Nexmo account. Sign upfor free at nexmo.com.InstallationUsageSMS APIVoice APIVerify APINumber Insight APINumber Management APIManaging SecretsApplication APIOverriding API AttributesFrequently Asked QuestionsLicenseInstallationTo install the Python client library using pip:pip install nexmoTo upgrade your installed client library using pip:pip install nexmo --upgradeAlternatively, you can clone the repository via the command line:git clone git@github.com:Nexmo/nexmo-python.gitor by opening it on GitHub desktop.UsageBegin by importing thenexmomodule:importnexmoThen construct a client object with your key and secret:client=nexmo.Client(key=api_key,secret=api_secret)For production, you can specify theNEXMO_API_KEYandNEXMO_API_SECRETenvironment variables instead of specifying the key and secret explicitly.For newer endpoints that support JWT authentication such as the Voice API,
you can also specify theapplication_idandprivate_keyarguments:client=nexmo.Client(application_id=application_id,private_key=private_key)To check signatures for incoming webhook requests, you'll also need
to specify thesignature_secretargument (or theNEXMO_SIGNATURE_SECRETenvironment variable).SMS APISMS ClassCreating an instance of the SMS classTo create an instance of the SMS class follow these steps:Import the class#Option 1fromnexmoimportSms#Option 2fromnexmo.smsimportSms#Option 3importnexmo#then you can use nexmo.Sms() to create an instanceCreate an instance#Option 1 - pass key and secret to the constructorsms=Sms(key=NEXMO_API_KEY,secret=NEXMO_API_SECRET)#Option 2 - Create a client instance and then pass the client to the Sms instanceclient=Client(key=NEXMO_API_KEY,secret=NEXMO_API_SECRET)sms=Sms(client)Send an SMSfromnexmoimportSmssms=Sms(key=NEXMO_API_KEY,secret=NEXMO_API_SECRET)sms.send_message({"from":NEXMO_BRAND_NAME,"to":TO_NUMBER,"text":"A text message sent using the Nexmo SMS API",})Send SMS with unicodesms.send_message({'from':NEXMO_BRAND_NAME,'to':TO_NUMBER,'text':'こんにちは世界','type':'unicode',})Submit SMS ConversionfromnexmoimportClient,Smsclient=Client(key=NEXMO_API_KEY,secret=NEXMO_SECRET)sms=Sms(client)response=sms.send_message({'from':NEXMO_BRAND_NAME,'to':TO_NUMBER,'text':'Hi from Vonage'})sms.submit_sms_conversion(response['message-id'])Voice APIMake a callfromnexmoimportClient,Voiceclient=Client(application_id=APPLICATION_ID,private_key=PRIVATE_KEY)voice=Voice(client)voice.create_all({'to':[{'type':'phone','number':'14843331234'}],'from':{'type':'phone','number':'14843335555'},'answer_url':['https://example.com/answer']})Retrieve a list of callsfromnexmoimportClient,Voiceclient=Client(application_id=APPLICATION_ID,private_key=PRIVATE_KEY)voice=Voice(client)voice.get_calls()Retrieve a single callfromnexmoimportClient,Voiceclient=Client(application_id=APPLICATION_ID,private_key=PRIVATE_KEY)voice=Voice(client)voice.get_call(uuid)Update a callfromnexmoimportClient,Voiceclient=Client(application_id=APPLICATION_ID,private_key=PRIVATE_KEY)voice=Voice(client)response=voice.create_all({'to':[{'type':'phone','number':'14843331234'}],'from':{'type':'phone','number':'14843335555'},'answer_url':['https://example.com/answer']})voice.update_call(response['uuid'],action='hangup')Stream audio to a callfromnexmoimportClient,Voiceclient=Client(application_id=APPLICATION_ID,private_key=PRIVATE_KEY)voice=Voice(client)stream_url='https://nexmo-community.github.io/ncco-examples/assets/voice_api_audio_streaming.mp3'response=voice.create_call({'to':[{'type':'phone','number':'14843331234'}],'from':{'type':'phone','number':'14843335555'},'answer_url':['https://example.com/answer']})voice.send_audio(response['uuid'],stream_url=[stream_url])Stop streaming audio to a callfromnexmoimportClient,Voiceclient=Client(application_id='0d4884d1-eae8-4f18-a46a-6fb14d5fdaa6',private_key='./private.key')voice=Voice(client)stream_url='https://nexmo-community.github.io/ncco-examples/assets/voice_api_audio_streaming.mp3'response=voice.create_call({'to':[{'type':'phone','number':'14843331234'}],'from':{'type':'phone','number':'14843335555'},'answer_url':['https://example.com/answer']})voice.send_audio(response['uuid'],stream_url=[stream_url])voice.stop_audio(response['uuid'])Send a synthesized speech message to a callfromnexmoimportClient,Voiceclient=Client(application_id=APPLICATION_ID,private_key=PRIVATE_KEY)voice=Voice(client)response=voice.create_call({'to':[{'type':'phone','number':'14843331234'}],'from':{'type':'phone','number':'14843335555'},'answer_url':['https://example.com/answer']})voice.send_speech(response['uuid'],text='Hello from nexmo')Stop sending a synthesized speech message to a call>>>fromnexmoimportClient,Voice>>>client=Client(application_id=APPLICATION_ID,private_key=APPLICATION_ID)>>>voice=Voice(client)>>>response=voice.create_call({'to':[{'type':'phone','number':'14843331234'}],'from':{'type':'phone','number':'14843335555'},'answer_url':['https://example.com/answer']})>>>voice.send_speech(response['uuid'],text='Hello from nexmo')>>>voice.stop_speech(response['uuid'])Send DTMF tones to a callfromnexmoimportClient,Voiceclient=Client(application_id=APPLICATION_ID,private_key=PRIVATE_KEY)voice=Voice(client)response=voice.create_call({'to':[{'type':'phone','number':'14843331234'}],'from':{'type':'phone','number':'14843335555'},'answer_url':['https://example.com/answer']})voice.send_dtmf(response['uuid'],digits='1234')Get recordingresponse=client.get_recording(RECORDING_URL)Verify APIVerify ClassCreating an instance of the classTo create an instance of the Verify class, Just follow the next steps:
​Import the class from module(3 different ways)#First wayfromnexmoimportVerify​#Second wayfromnexmo.verifyimportVerify​#Third valid wayimportnexmo#then you can use nexmo.Verify() to create an instanceCreate the instance​#First way - pass key and secret to the constructorverify=Verify(key=NEXMO_API_KEY,secret=NEXMO_API_SECRET)​#Second way - Create a client instance and then pass the client to the Verify contructorclient=Client(key=NEXMO_API_KEY,secret=NEXMO_API_SECRET)verify=Verify(client)Search for a Verification requestclient=Client(key='API_KEY',secret='API_SECRET')verify=Verify(client)response=verify.search('69e2626cbc23451fbbc02f627a959677')ifresponseisnotNone:print(response['status'])Send verification codeclient=Client(key='API_KEY',secret='API_SECRET')verify=Verify(client)response=verify.request(number=RECIPIENT_NUMBER,brand='AcmeInc')ifresponse["status"]=="0":print("Started verification request_id is%s"%(response["request_id"]))else:print("Error:%s"%response["error_text"])Send verification code with workflowclient=Client(key='API_KEY',secret='API_SECRET')verify=Verify(client)response=verify.request(number=RECIPIENT_NUMBER,brand='AcmeInc',workflow_id=1)ifresponse["status"]=="0":print("Started verification request_id is%s"%(response["request_id"]))else:print("Error:%s"%response["error_text"])Check verification codeclient=Client(key='API_KEY',secret='API_SECRET')verify=Verify(client)response=verify.check(REQUEST_ID,code=CODE)ifresponse["status"]=="0":print("Verification successful, event_id is%s"%(response["event_id"]))else:print("Error:%s"%response["error_text"])Cancel Verification Requestclient=Client(key='API_KEY',secret='API_SECRET')verify=Verify(client)response=verify.cancel(REQUEST_ID)ifresponse["status"]=="0":print("Cancellation successful")else:print("Error:%s"%response["error_text"])Trigger next verification proccessclient=Client(key='API_KEY',secret='API_SECRET')verify=Verify(client)response=verify.trigger_next_event(REQUEST_ID)ifresponse["status"]=="0":print("Next verification stage triggered")else:print("Error:%s"%response["error_text"])Send payment authentication codeclient=Client(key='API_KEY',secret='API_SECRET')verify=Verify(client)response=verify.psd2(number=RECIPIENT_NUMBER,payee=PAYEE,amount=AMOUNT)ifresponse["status"]=="0":print("Started PSD2 verification request_id is%s"%(response["request_id"]))else:print("Error:%s"%response["error_text"])Send payment authentication code with workflowclient=Client(key='API_KEY',secret='API_SECRET')verify=Verify(client)verify.psd2(number=RECIPIENT_NUMBER,payee=PAYEE,amount=AMOUNT,workflow_id:WORKFLOW_ID)ifresponse["status"]=="0":print("Started PSD2 verification request_id is%s"%(response["request_id"]))else:print("Error:%s"%response["error_text"])Number Insight APIBasic Number Insightclient.get_basic_number_insight(number='447700900000')Docs:https://developer.nexmo.com/api/number-insight#getNumberInsightBasicStandard Number Insightclient.get_standard_number_insight(number='447700900000')Docs:https://developer.nexmo.com/api/number-insight#getNumberInsightStandardAdvanced Number Insightclient.get_advanced_number_insight(number='447700900000')Docs:https://developer.nexmo.com/api/number-insight#getNumberInsightAdvancedManaging SecretsAn API is provided to allow you to rotate your API secrets. You can create a new secret (up to a maximum of two secrets) and delete the existing one once all applications have been updated.List Secretssecrets=client.list_secrets(API_KEY)Create A New SecretCreate a new secret (the created dates will help you know which is which):client.create_secret(API_KEY,'awes0meNewSekret!!;');Delete A SecretDelete the old secret (any application still using these credentials will stop working):client.delete_secret(API_KEY,'my-secret-id')Application APICreate an applicationresponse=client.application_v2.create_application({name='Example App',type='voice'})Docs:https://developer.nexmo.com/api/application.v2#createApplicationRetrieve a list of applicationsresponse=client.application_v2.list_applications()Docs:https://developer.nexmo.com/api/application.v2#listApplicationRetrieve a single applicationresponse=client.application_v2.get_application(uuid)Docs:https://developer.nexmo.com/api/application.v2#getApplicationUpdate an applicationresponse=client.application_v2.update_application(uuid,answer_method='POST')Docs:https://developer.nexmo.com/api/application.v2#updateApplicationDelete an applicationresponse=client.application_v2.delete_application(uuid)Docs:https://developer.nexmo.com/api/application.v2#deleteApplicationValidate webhook signaturesclient=nexmo.Client(signature_secret='secret')ifclient.check_signature(request.query):# valid signatureelse:# invalid signatureDocs:https://developer.nexmo.com/concepts/guides/signing-messagesNote: you'll need to contactsupport@nexmo.comto enable message signing on
your account before you can validate webhook signatures.JWT parametersBy default, the library generates short-lived tokens for JWT authentication.Use the auth method to specify parameters for a longer life token or to
specify a different token identifier:client.auth(nbf=nbf,exp=exp,jti=jti)Overriding API AttributesIn order to rewrite/get the value of variables used across all the Nexmo classes Python usesCall by Object Referencethat allows you to create a single client for Sms/Voice Classes. This means that if you make a change on a client instance this will be available for the Sms class.An example using setters/getters withObject references:fromnexmoimportClient,Sms#Defines the clientclient=Client(key='YOUR_API_KEY',secret='YOUR_API_SECRET')print(client.host())# using getter for host -- value returned: rest.nexmo.com#Define the sms instancesms=Sms(client)#Change the value in clientclient.host('mio.nexmo.com')#Change host to mio.nexmo.com - this change will be available for smsOverriding API Host / Host AttributesThese attributes are private in the client class and the only way to access them is using the getters/setters we provide.fromnexmoimportClientclient=Client(key='YOUR_API_KEY',secret='YOUR_API_SECRET')print(client.host())# return rest.nexmo.comclient.host('mio.nexmo.com')# rewrites the host value to mio.nexmo.comprint(client.api_host())# returns api.nexmo.comclient.api_host('myapi.nexmo.com')# rewrite the value of api_hostFrequently Asked QuestionsDropping support for Python 2.7Back in 2014 when Guido van Rossum, Python's creator and principal author, made the announcement, January 1, 2020 seemed pretty far away. Python 2.7’s sunset has happened, after which there’ll be absolutely no more support from the core Python team. Many utilized projects pledge to drop Python 2 support in or before 2020.(Official statement here).Just because 2.7 isn’t going to be maintained past 2020 doesn’t mean your applications or libraries suddenly stop working but as of this moment we won't give official support for upcoming releases. Please read the official"Porting Python 2 Code to Python 3" guide. Please also read thePython 3 Statement Practicalitiesfor advice on sunsetting your Python 2 code.Supported APIsThe following is a list of Vonage APIs and whether the Python SDK provides support for them:APIAPI Release StatusSupported?Account APIGeneral Availability✅Alerts APIGeneral Availability✅Application APIGeneral Availability✅Audit APIBeta❌Conversation APIBeta❌Dispatch APIBeta❌External Accounts APIBeta❌Media APIBeta❌Messages APIBeta❌Number Insight APIGeneral Availability✅Number Management APIGeneral Availability✅Pricing APIGeneral Availability✅Redact APIGeneral Availability✅Reports APIBeta❌SMS APIGeneral Availability✅Verify APIGeneral Availability✅Voice APIGeneral Availability✅ContributingWe :heart: contributions! But if you plan to work on something big or controversial, pleasecontact usfirst!We recommend working onnexmo-pythonwith avirtualenv. The following command will install all the Python dependencies you need to run the tests:makeinstallThe tests are all written with pytest. You run them with:maketestLicenseThis library is released under theMIT License.