Working with the Nylas Contacts API and Python

Working with the Nylas Contacts API and Python

9 min read

Today I’m going to show you how to manage contacts using the Nylas Contacts API. I’ll cover how to: 

  • Return all contacts
  • Return individual contacts
  • Retrieve information about a contact like their picture
  • Create a contact
  • Update a contact
  • Delete a contact

For the sake of simplicity, we’ll use the Quickstart application you set up when you first sign up for Nylas. In a follow up post, we’ll create our own app and learn how to connect multiple accounts for the Contacts API.

Prerequisites

For this project, you will need:

  • A Nylas developer account
  • Access to your Quickstart application in your account 
  • Your credentials – CLIENT_ID, CLIENT_SECRET, and ACCESS_TOKEN if you need help
  • Nylas Python SDK

Packages used

For this project, we use the following packages:

  • dotenv
  • os
  • pprint 
  • nylas

Install the Nylas Python SDK

You can install the Nylas SDK with pip:

pip install nylas

Connect an account

When you sign up for your Nylas account, the email you provide is connected for you in the Quickstart application. You can use this to try out the different commands in this tutorial.

NOTE: If you want to work with multiple accounts, you need to create your own application. We will review how to set that up in the next tutorial.

Set up your .env file

In the top level of your project, create a .env file using the editor of your choice. Set up your file as shown, but replace the items with your credentials.

CLIENT_ID = "The ID for your application"
CLIENT_SECRET = "The secret for your application"
ACCESS_TOKEN = "The access token you generated with the Quick Start application."

If you did not note your token and save it, you can make a new one in the dashboard.

Return all contacts

One of the first things you may need to do is retrieve a list of your contacts for review. After we set up our environment variables, we need to initialize the client with our credentials. Then we are ready to retrieve our contacts! For ease of review, pprint is used to format the response for you.

from dotenv import load_dotenv
load_dotenv()
 
import os, pprint
from nylas import APIClient
 
nylas = APIClient(
   os.environ.get("CLIENT_ID"),
   os.environ.get("CLIENT_SECRET"),
   os.environ.get("ACCESS_TOKEN"),
)
 
contact = nylas.contacts.all()
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(contact)

The response back will be verbose and contain a lot of details for each contact:

{   'account_id': 'adem6sgnye7dyckcuhmf9xl',
        'api': <nylas.client.client.APIClient object at 0x1033a8e80>,
        'cls': <class 'nylas.client.restful_models.Contact'>,
        'company_name': None,
        'emails': defaultdict(<class 'list'>, {None: ['[email protected]']}),
        'given_name': 'Example',
        'id': '8nfmsbwfx8yhbfmw2angd2fv',
        'im_addresses': defaultdict(<class 'list'>, {}),
        'job_title': None,
        'manager_name': None,
        'middle_name': None,
        'nickname': None,
        'notes': None,
        'object': 'contact',
        'office_location': None,
        'phone_numbers': defaultdict(<class 'list'>, {}),
        'physical_addresses': defaultdict(<class 'list'>, {}),
        'picture_url': None,
        'source': 'inbox',
        'suffix': None,
        'surname': None,
        'web_pages': defaultdict(<class 'list'>, {})},
}

Of particular interest to us is the ‘id’ item. (Not account_id – account_id will bring back all contacts associated with the account.) id will bring back details for a specific user. 

Return an individual contact

Here’s how we return an individual contact with the Nylas Python SDK. For this example, you’ll need the ID for the individual contact you want to retrieve: 

from dotenv import load_dotenv
load_dotenv()
import os, pprint
from nylas import APIClient
 
nylas = APIClient(
   os.environ.get("CLIENT_ID"),
   os.environ.get("CLIENT_SECRET"),
   os.environ.get("ACCESS_TOKEN"),
)
contact = nylas.contacts.get('ID')
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(contact)

Create a contact with the Nylas Contacts API

You can create a contact like this: 

from dotenv import load_dotenv
load_dotenv()

import os, pprint
from nylas import APIClient

nylas = APIClient(
    os.environ.get("CLIENT_ID"),
    os.environ.get("CLIENT_SECRET"),
    os.environ.get("ACCESS_TOKEN"),
)

# CREATE CONTACT

contact = nylas.contacts.create()
contact.given_name = "John"
contact.middle_name = "Q"
contact.surname = "Smith"
contact.emails['personal'] = ['[email protected]']
contact.notes = "Test Contact"
contact.phone_numbers['personal'] = ['(555) 867-5309']
contact.web_pages['homepage'] = ['https://stg-5ji7vw.elementor.cloud']
contact.save()

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(contact)

You’ll get back a response showing the new details you populated for your contact: 

{   'account_id': 'adem6sllgnye7dyckcuhmf9xl',
    'api': <nylas.client.client.APIClient object at 0x1026c9f10>,
    'cls': <class 'nylas.client.restful_models.Contact'>,
    'company_name': None,
    'emails': defaultdict(<class 'list'>,
    {   'personal': ['[email protected]']}),
    'given_name': John',
    'id': 'ik80tuszj6psbninc1me0d0u',
    'im_addresses': defaultdict(<class 'list'>, {}),
    'job_status_id': '7m4zoy86fdshqzlt2bw1v9oyq',
    'job_title': None,
    'manager_name': None,
    'middle_name': 'Q',
    'nickname': None,
    'notes': 'Test Contact',
    'object': 'contact',
    'office_location': None,
    'phone_numbers': defaultdict(<class 'list'>,
                                 {   'personal': ['(555) 867-5309']}),
    'physical_addresses': defaultdict(<class 'list'>, {}),
    'picture_url': None,
    'source': 'address_book',
    'suffix': None,
    'surname': 'Smith',
    'web_pages': defaultdict(<class 'list'>,
                             {   'homepage': ['https://stg-5ji7vw.elementor.cloud']})}

NOTE: When you create a contact, you cannot add an image. The picture related parameters are for retrieving existing image information for a contact.

Modify a contact

To modify a contact using the Nylas Contacts API, you need the contact ID. It will be labeled id in the information for each contact. You can retrieve a contact by returning all contacts and browsing through if you don’t know the ID for the contact you want to work with.

NOTE: You cannot modify the image for a contact or add one if one is not present.

from nylas import APIClient
from datetime import datetime

nylas = APIClient(
   CLIENT_ID,
   CLIENT_SECRET,
   ACCESS_TOKEN
)

# Get a contact with a specified id
contact = nylas.contacts.get("{id}")

# Save the contact to Nylas and the 3rd party provider
contact.save()

# The following attributes can be modified for the contact object
contact.given_name = 'My'
contact.middle_name = 'Nylas'
contact.surname = 'Friend'
contact.suffix = ''
contact.nickname = 'Nylas'
contact.office_location = 'San Francisco'
contact.company_name = 'Nylas'
contact.notes = 'Check out the Nylas Email, Calendar, and Contacts APIs'
contact.manager_name = ''
contact.job_title = 'Communications Platform'
contact.birthday = datetime(2014, 6, 1)

# emails must be one of type personal, or work
contact.emails['personal'] = ['[email protected]']

# physical_addresses must be one of type work, home, or other
contact.physical_addresses['work'] = [{
   # physical addresses must be structured like the following
   'format': 'structured',
   'city': 'San Francisco',
   'country': 'US',
   'state': 'CA',
   'postal_code': '94102',
   'type': 'work',
   'street_address': '944 Market St, 8th Floor'}]

# phone_numbers must be one of type
# business, organization_main, mobile, assistant,
# business_fax, home_fax, radio, car, home, or pager
contact.phone_numbers['business'] = ['555 555-5555']

# web_pages must be one of type homepage, profile, work, or blog
contact.web_pages['homepage'] = ['https://stg-5ji7vw.elementor.cloud']

# im_addresses must be one of type gtalk, aim,
# yahoo, lync, skype, qq, msn, icc, or jabber
contact.im_addresses['gtalk'] = 'Nylas'

Retrieve an image for an individual contact

If a contact has an image associated with their account, you can retrieve and store the image. When you receive the image, it’s a binary file and you must add .png to the end of the file to view its contents. You will also need to check if an image is associated or you may get an error with your code if there isn’t one available.

from nylas import APIClient
nylas = APIClient(
   CLIENT_ID,
   CLIENT_SECRET,
   ACCESS_TOKEN
)

# Get a contact object to access it's picture
contact = nylas.contacts.get('{id}')

# get_picture() returns the urllib request for the picture file
picture = contact.get_picture()

# Here's an example that shows how to save the picture to a file
file = open('picture.jpg', 'wb')
file.write(picture.read())
file.close()

# You can also access the url where Nylas stores the picture with the picture_url attribute
contact.picture_url

Delete a contact

To delete a contact, retrieve the ID for the contact and send a request to Nylas to remove it from the system. This is permanent. If you want the contact information again, you would need to sync and pull it from the provider.

from nylas import APIClient

nylas = APIClient(
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN,
)
nylas.contacts.delete('{id}')

Notes about the Contacts API

This section walks you through details about the Contacts API that may come up when you are working on your project.

Handling images with the Contacts API

The Contacts API is read-only for images associated with profiles. You can’t add or modify image related fields. 

Parsed vs synced contacts

In a response for a contact, you will see a source field. This field tells you where the contact information came from. If you’ve synced with a provider like Yahoo, Gmail, or Microsoft, this field will read address_book. If Nylas provides the contact information by parsing from emails, then it will be listed as inbox. When possible try to sync to get contact information as it is likely to contain more detail than parsing can provide. 

Conclusion

We’ve now walked through the basic features of the Contacts API. If you want to learn more and see a demo of this product in action, go here. You can also (if you haven’t already), sign up for a trial account with Nylas! For a full list of details about what this API offers, you can also review the Contacts API reference documentation.

Related resources

How to create an appointment scheduler in your React app

Learn how to create an appointment scheduler in your React app using Nylas Scheduler. Streamline bookings and UX with step-by-step guidance.

Beyond APIs: Designing elegant, smart Web Components

Dive into the world of smart Web Components for advanced API integration solutions. Design elegant, customizable elements to elevate user experiences.

How to integrate a React calendar component to streamline scheduling

Elevate your app’s scheduling with a React calendar component and seamlessly integrate with Nylas for efficient calendar management.