# Clear Street Java API Library
[](https://central.sonatype.com/artifact/com.clear_street.api/clear-street-java/0.2.0)
[](https://javadoc.io/doc/com.clear_street.api/clear-street-java/0.2.0)
The Clear Street Java SDK provides convenient access to the Clear Street REST API from applications written in Java.
It is generated with [Stainless](https://www.stainless.com/).
Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.clear_street.api/clear-street-java/0.2.0).
## Installation
### Gradle
```kotlin
implementation("com.clear_street.api:clear-street-java:0.2.0")
```
### Maven
```xml
com.clear_street.apiclear-street-java0.2.0
```
## Requirements
This library requires Java 8 or later.
## Usage
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
import com.clear_street.api.models.v1.accounts.AccountGetAccountsParams;
import com.clear_street.api.models.v1.accounts.AccountGetAccountsResponse;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
// Configures using the `clearstreet.baseUrl` system property
// Or configures using the `CLEAR_STREET_BASE_URL` environment variable
.fromEnv()
.apiKey("My API Key")
.build();
AccountGetAccountsResponse response = client.v1().accounts().getAccounts();
```
## Client configuration
Configure the client using system properties or environment variables:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
// Configures using the `clearstreet.baseUrl` system property
// Or configures using the `CLEAR_STREET_BASE_URL` environment variable
.fromEnv()
.apiKey("My API Key")
.build();
```
Or manually:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
.apiKey("My API Key")
.build();
```
Or using a combination of the two approaches:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
// Configures using the `clearstreet.baseUrl` system property
// Or configures using the `CLEAR_STREET_BASE_URL` environment variable
.fromEnv()
.apiKey("My API Key")
.build();
```
See this table for the available options:
| Setter | System property | Environment variable | Required | Default value |
| --------- | --------------------- | ----------------------- | -------- | ------------------------------- |
| `baseUrl` | `clearstreet.baseUrl` | `CLEAR_STREET_BASE_URL` | true | `"https://api.clearstreet.com"` |
System properties take precedence over environment variables.
> [!TIP]
> Don't create more than one client in the same application. Each client has a connection pool and
> thread pools, which are more efficient to share between requests.
### Modifying configuration
To temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service:
```java
import com.clear_street.api.client.ClearStreetClient;
ClearStreetClient clientWithOptions = client.withOptions(optionsBuilder -> {
optionsBuilder.baseUrl("https://example.com");
optionsBuilder.maxRetries(42);
});
```
The `withOptions()` method does not affect the original client or service.
## Requests and responses
To send a request to the Clear Street API, build an instance of some `Params` class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Java class.
For example, `client.v1().accounts().getAccounts(...)` should be called with an instance of `AccountGetAccountsParams`, and it will return an instance of `AccountGetAccountsResponse`.
## Immutability
Each class in the SDK has an associated [builder](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) or factory method for constructing it.
Each class is [immutable](https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html) once constructed. If the class has an associated builder, then it has a `toBuilder()` method, which can be used to convert it back to a builder for making a modified copy.
Because each class is immutable, builder modification will _never_ affect already built class instances.
## Asynchronous execution
The default client is synchronous. To switch to asynchronous execution, call the `async()` method:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
import com.clear_street.api.models.v1.accounts.AccountGetAccountsParams;
import com.clear_street.api.models.v1.accounts.AccountGetAccountsResponse;
import java.util.concurrent.CompletableFuture;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
// Configures using the `clearstreet.baseUrl` system property
// Or configures using the `CLEAR_STREET_BASE_URL` environment variable
.fromEnv()
.apiKey("My API Key")
.build();
CompletableFuture response = client.async().v1().accounts().getAccounts();
```
Or create an asynchronous client from the beginning:
```java
import com.clear_street.api.client.ClearStreetClientAsync;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClientAsync;
import com.clear_street.api.models.v1.accounts.AccountGetAccountsParams;
import com.clear_street.api.models.v1.accounts.AccountGetAccountsResponse;
import java.util.concurrent.CompletableFuture;
ClearStreetClientAsync client = ClearStreetOkHttpClientAsync.builder()
// Configures using the `clearstreet.baseUrl` system property
// Or configures using the `CLEAR_STREET_BASE_URL` environment variable
.fromEnv()
.apiKey("My API Key")
.build();
CompletableFuture response = client.v1().accounts().getAccounts();
```
The asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s.
## Raw responses
The SDK defines methods that deserialize responses into instances of Java classes. However, these methods don't provide access to the response headers, status code, or the raw response body.
To access this data, prefix any HTTP method call on a client or service with `withRawResponse()`:
```java
import com.clear_street.api.core.http.Headers;
import com.clear_street.api.core.http.HttpResponseFor;
import com.clear_street.api.models.v1.accounts.AccountGetAccountsParams;
import com.clear_street.api.models.v1.accounts.AccountGetAccountsResponse;
HttpResponseFor response = client.v1().accounts().withRawResponse().getAccounts();
int statusCode = response.statusCode();
Headers headers = response.headers();
```
You can still deserialize the response into an instance of a Java class if needed:
```java
import com.clear_street.api.models.v1.accounts.AccountGetAccountsResponse;
AccountGetAccountsResponse parsedResponse = response.parse();
```
## Error handling
The SDK throws custom unchecked exception types:
- [`ClearStreetServiceException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/ClearStreetServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code:
| Status | Exception |
| ------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| 400 | [`BadRequestException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/BadRequestException.kt) |
| 401 | [`UnauthorizedException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/UnauthorizedException.kt) |
| 403 | [`PermissionDeniedException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/PermissionDeniedException.kt) |
| 404 | [`NotFoundException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/NotFoundException.kt) |
| 422 | [`UnprocessableEntityException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/UnprocessableEntityException.kt) |
| 429 | [`RateLimitException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/RateLimitException.kt) |
| 5xx | [`InternalServerException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/InternalServerException.kt) |
| others | [`UnexpectedStatusCodeException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/UnexpectedStatusCodeException.kt) |
- [`ClearStreetIoException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/ClearStreetIoException.kt): I/O networking errors.
- [`ClearStreetRetryableException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/ClearStreetRetryableException.kt): Generic error indicating a failure that could be retried by the client.
- [`ClearStreetInvalidDataException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/ClearStreetInvalidDataException.kt): Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response.
- [`ClearStreetException`](clear-street-java-core/src/main/kotlin/com/clear_street/api/errors/ClearStreetException.kt): Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class.
## Logging
Enable logging by setting the `CLEAR_STREET_LOG` environment variable to `info`:
```sh
export CLEAR_STREET_LOG=info
```
Or to `debug` for more verbose logging:
```sh
export CLEAR_STREET_LOG=debug
```
Or configure the client manually using the `logLevel` method:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
import com.clear_street.api.core.LogLevel;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
.fromEnv()
.logLevel(LogLevel.INFO)
.apiKey("My API Key")
.build();
```
## ProGuard and R8
Although the SDK uses reflection, it is still usable with [ProGuard](https://github.com/Guardsquare/proguard) and [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization) because `clear-street-java-core` is published with a [configuration file](clear-street-java-core/src/main/resources/META-INF/proguard/clear-street-java-core.pro) containing [keep rules](https://www.guardsquare.com/manual/configuration/usage).
ProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary.
## Jackson
The SDK depends on [Jackson](https://github.com/FasterXML/jackson) for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default.
The SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config).
If the SDK threw an exception, but you're _certain_ the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`ClearStreetOkHttpClient`](clear-street-java-client-okhttp/src/main/kotlin/com/clear_street/api/client/okhttp/ClearStreetOkHttpClient.kt) or [`ClearStreetOkHttpClientAsync`](clear-street-java-client-okhttp/src/main/kotlin/com/clear_street/api/client/okhttp/ClearStreetOkHttpClientAsync.kt).
> [!CAUTION]
> We make no guarantee that the SDK works correctly when the Jackson version check is disabled.
Also note that there are bugs in older Jackson versions that can affect the SDK. We don't work around all Jackson bugs ([example](https://github.com/FasterXML/jackson-databind/issues/3240)) and expect users to upgrade Jackson for those instead.
## Network options
### Retries
The SDK automatically retries 2 times by default, with a short exponential backoff between requests.
Only the following error types are retried:
- Connection errors (for example, due to a network connectivity problem)
- 408 Request Timeout
- 409 Conflict
- 429 Rate Limit
- 5xx Internal
The API may also explicitly instruct the SDK to retry or not retry a request.
To set a custom number of retries, configure the client using the `maxRetries` method:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
.fromEnv()
.maxRetries(4)
.apiKey("My API Key")
.build();
```
### Timeouts
Requests time out after 1 minute by default.
To set a custom timeout, configure the method call using the `timeout` method:
```java
import com.clear_street.api.models.v1.accounts.AccountGetAccountsResponse;
AccountGetAccountsResponse response = client.v1().accounts().getAccounts(RequestOptions.builder().timeout(Duration.ofSeconds(30)).build());
```
Or configure the default for all method calls at the client level:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
import java.time.Duration;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
.fromEnv()
.timeout(Duration.ofSeconds(30))
.apiKey("My API Key")
.build();
```
### Proxies
To route requests through a proxy, configure the client using the `proxy` method:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
import java.net.InetSocketAddress;
import java.net.Proxy;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
.fromEnv()
.proxy(new Proxy(
Proxy.Type.HTTP, new InetSocketAddress(
"https://example.com", 8080
)
))
.apiKey("My API Key")
.build();
```
If the proxy responds with `407 Proxy Authentication Required`, supply credentials by also configuring `proxyAuthenticator`:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
import com.clear_street.api.core.http.ProxyAuthenticator;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
.fromEnv()
.proxy(...)
// Or a custom implementation of `ProxyAuthenticator`.
.proxyAuthenticator(ProxyAuthenticator.basic("username", "password"))
.apiKey("My API Key")
.build();
```
### Connection pooling
To customize the underlying OkHttp connection pool, configure the client using the `maxIdleConnections` and `keepAliveDuration` methods:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
import java.time.Duration;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
.fromEnv()
// If `maxIdleConnections` is set, then `keepAliveDuration` must be set, and vice versa.
.maxIdleConnections(10)
.keepAliveDuration(Duration.ofMinutes(2))
.apiKey("My API Key")
.build();
```
If both options are unset, OkHttp's default connection pool settings are used.
### HTTPS
> [!NOTE]
> Most applications should not call these methods, and instead use the system defaults. The defaults include
> special optimizations that can be lost if the implementations are modified.
To configure how HTTPS connections are secured, configure the client using the `sslSocketFactory`, `trustManager`, and `hostnameVerifier` methods:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
.fromEnv()
// If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa.
.sslSocketFactory(yourSSLSocketFactory)
.trustManager(yourTrustManager)
.hostnameVerifier(yourHostnameVerifier)
.apiKey("My API Key")
.build();
```
### Environments
The SDK sends requests to the production by default. To send requests to a different environment, configure the client like so:
```java
import com.clear_street.api.client.ClearStreetClient;
import com.clear_street.api.client.okhttp.ClearStreetOkHttpClient;
ClearStreetClient client = ClearStreetOkHttpClient.builder()
.fromEnv()
.staging()
.apiKey("My API Key")
.build();
```
### Custom HTTP client
The SDK consists of three artifacts:
- `clear-street-java-core`
- Contains core SDK logic
- Does not depend on [OkHttp](https://square.github.io/okhttp)
- Exposes [`ClearStreetClient`](clear-street-java-core/src/main/kotlin/com/clear_street/api/client/ClearStreetClient.kt), [`ClearStreetClientAsync`](clear-street-java-core/src/main/kotlin/com/clear_street/api/client/ClearStreetClientAsync.kt), [`ClearStreetClientImpl`](clear-street-java-core/src/main/kotlin/com/clear_street/api/client/ClearStreetClientImpl.kt), and [`ClearStreetClientAsyncImpl`](clear-street-java-core/src/main/kotlin/com/clear_street/api/client/ClearStreetClientAsyncImpl.kt), all of which can work with any HTTP client
- `clear-street-java-client-okhttp`
- Depends on [OkHttp](https://square.github.io/okhttp)
- Exposes [`ClearStreetOkHttpClient`](clear-street-java-client-okhttp/src/main/kotlin/com/clear_street/api/client/okhttp/ClearStreetOkHttpClient.kt) and [`ClearStreetOkHttpClientAsync`](clear-street-java-client-okhttp/src/main/kotlin/com/clear_street/api/client/okhttp/ClearStreetOkHttpClientAsync.kt), which provide a way to construct [`ClearStreetClientImpl`](clear-street-java-core/src/main/kotlin/com/clear_street/api/client/ClearStreetClientImpl.kt) and [`ClearStreetClientAsyncImpl`](clear-street-java-core/src/main/kotlin/com/clear_street/api/client/ClearStreetClientAsyncImpl.kt), respectively, using OkHttp
- `clear-street-java`
- Depends on and exposes the APIs of both `clear-street-java-core` and `clear-street-java-client-okhttp`
- Does not have its own logic
This structure allows replacing the SDK's default HTTP client without pulling in unnecessary dependencies.
#### Customized [`OkHttpClient`](https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html)
> [!TIP]
> Try the available [network options](#network-options) before replacing the default client.
To use a customized `OkHttpClient`:
1. Replace your [`clear-street-java` dependency](#installation) with `clear-street-java-core`
2. Copy `clear-street-java-client-okhttp`'s [`OkHttpClient`](clear-street-java-client-okhttp/src/main/kotlin/com/clear_street/api/client/okhttp/OkHttpClient.kt) class into your code and customize it
3. Construct [`ClearStreetClientImpl`](clear-street-java-core/src/main/kotlin/com/clear_street/api/client/ClearStreetClientImpl.kt) or [`ClearStreetClientAsyncImpl`](clear-street-java-core/src/main/kotlin/com/clear_street/api/client/ClearStreetClientAsyncImpl.kt), similarly to [`ClearStreetOkHttpClient`](clear-street-java-client-okhttp/src/main/kotlin/com/clear_street/api/client/okhttp/ClearStreetOkHttpClient.kt) or [`ClearStreetOkHttpClientAsync`](clear-street-java-client-okhttp/src/main/kotlin/com/clear_street/api/client/okhttp/ClearStreetOkHttpClientAsync.kt), using your customized client
### Completely custom HTTP client
To use a completely custom HTTP client:
1. Replace your [`clear-street-java` dependency](#installation) with `clear-street-java-core`
2. Write a class that implements the [`HttpClient`](clear-street-java-core/src/main/kotlin/com/clear_street/api/core/http/HttpClient.kt) interface
3. Construct [`ClearStreetClientImpl`](clear-street-java-core/src/main/kotlin/com/clear_street/api/client/ClearStreetClientImpl.kt) or [`ClearStreetClientAsyncImpl`](clear-street-java-core/src/main/kotlin/com/clear_street/api/client/ClearStreetClientAsyncImpl.kt), similarly to [`ClearStreetOkHttpClient`](clear-street-java-client-okhttp/src/main/kotlin/com/clear_street/api/client/okhttp/ClearStreetOkHttpClient.kt) or [`ClearStreetOkHttpClientAsync`](clear-street-java-client-okhttp/src/main/kotlin/com/clear_street/api/client/okhttp/ClearStreetOkHttpClientAsync.kt), using your new client class
## Undocumented API functionality
The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.
### Parameters
To set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class:
```java
import com.clear_street.api.core.JsonValue;
import com.clear_street.api.models.v1.accounts.AccountGetAccountsParams;
AccountGetAccountsParams params = AccountGetAccountsParams.builder()
.putAdditionalHeader("Secret-Header", "42")
.putAdditionalQueryParam("secret_query_param", "42")
.putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))
.build();
```
These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods.
To set undocumented parameters on _nested_ headers, query params, or body classes, call the `putAdditionalProperty` method on the nested class:
```java
import com.clear_street.api.core.JsonValue;
import com.clear_street.api.models.v1.accounts.AccountPatchAccountByIdParams;
import com.clear_street.api.models.v1.accounts.RiskSettings;
AccountPatchAccountByIdParams params = AccountPatchAccountByIdParams.builder()
.risk(RiskSettings.builder()
.putAdditionalProperty("secretProperty", JsonValue.from("42"))
.build())
.build();
```
These properties can be accessed on the nested built object later using the `_additionalProperties()` method.
To set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](clear-street-java-core/src/main/kotlin/com/clear_street/api/core/Values.kt) object to its setter:
```java
import com.clear_street.api.models.v1.accounts.AccountGetAccountsParams;
AccountGetAccountsParams params = AccountGetAccountsParams.builder().build();
```
The most straightforward way to create a [`JsonValue`](clear-street-java-core/src/main/kotlin/com/clear_street/api/core/Values.kt) is using its `from(...)` method:
```java
import com.clear_street.api.core.JsonValue;
import java.util.List;
import java.util.Map;
// Create primitive JSON values
JsonValue nullValue = JsonValue.from(null);
JsonValue booleanValue = JsonValue.from(true);
JsonValue numberValue = JsonValue.from(42);
JsonValue stringValue = JsonValue.from("Hello World!");
// Create a JSON array value equivalent to `["Hello", "World"]`
JsonValue arrayValue = JsonValue.from(List.of(
"Hello", "World"
));
// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`
JsonValue objectValue = JsonValue.from(Map.of(
"a", 1,
"b", 2
));
// Create an arbitrarily nested JSON equivalent to:
// {
// "a": [1, 2],
// "b": [3, 4]
// }
JsonValue complexValue = JsonValue.from(Map.of(
"a", List.of(
1, 2
),
"b", List.of(
3, 4
)
));
```
Normally a `Builder` class's `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset.
To forcibly omit a required parameter or property, pass [`JsonMissing`](clear-street-java-core/src/main/kotlin/com/clear_street/api/core/Values.kt):
```java
import com.clear_street.api.core.JsonMissing;
import com.clear_street.api.models.v1.accounts.AccountGetAccountByIdParams;
import com.clear_street.api.models.v1.accounts.AccountGetAccountsParams;
AccountGetAccountsParams params = AccountGetAccountByIdParams.builder()
.accountId(JsonMissing.of())
.build();
```
### Response properties
To access undocumented response properties, call the `_additionalProperties()` method:
```java
import com.clear_street.api.core.JsonValue;
import java.util.Map;
Map additionalProperties = client.v1().accounts().getAccounts(params)._additionalProperties();
JsonValue secretPropertyValue = additionalProperties.get("secretProperty");
String result = secretPropertyValue.accept(new JsonValue.Visitor<>() {
@Override
public String visitNull() {
return "It's null!";
}
@Override
public String visitBoolean(boolean value) {
return "It's a boolean!";
}
@Override
public String visitNumber(Number value) {
return "It's a number!";
}
// Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject`
// The default implementation of each unimplemented method delegates to `visitDefault`, which throws by default, but can also be overridden
});
```
To access a property's raw JSON value, which may be undocumented, call its `_` prefixed method:
```java
import com.clear_street.api.core.JsonField;
import java.util.Optional;
JsonField