Skip to content

samsarahq/samsara-java

Repository files navigation

Samsara Java Library

fern shield

The Samsara Java library provides convenient access to the Samsara APIs from Java.

Table of Contents

Documentation

API reference documentation is available here.

Reference

A full reference for this library is available here.

Usage

Instantiate and use the client with the following:

package com.example.usage;

import com.samsara.api.SamsaraApiClient;
import com.samsara.api.resources.vehicles.requests.ListVehiclesRequest;

public class Example {
    public static void main(String[] args) {
        SamsaraApiClient client = SamsaraApiClient
            .builder()
            .token("<token>")
            .build();

        client.vehicles().list(
            ListVehiclesRequest
                .builder()
                .build()
        );
    }
}

Environments

This SDK allows you to configure different environments for API requests.

import com.samsara.api.SamsaraApiClient;
import com.samsara.api.core.Environment;

SamsaraApiClient client = SamsaraApiClient
    .builder()
    .environment(Environment.Production API)
    .build();

Base Url

You can set a custom base URL when constructing the client.

import com.samsara.api.SamsaraApiClient;

SamsaraApiClient client = SamsaraApiClient
    .builder()
    .url("https://example.com")
    .build();

Pagination

Paginated requests will return an Iterable, which can be used to loop through the underlying items, or stream them. You can also call nextPage to perform the pagination manually

import com.samsara.api.SamsaraApiClient;
import com.samsara.api.core.pagination.SyncPagingIterable;
import com.samsara.api.types.VehicleResponseObjectResponseBody;
import java.util.List;

SamsaraApiClient client = SamsaraApiClient
    .builder()
    .build();

SyncPagingIterable<SyncPagingIterable<VehicleResponseObjectResponseBody>> response = client.vehicles().list(...);

// Iterator
for (item : response){
    // Do something with item
}

// Streaming
response.streamItems().map(item -> ...);

// Manual pagination
for (
        List<SyncPagingIterable<VehicleResponseObjectResponseBody>> items = response.getItems;
        response.hasNext();
        items = items.nextPage().getItems()) {
    // Do something with items
}

// Access pagination metadata
response.getResponse().ifPresent(r -> {
    String cursor = r.getNext();
    // Use cursor for stateless pagination
});

Exception Handling

When the API returns a non-success status code (4xx or 5xx response), an API exception will be thrown.

import com.samsara.api.core.SamsaraApiApiException;

try{
    client.vehicles().list(...);
} catch (SamsaraApiApiException e){
    // Do something with the API exception...
}

Advanced

Custom Client

This SDK is built to work with any instance of OkHttpClient. By default, if no client is provided, the SDK will construct one. However, you can pass your own client like so:

import com.samsara.api.SamsaraApiClient;
import okhttp3.OkHttpClient;

OkHttpClient customClient = ...;

SamsaraApiClient client = SamsaraApiClient
    .builder()
    .httpClient(customClient)
    .build();

Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retryable and the number of retry attempts has not grown larger than the configured retry limit (default: 2). Before defaulting to exponential backoff, the SDK will first attempt to respect the Retry-After header (as either in seconds or as an HTTP date), and then the X-RateLimit-Reset header (as a Unix timestamp in epoch seconds); failing both of those, it will fall back to exponential backoff.

A request is deemed retryable when any of the following HTTP status codes is returned:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Errors)

Use the maxRetries client option to configure this behavior.

import com.samsara.api.SamsaraApiClient;

SamsaraApiClient client = SamsaraApiClient
    .builder()
    .maxRetries(1)
    .build();

Timeouts

The SDK defaults to a 60 second timeout. You can configure this with a timeout option at the client or request level.

import com.samsara.api.SamsaraApiClient;
import com.samsara.api.core.RequestOptions;

// Client level
SamsaraApiClient client = SamsaraApiClient
    .builder()
    .timeout(60)
    .build();

// Request level
client.vehicles().list(
    ...,
    RequestOptions
        .builder()
        .timeout(60)
        .build()
);

Custom Headers

The SDK allows you to add custom headers to requests. You can configure headers at the client level or at the request level.

import com.samsara.api.SamsaraApiClient;
import com.samsara.api.core.RequestOptions;

// Client level
SamsaraApiClient client = SamsaraApiClient
    .builder()
    .addHeader("X-Custom-Header", "custom-value")
    .addHeader("X-Request-Id", "abc-123")
    .build();
;

// Request level
client.vehicles().list(
    ...,
    RequestOptions
        .builder()
        .addHeader("X-Request-Header", "request-value")
        .build()
);

Access Raw Response Data

The SDK provides access to raw response data, including headers, through the withRawResponse() method. The withRawResponse() method returns a raw client that wraps all responses with body() and headers() methods. (A normal client's response is identical to a raw client's response.body().)

ListHttpResponse response = client.vehicles().withRawResponse().list(...);

System.out.println(response.body());
System.out.println(response.headers().get("X-My-Header"));

Contributing

While we value open-source contributions to this SDK, this library is generated programmatically. Additions made directly to this library would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages