# Using the Python SDK

Source: https://developer.nylas.com/docs/v3/sdks/python/

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.


> **Warn:** 
> ⚠️ **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 developer account](https://dashboard-v3.nylas.com/register?utm_source=docs&utm_medium=devrel-surfaces&utm_campaign=&utm_content=python-sdk).
- [Get your developer keys](/docs/dev-guide/dashboard/#get-your-api-key). 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](/docs/dev-guide/platform/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](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/) for more information.

## Install the Nylas Python SDK

To install the Nylas Python SDK, run the following command in a terminal.

```bash
pip install nylas
```

## Initialize a Nylas instance

You can initialize a `nylas` instance by passing your API key to the constructor, as below.

```python
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 (Iowa)   | `https://api.us.nylas.com` |
| Europe (London)        | `https://api.eu.nylas.com` |

For more information, see our [data residency documentation](/docs/dev-guide/platform/data-residency/).


To change the API URL, pass the `NYLAS_API_URI` parameter with the API URL of your location.

```python
from nylas import Client

nylas = Client(
    os.environ.get('NYLAS_API_KEY'),
    os.environ.get('NYLAS_API_URI')
)
```

> **Info:** 
> **The base API URL defaults to the Nylas U.S. region**. See the [data residency documentation](/docs/dev-guide/platform/data-residency/) 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.

```py

from nylas import Client

nylas = Client(
    "<NYLAS_API_KEY>",
    "<NYLAS_API_URI>",
)

application = nylas.applications.info()
application_id = application[1]
print("Application ID:", application_id)


```

## Authenticate 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](/docs/v3/auth/).

In practice, Nylas' REST API simplifies the OAuth process to two steps: [redirecting the user to Nylas](#redirect-user-to-nylas), and [handling the auth response](#handle-the-authentication-response).

### Redirect user to Nylas

The following code sample redirects a user to Nylas for authentication.

```py
from dotenv import load_dotenv

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"]}'
```

> **Info:** 
> **Nylas provides granular scopes that allow you to control the level of access your application has to users' data**. For a list of scopes that Nylas supports, see [Using granular scopes to request user data](/docs/dev-guide/scopes/).

### Handle the authentication response

Next, your application has to handle the authentication response from Nylas, as in the example below.

```py
@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](https://github.com/nylas/nylas-python/releases).

## Function and model reference

The Nylas Python SDK includes [function and model documentation](https://nylas-python-sdk-reference.pages.dev/), so you can easily find the implementation details that you need.

## GitHub repositories

The [Nylas Python SDK repository](https://github.com/nylas/nylas-python) 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](https://github.com/nylas-samples).

## Tutorials

- [Read messages and threads](/docs/v3/sdks/python/read-messages-threads/)
- [Send messages](/docs/v3/sdks/python/send-email/)
- [Manage inbox folders and labels](/docs/v3/sdks/python/manage-folders-labels/)
- [Manage events](/docs/v3/sdks/python/manage-events/)
- [Manage contacts](/docs/v3/sdks/python/manage-contacts/)

## Recipes in the Cookbook

The [Nylas Cookbook](/docs/cookbook/) has task-focused recipes with examples in Python and every other SDK language. A few good starting points:

- [Send transactional email](/docs/cookbook/email/transactional-send/)
- [Schedule a message to send later](/docs/cookbook/email/schedule-send/)
- [Create and manage drafts](/docs/cookbook/email/manage-drafts/)
- [Organize folders and labels](/docs/cookbook/email/organize-folders/)
- [Reply to a thread](/docs/cookbook/email/threads/reply-to-a-thread/)
- [Work with the Contacts API](/docs/cookbook/contacts/contacts-api-guide/)