Manage contacts with Python
This page explains how to use the Nylas Python SDK and Contacts API to create and manage contacts.
Before you begin
Before you start, you must have done the following tasks:
- Installed and set up the Nylas Python SDK.
- Authenticated one or more end users.
List contacts
The example below lists the first and last names, email addresses, and IDs of the first 10 contacts in an end user's contact list.
from dotenv import load_dotenv
load_dotenv()
import os
import sys
from nylas import Client
nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)
contacts = nylas.contacts.list(
'<NYLAS_GRANT_ID>',
query_params={
"limit": 10
}
)
for contact in contacts[0]:
email = list(contact.emails.values())[0][0]
print("Name: {} {} | Email: {} | ID: {}".format(
contact.given_name, contact.surname, email, contact.id)
)
Create a contact
When you create a contact, Nylas syncs it to the end user's provider. The following example creates a contact, assigns its attributes, and saves it to Nylas.
from dotenv import load_dotenv
load_dotenv()
import os
import sys
from nylas import Client
nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)
grant_id = os.environ.get("NYLAS_GRANT_ID")
contact = nylas.contacts.create(
grant_id,
request_body={
"middleName": "Nylas",
"surname": "Friend",
"notes": "Make sure to keep in touch!",
"emails": [{"type": "work", "email": "swag@example.com"}],
"phoneNumbers": [{"type": "work", "number": "(555) 555-5555"}],
"webPages": [{"type": "other", "url": "nylas.com"}]
}
)
print(contact)
For more information on Contact objects and their attributes, see the Contacts reference documentation.
When you create a contact for a Google account, it renders like this on the provider:
For Microsoft Outlook, new contacts look like this:
Delete a contact
To delete a contact from an end user's account, you must get the contact's id
and pass it as an argument to the contacts.delete()
function. You can use the same code from the List contacts section to retrieve a contact's ID.
⚠️ The following code snippet deletes the contact you specify! Make sure the contact is one that you actually want to delete.
The code sample below finds and deletes a specific contact from an end user's account.
from dotenv import load_dotenv
load_dotenv()
import os
import sys
from nylas import Client
nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)
grant_id = os.environ.get("NYLAS_GRANT_ID")
contact_id = os.environ.get("CONTACT_ID")
request = nylas.contacts.destroy(
'<NYLAS_GRANT_ID>',
'<CONTACT_ID>',
)
Explore the Contacts API
If you've made it to this point, congratulations! You've learned how to manage contacts with the Nylas Python SDK and Contacts API! 🎉
There's plenty more that you can do with Nylas. Take a look at the following resources to learn more: