Vonage Python SDK v4 is Now Live!
最后更新 November 15, 2024

After a full, ground-up rewrite, Version 4 of the Vonage Python SDK is now available. It’s a complete redesign of the previous SDK that offers improvements and enhancements for all users. 

In this post, we’ll walk through the key features and show you how to get started with the new Vonage Python SDK for calling Vonage APIs.

Migrate from v3

If you're currently using SDK v3 and want to upgrade, this guide on migrating from v3 to v4 will be helpful.

Key Features

Doing a ground-up rewrite gave us the opportunity to make some critical structural enhancements, as well as decide how the user should interact with the SDK. 

Here’s a list of some of the most significant changes:

  1. A new monorepo structure

  2. Pydantic data models in requests and responses

  3. Improved inline documentation

  4. Improved error handling and more information

  5. Full support for the Vonage Video API

A New Monorepo Structure

v4 of the Vonage Python SDK now uses a monorepo structure, with different packages for calling different Vonage APIs all using common code. Installing just the top-level vonage package pulls in all the packages you need, so there’s no need to install anything else directly. This gives us more flexibility in what’s released, and when, so we can support new APIs earlier and more clearly version the different packages.

Pydantic Data Models in Requests and Responses

The v4 SDK makes heavy use of Pydantic data models to make it easy to call Vonage APIs and parse the results. 

Using Pydantic models to form requests enforces correct typing and makes it easier to pass the right objects to Vonage. Responses are now deserialized into fully documented Pydantic models, which gives more consistency than returning dictionaries as we did in v3. You can still turn Pydantic models into dictionaries or JSON strings with model.model_dump and model.model_dump_json respectively.

Improved Inline Documentation

Docstrings have been added to methods and data models across the whole SDK to improve the developer experience and make in-IDE development easier. Mousing over a new object/method in your IDE will give information about what it does and how to call it.

Screenshot showing the mouse-over display of a function from the new SDK in Visual Studio CodeThe help you now get in your IDE when using the new SDK

Improved Error Handling and More Information

In v3, most HTTP client errors raised a general HttpClientError exception. Errors in v4 are now finer-grained and error messages give more information and context. 

For example, a new HttpRequestError has been created, with distinct subtypes such as AuthenticationError, ForbiddenError, NotFoundError etc. You can access the HTTP response by catching an HTTP error and using its self.response attribute.

from vonage_http_client import HttpRequestError

try:
    response = client.application.create_application(params)

except HttpRequestError as e:
    print(e.message)  # Prints error message
    print(e.response.text)  # Prints the HTTP response text

Some API packages have their own errors for specific cases too.

For older Vonage APIs that always return an HTTP 200, error handling logic has been included to give a similar experience to the newer APIs.

You can now also access any HTTP response with vonage.Vonage.http_client.last_response and its corresponding HTTP request with vonage.Vonage.http_client.last_request, even when there’s no error thrown, to give you more insight into what’s happening.

Full Support for the Vonage Video API

Support has been added for all Vonage Video API features. As well as the features added to v3, new methods have been added to help you work with the Live Captions, Audio Connector and Experience Composer APIs.

This brings the SDK to feature parity with the OpenTok package. If you're using OpenTok, migration to use v4 of the Vonage Python SDK rather than the opentok Python package is highly recommended. See the OpenTok -> Vonage Video migration guide for help with this.

Installation

The new SDK should be installed in a new virtual environment. Open a console, create a new environment, and install the new SDK with pip using the following commands:

# Create the virtual environment
python3 -m venv venv

# Activate the virtual environment in Mac/Linux
. ./venv/bin/activate

# Or on Windows Command Prompt
venv\Scripts\activate

# Install the package
pip install vonage

You will notice that other dependent Vonage packages, such as vonage-http-client have been installed as well.

If you already have an earlier version of the SDK, use the --upgrade option to get the latest version:

pip install vonage --upgrade

Getting Started

To get started with the v4 SDK, you'll need to initialize an instance of the vonage.Vonage class, which can be used to access API methods. You’ll then need to provide authentication information. Before we break this down, here’s a full example that shows you how to create a new Vonage application with the v4 SDK:

from vonage import Vonage, Auth
from vonage_application import ApplicationConfig

vonage_client = Vonage(auth=Auth(api_key='your_api_key', api_secret='your_api_secret'))

application_data = vonage_client.application.create_application(
    ApplicationConfig(name='My Basic Application')
)

print(application_data)

Now, let’s break this down.

Authentication

Depending on the Vonage API you want to use, you'll use different forms of authentication. You'll need to provide either an API key and secret or the ID of a Vonage Application and its corresponding private key. This is done by initializing an instance of vonage.Auth.

from vonage import Auth

# API key/secret authentication
auth = Auth(
    api_key='your_api_key', api_secret='your_api_secret'
)

# Application ID/private key authentication
auth = Auth(
    application_id='your_vonage_application_id', private_key='your_application_private_key'
)

This auth can then be used when initializing an instance of vonage.Vonage. To set up an instance of the vonage.Vonage class to call Vonage APIs, do this:

from vonage import Vonage, Auth

# Create an Auth instance
auth = Auth(
    api_key='your_api_key', api_secret='your_api_secret'
)

# Create a Vonage client instance
vonage_client = Vonage(auth=auth)

Accessing API Methods

To access methods relating to Vonage APIs, you'll create an instance of the vonage.Vonage class and access them via named attributes, e.g. if you have an instance of vonage.Vonage called vonage_client, use this syntax:

vonage_client.vonage_api.api_method(...)

# For example:
vonage_client.video.create_session(...)

This is very similar to the previous v3.

Accessing API Data Models

Unlike the methods to call each Vonage API, the data models and errors specific to each API are not accessed through the vonage package, but are instead accessed through the specific API package.

For most APIs, data models and errors can be accessed from the top level of the API package, e.g. to send a Verify request, do this:

from vonage_verify import VerifyRequest, SmsChannel

sms_channel = SmsChannel(to='1234567890')
verify_request = VerifyRequest(
    brand='Vonage', workflow=[sms_channel]
)

response = vonage_client.verify.start_verification(
    verify_request
)
print(response)

However, some APIs with a lot of models have them located under the <vonage_api_package>.models package, e.g. vonage-messages, vonage-voice and vonage-video. To access these, simply import from <vonage_api_package>.models, e.g. to send an image via Facebook Messenger do this:

from vonage_messages.models import ( 
    MessengerImage, 
    MessengerOptions, 
    MessengerResource,
)

messenger_image_model = MessengerImage(
    to='messenger_id_to',
    from_='messenger_id_from',
    image=MessengerResource(
        url='https://example.com/image.jpg'
    ),
    messenger=MessengerOptions(
        category='message_tag', tag='my_message_tag'
    ),
)

vonage_client.messages.send(message)

Returning to our complete code example from earlier, we can now see how each part operates.

# Import objects for the Vonage client
from vonage import Vonage, Auth

# Import a data model
from vonage_application import ApplicationConfig

# Create a Vonage client instance
vonage_client = Vonage(auth=Auth(api_key='your_api_key', api_secret='your_api_secret'))

# Make the request using the ApplicationConfig data model
application_data = vonage_client.application.create_application(
    ApplicationConfig(name='My Basic Application')
)

# Print the response
print(application_data)

Summary

This has been a brief overview of the new features, changes and enhancements we’ve brought in v4 of the Vonage Python SDK. Here’s a link to the v3 -> v4 migration guide for some more specific details of API changes.

Please try out the new SDK and let us know your thoughts. We’d love to hear from you and can’t wait to see what you build with Vonage!

Additional Resources

Max KahanPython Developer Advocate

Max is a Python Developer Advocate and Software Engineer who's interested in communications APIs, machine learning, developer experience and dance! His training is in Physics, but now he works on open-source projects and makes stuff to make developers' lives better.

Ready to start building?

Experience seamless connectivity, real-time messaging, and crystal-clear voice and video calls-all at your fingertips.

Subscribe to Our Developer Newsletter

Subscribe to our monthly newsletter to receive our latest updates on tutorials, releases, and events. No spam.