Telnyx Java API Library
Installation
Gradle
Maven
Requirements
This library requires Java 8 or later.Usage
Client configuration
Configure the client using system properties or environment variables:| Setter | System property | Environment variable | Required | Default value |
|---|---|---|---|---|
apiKey | telnyx.apiKey | TELNYX_API_KEY | true | - |
baseUrl | telnyx.baseUrl | TELNYX_BASE_URL | true | "https://api.telnyx.com/v2" |
[!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, callwithOptions() on any client or service:
withOptions() method does not affect the original client or service.
Requests and responses
To send a request to the Telnyx API, build an instance of someParams 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.calls().dial(...) should be called with an instance of CallDialParams, and it will return an instance of CallDialResponse.
Immutability
Each class in the SDK has an associated builder or factory method for constructing it. Each class is immutable once constructed. If the class has an associated builder, then it has atoBuilder() 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 theasync() method:
CompletableFutures.
File uploads
The SDK defines methods that accept files. To upload a file, pass aPath:
InputStream:
byte[] array:
Path its filename is unknown so it will not be included in the request. To manually set a filename, pass a MultipartField:
Binary responses
The SDK defines methods that return binary responses, which are used for API responses that shouldn’t necessarily be parsed, like non-JSON data. These methods returnHttpResponse:
Files.copy(...) method:
OutputStream:
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 withwithRawResponse():
Error handling
The SDK throws custom unchecked exception types:-
TelnyxServiceException: Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code: -
TelnyxIoException: I/O networking errors. -
TelnyxRetryableException: Generic error indicating a failure that could be retried by the client. -
TelnyxInvalidDataException: 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. -
TelnyxException: 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
The SDK uses the standard OkHttp logging interceptor. Enable logging by setting theTELNYX_LOG environment variable to info:
debug for more verbose logging:
ProGuard and R8
Although the SDK uses reflection, it is still usable with ProGuard and R8 becausetelnyx-java-core is published with a configuration file containing keep rules.
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 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 thecheckJacksonVersionCompatibility on TelnyxOkHttpClient or TelnyxOkHttpClientAsync.
[!CAUTION] We make no guarantee that the SDK works correctly when the Jackson version check is disabled.
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
maxRetries method:
Timeouts
Requests time out after 1 minute by default. To set a custom timeout, configure the method call using thetimeout method:
Proxies
To route requests through a proxy, configure the client using theproxy method:
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:
Custom HTTP client
The SDK consists of three artifacts:telnyx-java-core- Contains core SDK logic
- Does not depend on OkHttp
- Exposes
TelnyxClient,TelnyxClientAsync,TelnyxClientImpl, andTelnyxClientAsyncImpl, all of which can work with any HTTP client
telnyx-java-client-okhttp- Depends on OkHttp
- Exposes
TelnyxOkHttpClientandTelnyxOkHttpClientAsync, which provide a way to constructTelnyxClientImplandTelnyxClientAsyncImpl, respectively, using OkHttp
telnyx-java- Depends on and exposes the APIs of both
telnyx-java-coreandtelnyx-java-client-okhttp - Does not have its own logic
- Depends on and exposes the APIs of both
Customized OkHttpClient
[!TIP] Try the available network options before replacing the default client.To use a customized
OkHttpClient:
- Replace your
telnyx-javadependency withtelnyx-java-core - Copy
telnyx-java-client-okhttp’sOkHttpClientclass into your code and customize it - Construct
TelnyxClientImplorTelnyxClientAsyncImpl, similarly toTelnyxOkHttpClientorTelnyxOkHttpClientAsync, using your customized client
Completely custom HTTP client
To use a completely custom HTTP client:- Replace your
telnyx-javadependency withtelnyx-java-core - Write a class that implements the
HttpClientinterface - Construct
TelnyxClientImplorTelnyxClientAsyncImpl, similarly toTelnyxOkHttpClientorTelnyxOkHttpClientAsync, 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 theputAdditionalHeader, putAdditionalQueryParam, or putAdditionalBodyProperty methods on any Params class:
_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:
_additionalProperties() method.
To set a documented parameter or property to an undocumented or not yet supported value, pass a JsonValue object to its setter:
JsonValue is using its from(...) method:
Builder class’s build method will throw IllegalStateException if any required parameter or property is unset.
To forcibly omit a required parameter or property, pass JsonMissing:
Response properties
To access undocumented response properties, call the_additionalProperties() method:
_ prefixed method:
Response validation
In rare cases, the API may return a response that doesn’t match the expected type. For example, the SDK may expect a property to contain aString, but the API could return something else.
By default, the SDK will not throw an exception in this case. It will throw TelnyxInvalidDataException only if you directly access the property.
If you would prefer to check that the response is completely well-typed upfront, then either call validate():
responseValidation method:
FAQ
Why don’t you use plain enum classes?
Java enum classes are not trivially forwards compatible. Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.
Why do you represent fields using JsonField<T> instead of just plain T?
Using JsonField<T> enables a few features:
- Allowing usage of undocumented API functionality
- Lazily validating the API response against the expected shape
- Representing absent vs explicitly null values
Why don’t you use data classes?
It is not backwards compatible to add new fields to a data class and we don’t want to introduce a breaking change every time we add a field to a class.
Why don’t you use checked exceptions?
Checked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason. Checked exceptions:- Are verbose to handle
- Encourage error handling at the wrong level of abstraction, where nothing can be done about the error
- Are tedious to propagate due to the function coloring problem
- Don’t play well with lambdas (also due to the function coloring problem)
Semantic versioning
This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:- Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
- Changes that we do not expect to impact the vast majority of users in practice.