# Using the Kotlin/Java SDK

Source: https://developer.nylas.com/docs/v3/sdks/kotlin-java/

As of August 2023, Nylas offers a Kotlin/Java SDK as part of Nylas v3, in addition to the legacy Java-only v2.7 SDK.


> **Warn:** 
> ⚠️ **The v2.x Kotlin/Java SDK is only compatible with v3.x Nylas APIs**. If you're still using an earlier version of Nylas, you should keep using the v1.x Java SDK until you can upgrade to Nylas v3.


## Before you begin

Before you can start using the Nylas Kotlin/Java 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=java-sdk).
- [Get your developer keys](/docs/dev-guide/dashboard/#get-your-api-key). You need to have your...
  - `NYLAS_CLIENT_ID`: Your Nylas application's client ID.
  - `ACCESS_TOKEN`: The access token provided when you authenticate a user to your Nylas application.

## Install the Nylas Kotlin/Java SDK

> **Info:** 
> **Note**: The Nylas Kotlin/Java SDK requires Java 8 or later.

For the following examples, replace `X.X.X` with the version you want to use. See the [list of Kotlin/Java SDK releases](https://github.com/nylas/nylas-java/releases) to learn about the available versions.

### Set up with Gradle

If you're using Gradle, add the following code to the dependencies section of your `build.gradle` file. Be sure to use only the code that matches the SDK version you want to use.

```java
implementation 'com.nylas.sdk:nylas:X.X.X'
```

```kt
implementation("com.nylas.sdk:nylas:X.X.X")
```

### Set up with Maven

For projects using Maven, add the following code to your POM file.

```xml
<dependency>
  <groupId>com.nylas.sdk</groupId>
  <artifactId>nylas</artifactId>
  <version>X.X.X</version>
</dependency>
```

## Initialize the Nylas Client

To start using the Kotlin/Java SDK, you must initialize the `NylasClient` object. The Nylas client allows you to access the [Manage Grants endpoints](/docs/reference/api/manage-grants/).

To create a Nylas application client object, initialize a `NylasClient` object and pass in your Nylas application's API key and API URI.

```java
public class quickstart_java {
  public static void main(String[] args) {
    Dotenv dotenv = Dotenv.load();

    NylasClient nylas = new NylasClient.Builder(dotenv.get("NYLAS_API_KEY")).
        apiUri(dotenv.get("NYLAS_API_URI")).
        build();
  }
}
```

```kt
fun main(args: Array<String>) {
  val dotenv = dotenv()

  val nylas = NylasClient(
      apiKey = dotenv["NYLAS_API_KEY"],
      apiUri = dotenv["NYLAS_API_URI"]
  )

  val http: Http = ignite()
}
```

> **Warn:** 
> **Be careful with secrets!** Follow best practices when you include secrets like your access token in your code. A more secure way to provide these values is to use a [KeyStore](https://docs.oracle.com/javase/7/docs/api/java/security/KeyStore.html) to protect sensitive information.

## Test Kotlin/Java SDK installation

Now that you have the Kotlin/Java 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.

```java
import com.nylas.NylasClient;
import com.nylas.models.*;

public class getApplication {
  public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
    NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();
    Response<ApplicationDetails> application = nylas.applications().getDetails();
    
    System.out.println(application);
  }
}

```

```kt
import com.nylas.NylasClient

fun main(args: Array<String>) {
  val nylas: NylasClient = NylasClient(
      apiKey = "<NYLAS_API_KEY>"
  )

  val application = nylas.applications().getDetails()
  
  print(application)
}

```

## 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 samples redirect a user to Nylas for authentication.

```java
public class AuthRequest {
  public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
    NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

    get("/nylas/auth", (request, response) -> {
      List<String> scope = new ArrayList<>();

      scope.add("https://www.googleapis.com/auth/userinfo.email");

      UrlForAuthenticationConfig config = new UrlForAuthenticationConfig(
          "<NYLAS_CLIENT_ID>",
          "http://localhost:4567/oauth/exchange",
          AccessType.ONLINE,
          AuthProvider.GOOGLE,
          Prompt.DETECT,
          scope,
          true,
          "sQ6vFQN",
          "<email_to_connect>");

      String url = nylas.auth().urlForOAuth2(config);

      response.redirect(url);
      return null;
    });
  }
}
```

```kt
fun main(args: Array<String>) {
  val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")
  val http: Http = ignite()

  http.get("/nylas/auth") {
    val scope = listOf("https://www.googleapis.com/auth/userinfo.email")

    val config : UrlForAuthenticationConfig = UrlForAuthenticationConfig(
        "<NYLAS_CLIENT_ID>",
        "http://localhost:4567/oauth/exchange",
        AccessType.ONLINE,
        AuthProvider.GOOGLE,
        Prompt.DETECT,
        scope,
        true,
        "sQ6vFQN",
        "<email_to_connect>")

    val url = nylas.auth().urlForOAuth2(config)

    response.redirect(url)
  }
}
```

> **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 examples below.

```java
get("/oauth/exchange", (request, response) -> {
  String code = request.queryParams("code");

  if(code == null) { response.status(401); }
  assert code != null;

  CodeExchangeRequest codeRequest = new CodeExchangeRequest(
      "http://localhost:4567/oauth/exchange",
      code,
      dotenv.get("NYLAS_CLIENT_ID"),
      null,
      null);

  try {
    CodeExchangeResponse codeResponse = nylas.auth().exchangeCodeForToken(codeRequest);

    request.session().attribute("grant_id", codeResponse.getGrantId());
    return "%s".formatted(codeResponse.getGrantId());
  } catch(Exception e) {
    return  "%s".formatted(e);
  }
});
```

```kt
http.get("/oauth/exchange") {
  val code : String = request.queryParams("code")

  if(code == "") { response.status(401) }

  val codeRequest : CodeExchangeRequest = CodeExchangeRequest(
      "http://localhost:4567/oauth/exchange",
      code,
      dotenv["NYLAS_CLIENT_ID"],
      null,
      null
  )

  try {
    val codeResponse : CodeExchangeResponse = nylas.auth().exchangeCodeForToken(codeRequest)

    request.session().attribute("grant_id",codeResponse.grantId)
    codeResponse.grantId
  } catch (e : Exception) {
    e.toString()
  }
}
```

## Latest supported version

For the latest supported version of the SDK, see the [Releases page on GitHub](https://github.com/nylas/nylas-java/releases).

## Method and model reference

The Nylas Kotlin/Java SDK includes [method and model documentation](https://nylas-java-sdk-reference.pages.dev/), so you can easily find the implementation details you need.

## GitHub repositories

The [Nylas Kotlin/Java SDK repository](https://github.com/nylas/nylas-java) houses the Kotlin/Java SDK and a number of useful tutorials that demonstrate how to handle things like webhooks, Bring Your Own Authentication, and Hosted OAuth. You can contribute to the SDK by creating an issue or opening a pull request.

For code samples, visit the [Nylas Samples repository](https://github.com/nylas-samples).

## Tutorials

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

## Recipes in the Cookbook

The [Nylas Cookbook](/docs/cookbook/) has task-focused recipes with examples in Kotlin/Java 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/)