Using the Kotlin/Java SDK
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.
⚠️ 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 v3 developer account.
- Get your developer keys. You need to have your...
NYLAS_CLIENT_ID
: Your Nylas application's client ID.ACCESS_TOKEN
: The access token provided when you authenticate an end user to your Nylas application.
Install the Nylas Kotlin/Java SDK
📝 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 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.
implementation 'com.nylas.sdk:nylas:X.X.X'
implementation("com.nylas.sdk:nylas:X.X.X")
Set up with Maven
For projects using Maven, add the following code to your POM file.
<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.
To create a Nylas application client object, initialize a NylasClient
object and pass in your Nylas application's API key and API URI.
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.*;
import static spark.Spark.*;
import com.google.gson.Gson;
import com.nylas.NylasClient;
import com.nylas.models.*;
import com.nylas.models.Calendar;
import io.github.cdimascio.dotenv.Dotenv;
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();
}
}
import com.nylas.NylasClient
import com.nylas.models.*
import io.github.cdimascio.dotenv.dotenv
import com.google.gson.Gson;
import spark.kotlin.Http
import spark.kotlin.ignite
import java.time.LocalDate
import java.time.ZoneId
import java.time.temporal.ChronoUnit
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()
}
⚠️ 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 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.
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);
}
}
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 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 samples redirect an end user to Nylas for authentication.
import java.util.*;
import static spark.Spark.*;
import com.nylas.NylasClient;
import com.nylas.models.*;
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;
});
}
}
import com.nylas.NylasClient
import com.nylas.models.AccessType
import com.nylas.models.AuthProvider
import com.nylas.models.Prompt
import com.nylas.models.UrlForAuthenticationConfig
import spark.kotlin.Http
import spark.kotlin.ignite
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)
}
}
🔍 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 examples below.
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);
}
});
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.
Method and model reference
The Nylas Kotlin/Java SDK includes method and model documentation, so you can easily find the implementation details you need.
GitHub repositories
The Nylas Kotlin/Java SDK repository houses the Kotlin/Java SDK and a number of useful tutorials that demonstrate how to handle things like webhooks, Custom 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.