Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

1 star

Watchers

3 watching

Forks

Repository files navigation

Shippo logo Shippo Java SDK

Shippo is a shipping API that connects you with multiple shipping carriers (such as USPS, UPS, DHL, Canada Post, Australia Post, and many others) through one interface.

You must register for a Shippo account to use our API. It's free to sign up. Only pay to print a live label, test labels are free.

To use the API, you must generate an API Token. In the following examples, replace <YOUR_API_KEY_HERE> with your own token.

For example.

Shippo sdk = Shippo.builder()
    .apiKeyHeader("<YOUR_API_KEY_HERE>")
    .build();

Summary

Shippo external API.: Use this API to integrate with the Shippo service

Table of Contents

SDK Installation

Getting started

JDK 11 or later is required.

The samples below show how a published SDK artifact is used:

Gradle:

implementation 'com.goshippo:shippoSDK:1.0.0-beta.1'

Maven:

<dependency>
    <groupId>com.goshippo</groupId>
    <artifactId>shippoSDK</artifactId>
    <version>1.0.0-beta.1</version>
</dependency>

How to build

After cloning the git repository to your file system you can build the SDK artifact from source to the build directory by running ./gradlew build on *nix systems or gradlew.bat on Windows systems.

If you wish to build from source and publish the SDK artifact to your local Maven repository (on your filesystem) then use the following command (after cloning the git repo locally):

On *nix:

./gradlew publishToMavenLocal -Pskip.signing

On Windows:

gradlew.bat publishToMavenLocal -Pskip.signing

SDK Example Usage

Example

package hello.world;

import com.goshippo.shippo_sdk.Shippo;
import com.goshippo.shippo_sdk.models.operations.ListAddressesResponse;

import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Exception {

        Shippo sdk = Shippo.builder()
                .apiKeyHeader("<YOUR_API_KEY_HERE>")
                .shippoApiVersion("2018-02-08")
                .build();

        ListAddressesResponse res = sdk.addresses().list()
                .page(1L)
                .results(5L)
                .shippoApiVersion("2018-02-08")
                .call();

        if (res.addressPaginatedList().isPresent()) {
            // handle response
        }
    }
}

Available Resources and Operations

Available methods
  • list - List all addresses
  • create - Create a new address
  • get - Retrieve an address
  • validate - Validate an address
  • list - List all carrier parcel templates
  • get - Retrieve a carrier parcel templates
  • list - List all customs declarations
  • create - Create a new customs declaration
  • get - Retrieve a customs declaration
  • list - List all customs items
  • create - Create a new customs item
  • get - Retrieve a customs item
  • list - List all manifests
  • create - Create a new manifest
  • get - Retrieve a manifest
  • list - List all orders
  • create - Create a new order
  • get - Retrieve an order
  • list - List all parcels
  • create - Create a new parcel
  • get - Retrieve an existing parcel
  • create - Create a refund
  • list - List all refunds
  • get - Retrieve a refund
  • list - List all service groups
  • create - Create a new service group
  • update - Update an existing service group
  • delete - Delete a service group
  • list - List all shipments
  • create - Create a new shipment
  • get - Retrieve a shipment
  • list - List all Shippo Accounts
  • create - Create a Shippo Account
  • get - Retrieve a Shippo Account
  • update - Update a Shippo Account
  • create - Register a tracking webhook
  • get - Get a tracking status
  • list - List all shipping labels
  • create - Create a shipping label
  • get - Retrieve a shipping label
  • list - List all user parcel templates
  • create - Create a new user parcel template
  • delete - Delete a user parcel template
  • get - Retrieves a user parcel template
  • update - Update an existing user parcel template

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!

About Shippo

Connect with multiple different carriers, get discounted shipping labels, track parcels, and much more with just one integration. You can use your own carrier accounts or take advantage of our discounted rates with the Shippo carrier accounts. Using Shippo makes it easy to deal with multiple carrier integrations, rate shopping, tracking and other parts of the shipping workflow. We provide the API and web app for all your shipping needs.

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.

ShippoException is the base class for all HTTP error responses. It has the following properties:

Method Type Description
message() String Error message
code() int HTTP response status code eg 404
headers Map<String, List<String>> HTTP response headers
body() byte[] HTTP body as a byte array. Can be empty array if no body is returned.
bodyAsString() String HTTP body as a UTF-8 string. Can be empty string if no body is returned.
rawResponse() HttpResponse<?> Raw HTTP response (body already read and not available for re-read)

Example

package hello.world;

import com.goshippo.shippo_sdk.Shippo;
import com.goshippo.shippo_sdk.models.errors.*;
import com.goshippo.shippo_sdk.models.operations.InitiateOauth2SigninResponse;
import java.io.UncheckedIOException;
import java.lang.Exception;
import java.lang.String;
import java.util.Optional;

public class Application {

    public static void main(String[] args) throws InitiateOauth2SigninResponseBody, InitiateOauth2SigninCarrierAccountsResponseResponseBody, InitiateOauth2SigninCarrierAccountsResponseBody, Exception {

        Shippo sdk = Shippo.builder()
                .shippoApiVersion("2018-02-08")
                .apiKeyHeader(System.getenv().getOrDefault("API_KEY_HEADER", ""))
            .build();
        try {

            InitiateOauth2SigninResponse res = sdk.carrierAccounts().initiateOauth2Signin()
                    .carrierAccountObjectId("<id>")
                    .redirectUri("https://ashamed-reporter.biz")
                    .call();

            // handle response
        } catch (ShippoException ex) { // all SDK exceptions inherit from ShippoException

            // ex.ToString() provides a detailed error message including
            // HTTP status code, headers, and error payload (if any)
            System.out.println(ex);

            // Base exception fields
            var rawResponse = ex.rawResponse();
            var headers = ex.headers();
            var contentType = headers.first("Content-Type");
            int statusCode = ex.code();
            Optional<byte[]> responseBody = ex.body();

            // different error subclasses may be thrown 
            // depending on the service call
            if (ex instanceof InitiateOauth2SigninResponseBody) {
                var e = (InitiateOauth2SigninResponseBody) ex;
                // Check error data fields
                e.data().ifPresent(payload -> {
                      Optional<String> title = payload.title();
                      Optional<String> detail = payload.detail();
                });
            }

            // An underlying cause may be provided. If the error payload 
            // cannot be deserialized then the deserialization exception 
            // will be set as the cause.
            if (ex.getCause() != null) {
                var cause = ex.getCause();
            }
        } catch (UncheckedIOException ex) {
            // handle IO error (connection, timeout, etc)
        }    }
}

Error Classes

Primary error:

Less common errors (9)

Network errors:

  • java.io.IOException (always wrapped by java.io.UncheckedIOException). Commonly encountered subclasses of IOException include java.net.ConnectException, java.net.SocketTimeoutException, EOFException (there are many more subclasses in the JDK platform).

Inherit from ShippoException:

* Check the method documentation to see if the error is applicable.

Server Selection

Override Server URL Per-Client

The default server can be overridden globally using the .serverURL(String serverUrl) builder method when initializing the SDK client instance. For example:

package hello.world;

import com.goshippo.shippo_sdk.Shippo;
import com.goshippo.shippo_sdk.models.operations.ListAddressesResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Exception {

        Shippo sdk = Shippo.builder()
                .serverURL("https://api.goshippo.com")
                .shippoApiVersion("2018-02-08")
                .apiKeyHeader(System.getenv().getOrDefault("API_KEY_HEADER", ""))
            .build();

        ListAddressesResponse res = sdk.addresses().list()
                .page(1L)
                .results(5L)
                .call();

        if (res.addressPaginatedList().isPresent()) {
            System.out.println(res.addressPaginatedList().get());
        }
    }
}

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
apiKeyHeader apiKey API key

To authenticate with the API the apiKeyHeader parameter must be set when initializing the SDK client instance. For example:

package hello.world;

import com.goshippo.shippo_sdk.Shippo;
import com.goshippo.shippo_sdk.models.operations.ListAddressesResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Exception {

        Shippo sdk = Shippo.builder()
                .apiKeyHeader(System.getenv().getOrDefault("API_KEY_HEADER", ""))
                .shippoApiVersion("2018-02-08")
            .build();

        ListAddressesResponse res = sdk.addresses().list()
                .page(1L)
                .results(5L)
                .call();

        if (res.addressPaginatedList().isPresent()) {
            System.out.println(res.addressPaginatedList().get());
        }
    }
}

Per-Operation Security Schemes

Some operations in this SDK require the security scheme to be specified at the request level. For example:

package hello.world;

import com.goshippo.shippo_sdk.Shippo;
import com.goshippo.shippo_sdk.models.components.EmbeddedAuthorizationRequest;
import com.goshippo.shippo_sdk.models.operations.CreateEmbeddedAuthorizationResponse;
import com.goshippo.shippo_sdk.models.operations.CreateEmbeddedAuthorizationSecurity;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Exception {

        Shippo sdk = Shippo.builder()
                .shippoApiVersion("2018-02-08")
            .build();

        CreateEmbeddedAuthorizationResponse res = sdk.embeddedAuthorization().create()
                .security(CreateEmbeddedAuthorizationSecurity.builder()

                    .build())
                .shippoAccountId("e0b382dc7d754c0ca6358c09d5d2bdf7")
                .embeddedAuthorizationRequest(EmbeddedAuthorizationRequest.builder()
                    .scope("embedded:carriers")
                    .build())
                .call();

        if (res.embeddedAuthorization().isPresent()) {
            System.out.println(res.embeddedAuthorization().get());
        }
    }
}

Custom HTTP Client

The Java SDK makes API calls using an HTTPClient that wraps the native HttpClient. This client provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The HTTPClient interface allows you to either use the default SpeakeasyHTTPClient that comes with the SDK, or provide your own custom implementation with customized configuration such as custom executors, SSL context, connection pools, and other HTTP client settings.

The interface provides synchronous (send) methods.

The following example shows how to add a custom header and handle errors:

import com.goshippo.shippo_sdk.Shippo;
import com.goshippo.shippo_sdk.utils.HTTPClient;
import com.goshippo.shippo_sdk.utils.SpeakeasyHTTPClient;
import com.goshippo.shippo_sdk.utils.Utils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.time.Duration;

public class Application {
    public static void main(String[] args) {
        // Create a custom HTTP client with hooks
        HTTPClient httpClient = new HTTPClient() {
            private final HTTPClient defaultClient = new SpeakeasyHTTPClient();
            
            @Override
            public HttpResponse<InputStream> send(HttpRequest request) throws IOException, URISyntaxException, InterruptedException {
                // Add custom header and timeout using Utils.copy()
                HttpRequest modifiedRequest = Utils.copy(request)
                    .header("x-custom-header", "custom value")
                    .timeout(Duration.ofSeconds(30))
                    .build();
                    
                try {
                    HttpResponse<InputStream> response = defaultClient.send(modifiedRequest);
                    // Log successful response
                    System.out.println("Request successful: " + response.statusCode());
                    return response;
                } catch (Exception error) {
                    // Log error
                    System.err.println("Request failed: " + error.getMessage());
                    throw error;
                }
            }
        };

        Shippo sdk = Shippo.builder()
            .client(httpClient)
            .build();
    }
}
Custom HTTP Client Configuration

You can also provide a completely custom HTTP client with your own configuration:

import com.goshippo.shippo_sdk.Shippo;
import com.goshippo.shippo_sdk.utils.HTTPClient;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.time.Duration;
import java.util.concurrent.Executors;

public class Application {
    public static void main(String[] args) {
        // Custom HTTP client with custom configuration
        HTTPClient customHttpClient = new HTTPClient() {
            private final HttpClient client = HttpClient.newBuilder()
                .executor(Executors.newFixedThreadPool(10))
                .connectTimeout(Duration.ofSeconds(30))
                // .sslContext(customSslContext) // Add custom SSL context if needed
                .build();

            @Override
            public HttpResponse<InputStream> send(HttpRequest request) throws IOException, URISyntaxException, InterruptedException {
                return client.send(request, HttpResponse.BodyHandlers.ofInputStream());
            }
        };

        Shippo sdk = Shippo.builder()
            .client(customHttpClient)
            .build();
    }
}

You can also enable debug logging on the default SpeakeasyHTTPClient:

import com.goshippo.shippo_sdk.Shippo;
import com.goshippo.shippo_sdk.utils.SpeakeasyHTTPClient;

public class Application {
    public static void main(String[] args) {
        SpeakeasyHTTPClient httpClient = new SpeakeasyHTTPClient();
        httpClient.enableDebugLogging(true);

        Shippo sdk = Shippo.builder()
            .client(httpClient)
            .build();
    }
}

Debugging

Debug

You can setup your SDK to emit debug logs for SDK requests and responses.

For request and response logging (especially json bodies), call enableHTTPDebugLogging(boolean) on the SDK builder like so:

SDK.builder()
    .enableHTTPDebugLogging(true)
    .build();

Example output:

Sending request: http://localhost:35123/bearer#global GET
Request headers: {Accept=[application/json], Authorization=[******], Client-Level-Header=[added by client], Idempotency-Key=[some-key], x-speakeasy-user-agent=[speakeasy-sdk/java 0.0.1 internal 0.1.0 org.openapis.openapi]}
Received response: (GET http://localhost:35123/bearer#global) 200
Response headers: {access-control-allow-credentials=[true], access-control-allow-origin=[*], connection=[keep-alive], content-length=[50], content-type=[application/json], date=[Wed, 09 Apr 2025 01:43:29 GMT], server=[gunicorn/19.9.0]}
Response body:
{
  "authenticated": true, 
  "token": "global"
}

WARNING: This logging should only be used for temporary debugging purposes. Leaving this option on in a production system could expose credentials/secrets in logs. Authorization headers are redacted by default and there is the ability to specify redacted header names via SpeakeasyHTTPClient.setRedactedHeaders.

NOTE: This is a convenience method that calls HTTPClient.enableDebugLogging(). The SpeakeasyHTTPClient honors this setting. If you are using a custom HTTP client, it is up to the custom client to honor this setting.

Another option is to set the System property -Djdk.httpclient.HttpClient.log=all. However, this second option does not log bodies.

Jackson Configuration

The SDK ships with a pre-configured Jackson ObjectMapper accessible via JSON.getMapper(). It is set up with type modules, strict deserializers, and the feature flags needed for full SDK compatibility (including ISO-8601 OffsetDateTime serialization):

import com.goshippo.shippo_sdk.utils.JSON;

String json = JSON.getMapper().writeValueAsString(response);

To compose with your own ObjectMapper, register the provided ShippoSDKJacksonModule, which bundles all the same modules and feature flags as a single plug-and-play module:

import com.goshippo.shippo_sdk.utils.ShippoSDKJacksonModule;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper myMapper = new ObjectMapper()
    .registerModule(new ShippoSDKJacksonModule());

String json = myMapper.writeValueAsString(response);

About

No description, website, or topics provided.

Resources

Contributing

Stars

1 star

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages