Using the Python SDK
The Nylas Python SDK is an open-source software development kit that enables you to use Python to integrate the Nylas APIs with your application.
⚠️ 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.
Before you begin
Before you can start using the Nylas Python SDK, make sure you have done the following:
- Create a free Nylas v3 developer account.
- Get your developer keys. You need to have your...
NYLAS_API_KEY
: The API key for your application in the Nylas Dashboard.NYLAS_API_URI
: The URI for your application according to your data residency.NYLAS_GRANT_ID
: The grant ID provided when you authenticate an account to your Nylas application.
- Install pip and create a virtual environment. See the official Python documentation for more information.
Install the Nylas Python SDK
To install the Nylas Python SDK, run the following command in a terminal.
pip install nylas
Initialize a Nylas instance
You can initialize a nylas
instance by passing your API key to the constructor, as below.
from nylas import Client
nylas = Client(
api_key="<NYLAS_API_KEY>",
api_uri="<NYLAS_API_URI>"
)
(Optional) Change the base API URL
You can choose to change the base API URL depending on your location, as in the table below.
Location | Nylas API URL |
---|---|
United States (Oregon) | https://api.us.nylas.com |
Europe (Ireland) | http://api.eu.nylas.com |
For more information, see the data residency documentation and the Migration guide for data centers.
To change the API URL, pass the NYLAS_API_URI
parameter with the API URL of your location.
from nylas import Client
nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)
🔍 The base API URL defaults to the Nylas U.S. region. See the data residency documentation for more information.
Test Python SDK installation
Now that you have the Python SDK installed and set up, you can make a simple program to test your installation. For example, the following code makes a request to return information about your Nylas application.
# Load your env variables
from dotenv import load_dotenv
load_dotenv()
# Import your dependencies
import os
import sys
from nylas import Client
# Initialize your Nylas API client
nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)
# Retrieve Application Information
application = nylas.applications.info()
application_id = application[1]
print("Application ID:", application_id)
Authenticate end users
The Nylas APIs use OAuth 2.0 and let you choose to authenticate using either an API key or access token. For more information about authenticating with Nylas, see the Authentication guide.
In practice, Nylas' REST API simplifies the OAuth process to two steps: redirecting the end user to Nylas, and handling the auth response.
Redirect end user to Nylas
The following code sample redirects an end user to Nylas for authentication.
from dotenv import load_dotenv
import os
from nylas import Client
from flask import Flask, request, redirect, url_for, session, jsonify
from flask_session.__init__ import Session
from nylas.models.auth import URLForAuthenticationConfig
from nylas.models.auth import CodeExchangeRequest
from datetime import datetime, timedelta
# Create the app
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Initialize Nylas client
nylas = Client(
api_key = "<NYLAS_API_KEY>",
api_uri = "<NYLAS_API_URI>",
)
@app.route("/nylas/auth", methods=["GET"])
def login():
if session.get("grant_id") is None:
config = URLForAuthenticationConfig({
"client_id": "<NYLAS_CLIENT_ID>",
"redirect_uri" : "http://localhost:5000/oauth/exchange"
})
url = nylas.auth.url_for_oauth2(config)
return redirect(url)
else:
return f'{session["grant_id"]}'
🔍 Nylas provides granular auth scopes that allow you to control the level of access your application has to end users' data. For a list of scopes that Nylas supports, see the Authentication scopes documentation.
Handle the authentication response
Next, your application has to handle the authentication response from Nylas, as in the example below.
@app.route("/oauth/exchange", methods=["GET"])
def authorized():
if session.get("grant_id") is None:
code = request.args.get("code")
exchangeRequest = CodeExchangeRequest({
"redirect_uri": "http://localhost:5000/oauth/exchange",
"code": code,
"client_id": "<NYLAS_CLIENT_ID>"
})
exchange = nylas.auth.exchange_code_for_token(exchangeRequest)
session["grant_id"] = exchange.grant_id
return redirect(url_for("login"))
Latest supported version
For the latest supported version of the SDK, see the Releases page on GitHub.
Function and model reference
The Nylas Python SDK includes function and model documentation, so you can easily find the implementation details that you need.
GitHub repositories
The Nylas Python SDK repository houses the Python SDK. You can contribute to the SDK by creating an issue or opening a pull request.
For Nylas code samples, visit the Nylas Samples repository.