Only show these results:

Upgrade v1 Nylas Java SDK to v2 Kotlin/Java SDK

Version 2.0.0 of the Nylas Java 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 introduces Kotlin support, and the name has been changed to "Kotlin/Java SDK" to indicate this. This release also includes method 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 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.

Changes to v2 Kotlin/Java SDK

The new v2 Nylas Kotlin/Java SDK is a major release and brings a lot of changes — including introducing Kotlin support to the SDK. The following sections describe the updates.

Changes to objects in v2 Kotlin/Java SDK

The v2 Kotlin/Java SDK exclusively uses builder patterns to create objects. This makes it easier to create objects with many optional parameters. All models that include optional parameters have a builder class that you can use to create the object.

The Kotlin/Java SDK has different models for creating, upgrading, and retrieving objects. This better reflects the underlying methods in the Nylas APIs.

  • "Create" objects are prefixed with Create and have a Request suffix.
  • "Update" objects are prefixed with Update and have a Request suffix.
  • "Retrieve" objects use only the object's name.

For example, the v1 Java SDK included only one Calendar object. The v2 Kotlin/Java SDK splits the Calendar object into three:

  • Calendar: An object for retrieving a Calendar.
  • CreateCalendarRequest: An object for creating a Calendar.
  • UpdateCalendarRequest: An object for updating a Calendar.

The code snippets below show how to create a calendar in the v2 Kotlin/Java SDK, and the v1 Java SDK for reference.

NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

CreateCalendarRequest createCalendarRequest = new CreateCalendarRequest.Builder("My Calendar")
.description("My calendar description") // Optional
.location("My calendar location") // Optional
.timezone("America/New_York") // Optional
.build();
val requestBody = CreateCalendarRequest(
"My Calendar",
"My calendar description",
"My calendar location",
"America/New_York",
mapOf<String, String>()
)

val calendar: Response<Calendar> = nylas.calendars().create("<NYLAS_GRANT_ID>", requestBody)
NylasClient nylas = new NylasClient();
NylasAccount account = nylas.account("<NYLAS_ACCESS_TOKEN>");
Calendars calendars = account.calendars();

Calendar newCal = new Calendar();
newCal.setName("My Calendar");
newCal.setDescription("My calendar description");
newCal.setLocation("My calendar location");
newCal.setTimezone("America/New_York");

Calendar created = calendars.create(newCal);

Changes to authentication in v2 Kotlin/Java SDK

The authentication methods available in the v2 Nylas Kotlin/Java 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 v2 Kotlin/Java SDK. This includes grants, authentication callback URIs ("redirect URIs"), and OAuth tokens, and authenticating your end users.

The v2 Kotlin/Java 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 v2 Kotlin/Java SDK, and the v1 Java SDK for reference.

NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

String clientId = "<NYLAS_CLIENT_ID>";
String clientUri = "https://redirect-uri.com/path";

// Build the URL for authentication.
String authURL = nylasClient.auth().urlForOAuth2(
new UrlForAuthenticationConfig.Builder(clientId, clientUri)
.loginHint("[email protected]")
.build()
);

// Write code here to redirect the user to the URL and parse the code.
...

// Exchange the code for an access token.
CodeExchangeRequest codeExchangeRequest = new CodeExchangeRequest.Builder(
clientUri,
"<AUTH_EXCHANGE_CODE>",
clientId
).build();

CodeExchangeResponse codeExchangeResponse = nylasClient.auth().exchangeCodeForToken(codeExchangeRequest);

// Use either the email address that was authenticated or the grant ID from the response as the identifier.
ListResponse<Calendars> calendars = nylas.calendars().list("[email protected]");
ListResponse<Calendars> calendars = nylas.calendars().list(codeExchangeResponse.getGrantId());
val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")

# The URL for authentication
val config : UrlForAuthenticationConfig = UrlForAuthenticationConfig(
"<NYLAS_CLIENT_ID>",
"<CALLBACK_URI>",
AccessType.ONLINE,
AuthProvider.GOOGLE,
Prompt.DETECT,
scope,
true,
"<STATE>",
"[email protected]"
)

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

response.redirect(url)

# Write logic to handle URL call
...

# Exchange the code for an access token.
val codeRequest : CodeExchangeRequest = CodeExchangeRequest(
"<CALLBACK_URI>",
"<AUTH_EXCHANGE_CODE>",
"<NYLAS_CLIENT_ID>",
"nylas"
)

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

# Use either the email address that was authenticated or the grant ID from the response as the identifier.
val calendars: List<Calendar> = nylas.calendars().list("[email protected]")
val calendars: List<Calendar> = nylas.calendars().list("<NYLAS_GRANT_ID>")
from nylas import APIClient;

// Credentials of user
nylas = APIClient(
"<NYLAS_CLIENT_ID>",
"<NYLAS_CLIENT_SECRET>",
"<NYLAS_ACCESS_TOKEN>",
);

// Credentials to be granted
api = APIClient(
"<NYLAS_CLIENT_ID>",
"<NYLAS_CLIENT_SECRET>",
);

# The URL for authentication
url = api.authentication_url(
redirect_uri="<CALLBACK_URI>",
scopes=["<SCOPES>"],
login_hint="[email protected]",
state="mycustomstate",
);

return redirect(url);

// Write logic to handle URL call
...

// Exchange the code for an access token.
code = api.token_for_code("<AUTH_EXCHANGE_CODE>")
client = APIClient(
"<NYLAS_CLIENT_ID>", "<NYLAS_CLIENT_SECRET>", "<AUTH_EXCHANGE_CODE>"
)

// Use either the email address that was authenticated or the grant ID from the response as the identifier.
Events email_events = nylas.events();
RemoteCollection<Event> events_mail_list = email_events.list(new EventQuery().calendarId("[email protected]")

Events grant_events = api.events();
RemoteCollection<Event> events_grant_list = grant_events.list(new EventQuery().calendarId("<NYLAS_GRANT_ID>")

Changes to requests in v2 Kotlin/Java SDK

You might notice some new concepts in the v2 Kotlin/Java SDK when making requests:

These are explained in more detail in the following sections.

Resource parameters

In the v2 Nylas Kotlin/Java SDK, each resource takes different parameters. All resources take an identifier, which is the ID of the account ("grant") that you want to make the request for. This is usually the account's grant ID or email address. Some resources also take query parameters, which are mainly used to filter data or pass additional information.

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 a string representing the next page's token.

Standard error objects

The v3 Nylas APIs include standard error objects for all requests. The v2 Kotlin/Java 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 v2 Kotlin/Java 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.

The code samples below show how to create an event and handle the errors that might occur in the v2 Kotlin/Java SDK, and in the v1 Java SDK for reference.

NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

// Build the create Event request.
CreateEventRequest createEventRequest = new CreateEventRequest.Builder(
new CreateEventRequest.When
.Timespan
.Builder
(1686765600, 1686769200)
.build()
)
.title("My Event") // Optional
.description("My event description") // Optional
.location("My event location") // Optional
.build();

// Build the query parameters. They're required for event creation.
CreateEventQueryParams createEventQueryParams = new CreateEventQueryParams.Builder(calendarId).build();

try {
// Make the request.
Response<Event> createdEventResponse = nylas.events().create(
"<NYLAS_GRANT_ID>",
createEventRequest,
createEventQueryParams
);
} catch (NylasApiError e) {
// Handle error.
}
val nylas: NylasClient = NylasClient(apiKey = dotenv["NYLAS_API_KEY"])

val iStartDate: Int = 1686765600
val iEndDate: Int = 1686769200

val eventWhenObj: CreateEventRequest.When = CreateEventRequest.When.Timespan(iStartDate, iEndDate)
val title: String = "My Event"
val location: String = "My event location"
val description: String = "My event location"

val eventRequest: CreateEventRequest = CreateEventRequest(eventWhenObj, title, location, description)
NylasClient nylas = new NylasClient();
NylasAccount account = nylas.account("<NYLAS_ACCESS_TOKEN>");
LocalDate today = LocalDate.now();
Event.When when = new Event.Datespan(today, today.plusDays(1));

Event event = new Event("<CALENDAR_ID>", when);
event.setTitle("My Event");
event.setLocation("My event location");
event.setDescription("My event description");

try {
Event event_created = account.events().create(event, true);
} catch (Exception e) {
// Handle error.
}

Upgrade to v2 Kotlin/Java SDK

📝 Note: The SDK's artifact name has been changed from nylas-java-sdk to nylas, making it consistent with the other Nylas SDK offerings. The name change also reflects that the SDK is no longer Java-only, but now supports Kotlin as well.

To upgrade the v1.x Nylas Java SDK to the v2 Kotlin/Java SDK, change the dependency in your build.gradle or in your pom.xml file to the following specification.

implementation ('com.nylas.sdk:nylas:2.0.0')   
<dependency>
<groupId>com.nylas.sdk</groupId>
<artifactId>nylas</artifactId>
<version>2.0.X</version>
</dependency>

Initialize the NylasClient object

After you upgrade to the v2 Kotlin/Java SDK, you need to set up your environment. To do so, create a NylasClient object using the builder. The examples below show the command you use with the v2 Kotlin/Java SDK, and with the v1 Java SDK for reference.

NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();   
val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")   
NylasClient nylas = new NylasClient();
Account account = nylas.account("<NYLAS_ACCESS_TOKEN>");

⚠️ All previous methods of initializing the NylasClient object have been removed. The Nylas v2 Kotlin/Java SDK uses builder patterns only to create objects.

You can now use the NylasClient object to make API requests.

Make requests to the Nylas APIs

To make requests to the Nylas APIs, use the NylasClient object that you initialized during setup.

The v2 Kotlin/Java 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 in the v2 Kotlin/Java SDK, and in the v1 Java SDK for reference.

NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();
ListResponse<Calendars> calendars = nylas.calendars().list("<NYLAS_GRANT_ID>");
val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")
val calendars: List<Calendar> = nylas.calendars().list("<NYLAS_GRANT_ID>", calendarQueryParams).data
NylasClient nylas = new NylasClient();
NylasAccount account = nylas.account("<NYLAS_ACCESS_TOKEN>");
Calendars calendars = account.calendars().list();

What's next?