Adding a phone number to a user recordΒΆ

Below is a sample function written in python showing how to add a phone number to a user record.

import requests

AK_USERNAME = '' # Enter your username
AK_PASSWORD = '' # Enter your password
AK_DOMAIN = 'docs.actionkit.com'

def user_add_phone(user_id, phone, phone_type, source='restful_api'):

    """ Adds a new phone (of phone_type) to the user at user_id.
        Defaults the phone source to 'restful_api' but you can customize it.
    """

    endpoint = 'user'

    # First, get any existing phone numbers
    response = requests.get(
        'https://{0}:{1}@{2}/rest/v1/{3}/{4}/'.format(
            AK_USERNAME,
            AK_PASSWORD,
            AK_DOMAIN,
            endpoint,
            user_id
        )
    ).json()

    phones = response.get('phones')

    # Add the new phone number
    phones.append({
        "type": phone_type,
        "phone": phone,
        "user": '/rest/v1/user/{0}/'.format(user_id),
        "source": source
    })

    # Patch it to the user's record
    response = requests.patch(
        'https://{0}:{1}@{2}/rest/v1/{3}/{4}/'.format(
            AK_USERNAME,
            AK_PASSWORD,
            AK_DOMAIN,
            endpoint,
            user_id
        ),
        json={
            "phones": phones
        }
    )

    if response.status_code == 202:
        return "Successfully added phone for user #{0}".format(
            user_id
        )
    else:
        return "Did not add phone for user #{0}: {1}".format(
            user_id,
            response.text
        )

With that function defined, you'll be able to use user_add_phone() with a given user_id, phone number, phone type, and optional source, like: user_add_phone(123456, "202-555-0000", "mobile", source='sms-integration') which will create a new mobile phone number for user ID 123456 with the source of 'sms-integration'.

Note that a user cannot have multiple phone numbers of the same type with the same source. So if you tried to add a second mobile phone number for that user, you'd need to use a different source in order to save the second mobile phone number.