Upgrade v5 Nylas Python SDK to v6
Version 6.0.0 of the Nylas Python SDK is a major release that makes the SDK compatible with Nylas v3. The goal of this release was to make the SDK more idiomatic and easier to use. It includes function and model documentation, so you can easily find the implementation details that you need.
Nylas v3 brings a lot of changes. Be sure to familiarize yourself with them before you start upgrading. For more information, see the list of v3 features and changes and the v3 diff list.
⚠️ The v6.x Nylas Python SDK is only compatible with v3.x Nylas APIs. If you're still using an earlier version of Nylas, you should keep using the v5.x Python SDK until you can upgrade to Nylas v3.
Changes to v6 Python SDK
The new v6 Python SDK is a major release and brings a lot of changes. The following sections describe the updates.
Changes to models in v6 Python SDK
Models have been completely changed in the v6 Nylas Python SDK. The SDK now includes specific models for each request to and response from the Nylas APIs. This change is designed to make it easier to work with the SDK.
Because the v6 SDK drops support for Python versions lower than v3.8, it takes advantage of some new Python features:
- Models that represent response objects now use dataclasses. This makes them more readable and easier to use, and provides some type hinting and in-IDE hinting.
- Response objects now implement the
dataclasses-json
library, which provides utility functions such asto_dict()
andto_json()
. This allows you to use your data in different formats. - Models that represent request objects now use TypedDicts to provide a seamless guided experience when building objects for outgoing requests.
- Both dataclass and TypedDict classes are fully typed, meaning that you have all the information you need to make a successful API request.
For example, the v5 Python SDK included only one Calendar
object which represented a calendar in all of the following states:
- To be created.
- To be updated.
- To be retrieved.
This meant that models had to be configured with all possible fields that could ever be used in any of the above scenarios. This made objects very large and difficult to anticipate as a developer.
v6 of the SDK splits the Calendar
model into three:
Calendar
: A model for retrieving a Calendar object.CreateCalendarRequest
: A model for creating a Calendar object.UpdateCalendarRequest
: A model for updating a Calendar object.
Changes to authentication in v6 Python SDK
The authentication methods available in the v6 Python SDK reflect those available in the new v3 Nylas APIs. Nylas recommends you use OAuth and an API key to authenticate your end users, but you should make sure you understand the options before you migrate.
While you can only create and manage your Nylas application's connectors (previously called "integrations") from the v3 Dashboard, you can manage almost everything else directly from the v6 Python SDK. This includes grants, authentication callback URIs ("redirect URIs"), and OAuth tokens, and authenticating your end users.
The v6 Python SDK offers two main methods for authenticating end users to your Nylas application:
Auth#urlForOAuth2
: Returns the redirect URL for authentication with Nylas' OAuth 2.0 implementation.Auth#exchangeCodeForToken
: Exchanges an authorization code that Nylas returned from an authentication redirect for an access token from the OAuth provider. The response also includes information about the grant that was created.
💡 You don't need to use a grant ID to make a request. Instead, you can use the email address associated with a grant as the identifier. If you prefer to use the grant ID, you can extract it from the CodeExchangeResponse
and use it in your future requests.
The following examples show how to authenticate an end user in the v6 Python SDK, and in the v5 SDK for reference.
from nylas import Client
nylas = Client(
api_key="<NYLAS_API_KEY>",
)
# Build the URL for authentication.
auth_url = nylas.auth.url_for_oauth2({
"client_id": "<NYLAS_CLIENT_ID>",
"redirect_uri": "<CALLBACK_URI>",
"login_hint": "anna@example.com"
})
# Write code here to redirect the user to the URL and parse the code.
...
# Exchange the code for an access token.
code_exchange_response = nylas.auth.exchange_code_for_token({
"client_id": "<NYLAS_CLIENT_ID>",
"client_secret": "<NYLAS_CLIENT_SECRET>",
"code": "<AUTH_EXCHANGE_CODE>",
"redirect_uri": "<CALLBACK_URI>"
})
# Use either the email address that was authenticated or the grant ID from the response as the identifier.
response_with_email = nylas.calendars.list(identifier="anna@example.com")
# Or...
response_with_grant = nylas.calendars.list(identifier=code_exchange_response.grant_id)
from nylas import APIClient
nylas = APIClient(
os.environ.get("NYLAS_CLIENT_ID"),
os.environ.get("NYLAS_CLIENT_SECRET"),
api_server = os.environ.get("NYLAS_API_URI") or "https://api.nylas.com"
)
# Build the URL for authentication.
auth_url = nylas.authentication_url(
(CLIENT_URI or "") + 'request_body["success_url"]',
login_hint=request_body["anna@example.com"],
scopes=['email.modify'],
state=None,
)
# Write code here to redirect the user to the URL and parse the code.
...
# Exchange the code for an access token.
# Use the SDK method to exchange our authorization code for an access token with the Nylas API
access_token_obj = nylas.send_authorization(request_body["<ACCESS_TOKEN>"])
# process the result and send to client however you want
access_token = access_token_obj['<ACCESS_TOKEN>']
email_address = access_token_obj['anna@example.com']
nylas.access_token = access_token
calendars = nylas.calendars.where(calendar_id=calendar_id,title=character_to_search,limit=10)
Changes to requests in v6 Python SDK
You might notice some new concepts in the v6 Python SDK when you make requests:
These are explained in more detail in the following sections.
Standard response objects
The v3 Nylas APIs include standard response objects for all requests, except those made to OAuth endpoints. Generally, you'll encounter two types of response objects:
Response
: Used for requests that return a single object. This returns a parameterized object of the type that you requested, and a string representing the request ID.ListResponse
: Used for requests that return a list of objects. This returns a list of parameterized objects of the type that you requested, a string representing the request ID, and anext_cursor
string representing the next page's token.
🚀 Pagination features are coming to the Nylas Python SDK soon!
Both dataclass and TypedDict classes also support destructuring. This means that you can use code like the snippet below to manipulate your data. An example using the v5 Python SDK is also included, for reference.
from nylas import Client
nylas = Client(
api_key="<NYLAS_API_KEY>",
)
response = nylas.calendars.list(identifier="<NYLAS_GRANT_ID>")
calendars = response.data # The list of calendars.
# Or...
calendars, request_id = nylas.calendars.list(identifier="<CALENDAR_ID>") # The list of calendars and the request ID.
from nylas import APIClient
nylas = APIClient(
os.environ.get("NYLAS_CLIENT_ID"),
os.environ.get("NYLAS_CLIENT_SECRET"),
api_server = os.environ.get("NYLAS_API_URI") or "https://api.nylas.com"
)
nylas.access_token = '<NYLAS_ACCESS_TOKEN>'
calendars = nylas.calendars.all()
Standard error objects
The v3 Nylas APIs include standard error objects for all requests. The v6 Python SDK includes two superclass error classes:
AbstractNylasApiError
: Used for errors returned by the API.AbstractNylasSdkError
: Used for errors returned by the SDK.
The AbstractNylasApiError
class includes two subclasses:
NylasOAuthError
: Used for API errors that are returned from OAuth endpoints.NylasApiError
: Used for all other Nylas API errors.
The Python SDK extracts error details from the request response and stores them in an error object, along with the associated request ID and HTTP status code.
Currently, the AbstractNylasSdkError
class has only one subclass: the NylasSdkTimeoutError
, which is thrown when a request times out.
Pagination changes in v6 Python SDK
Pagination has changed in Nylas v3: if Nylas returns more than one page of results in the ListResponse
object, it also sends a next_cursor
parameter that contains a token for the next page.
📝 Currently, the v6 Nylas Python SDK does not support pagination. Until pagination support is added, you can use the next_cursor
parameter to make a request that returns the next page.
The following examples show how to iterate through a list of results using the v6 Python SDK and the v5 SDK, for reference.
from nylas import Client
nylas = Client(
api_key="<NYLAS_API_KEY>",
)
response = nylas.calendars.list(identifier="<NYLAS_GRANT_ID>")
all_calendars = list(response)
while response.next_cursor:
response = nylas.calendars.list(identifier="<NYLAS_GRANT_ID>",
query_params={"page_token": response.next_cursor})
all_calendars.extend(response)
from nylas import APIClient
nylas = APIClient(
os.environ.get("NYLAS_CLIENT_ID"),
os.environ.get("NYLAS_CLIENT_SECRET"),
api_server = os.environ.get("NYLAS_API_URI") or "https://api.nylas.com"
)
nylas.access_token = '<NYLAS_ACCESS_TOKEN>'
calendars = nylas.calendars.where(calendar_id=calendar_id,title=character_to_search,limit=10)
Upgrade to v6 Python SDK
📝 The minimum Python version is now the lowest-supported long-term stable release (LTS): v3.8.
To upgrade the v5.x Python SDK to v6, use pip
to download and install the new version.
pip install nylas --pre
Initialize a Nylas instance
After you upgrade to v6 of the SDK, you need to set up your environment. To do so, initialize a nylas
instance using the Client
constructor. The examples below show the command you use with the v6 Python SDK, and with the v5 SDK for reference.
from nylas import Client
nylas = Client(
api_key="<NYLAS_API_KEY>",
api_uri="<NYLAS_API_URI>"
)
from nylas import APIClient
nylas = APIClient(
os.environ.get("NYLAS_CLIENT_ID"),
os.environ.get("NYLAS_CLIENT_SECRET"),
api_server = os.environ.get("NYLAS_API_URI") or "https://api.nylas.com"
)
You can now use the nylas
instance to make API requests.
Make requests to the Nylas APIs
To make requests to the Nylas APIs, use the nylas
instance that you initialized during setup.
The v6 Python SDK is organized into resources corresponding to each of the Nylas APIs. Each resource includes all of the available methods to make requests to a specific API. For example, to get a list of calendars, you can use the calendars.list
method.
The code samples below show how to list calendars using the v6 Python SDK, and using the v5 SDK for reference.
from nylas import Client
nylas = Client(
api_key="<NYLAS_API_KEY>",
)
response = nylas.calendars.list(identifier="<NYLAS_GRANT_ID>")
from nylas import APIClient
nylas = APIClient(
os.environ.get("NYLAS_CLIENT_ID"),
os.environ.get("NYLAS_CLIENT_SECRET"),
api_server = os.environ.get("NYLAS_API_URI") or "https://api.nylas.com"
)
nylas.access_token = '<NYLAS_ACCESS_TOKEN>'
calendars = nylas.calendars.all()
What's next?
- See the list of Nylas Python SDK releases.
- See the Nylas Samples repository on GitHub for Python SDK examples.