Skip to content

Latest commit

History

8 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Table of Contentsgenerated with DocToc

JAVA SDK for Postmen API. For problems and suggestions, please open a GitHub Issue.

Installation

Requirements

JVM version >= 1.6. tested on

  • oraclejdk8
  • openjdk7
  • openjdk6

Manual Installation

  • Download release from this repository
  • Add to class path

Using Maven

(no info yet)

Using Gradle

(no info yet)

Quickstart

In order to get API key and choose a region refer to the documentation.

// create configConfigconfig = newConfigBuilder().setRegion("sandbox").setApiKey(apiKey).build();
// instantiate label serviceLabelServiceservice = newLabelService(config);
try {
// get labels you have already createdLabelslabels = service.get();
// prints object into the consoleExampleHelper.printObj(labels);
} catch (IOExceptione) {
e.printStackTrace();
}

API References (Link to JavaDocs)

Configuration

Instantiate a ConfigBuilder class, set options, and then use the build() method.

ConfigBuildercb = newConfigBuilder();
Configconfig = cb.set(apiKey).setRetry(false).build();
parameterexplanation
apiKeyyour api key to access Postmen
regionchoose which region you are using (sandbox or production)
endpointsets a custom endpoint (ignores version and region if populated)
versionversion of the api (used in conjunction with region)
proxyUrlUrl of the proxy
proxyPortPort of the proxy (default: 80)
retryretry if there are errors (default: true)
ratehelps you handle the rate limit (default: true)

Proxy

The sdk only allows defining proxy url and proxy port. If you are using socks proxy, then please check JVM systemwide proxy configuration

Changing the configuration of an instantiated Service Class

Configconfig = LabelService.getConfig();
config.setProxy("some.proxy.com");
// applies the recent configurationservice.reInitialize();

Service Classes

Instantiate a specific Service Class that will help you process Label, Rate, Manifest, Cancel Label or Address

Transaction TypeService Class
Label TransactionsLabelService
Rate TransactionsRateService
Manifest TransactionsManifestService
Cancel Label TransactionsCancelLabelService
Address TransactionsAddressService

service.create(Request Object);

Creates either a label, rate, manifest, cancel label or address validation depending on the instantiate service class

service.get();

Gets a List of objects you have

service.getWithParam(Map<String, String> query)

Gets a list of objects you have filtered by a query parameter in a Map

service.getWithParam(String query)

Gets a list of objects you have filtered by a query string

service.getById(String id)

Gets an object by Id

service.createAsync(Object); (This is in beta)

Future<LabelResponse> f = service.createAsync(req);
// do other things then retrieve// remember, .get() is a blocking callLabelResponselabelResponse = f.get();
Labellabel = labelResponse.getData();

Custom Request Config

If you want to use a different configuration for a certain request, you can do this:

// don't forget to clone, otherwise you might override the existing configConfignewConfig = service.getConfig().clone();
newConfig.setRetry(false);
Service.create(Object, newConfig);

Generic Methods available in Service Classes

callAsMap(String method, String path, Object body)

// returns a Map Response, do response.getData() to get the Map ObjectMapResponseresponse = LabelService.callAsMap("GET", "", null);
Map<Object, Object> map = response.getData();

callAsRaw(String method, String path, Object body)

// returns the raw json string responseStringresponse = LabelService.callAsRaw("GET", "", null);

Request Objects

you have to either pass a Request Object or a JSON Object to the Service class in order to make a request. There are 4 main Request Objects:

  1. LabelRequest
  2. RateRequest
  3. ManifestRequest
  4. CancelLabelRequest
  5. AddressRequest

Creating a Label example:

LabelRequestreq = newLabelRequest();
req.setAsync(false);
req.setServiceType("spsr_intl");
ShipperAccountshipperAccount = newShipperAccount(getShipperAccount());
req.setShipperAccount(shipperAccount);
Parcelparcel = newParcel();
parcel.setDescription("Parcel");
parcel.setBoxType("custom");
parcel.setWeight(newWeight(1.5, "kg"));
parcel.setDimension(newDimension(20, 30, 30, "cm"));
Itemitem = newItem();
item.setDescription("Food Bar");
item.setOriginCountry("USA");
item.setQuantity(2);
item.setPrice(newMoney(50, "USD"));
item.setWeight(newWeight(0.6, "kg"));
item.setSku("Epic_Food_Bar");
item.setHsCode("7877966");
parcel.addItems(item);
AddressshipFrom = newAddress();
shipFrom.setContactName("Joe Smith");
shipFrom.setCompanyName("Aftership");
shipFrom.setStreet1("bal");
shipFrom.setCity("NT");
shipFrom.setState("HK");
shipFrom.setPostalCode("N/A");
shipFrom.setCountry("HKG");
shipFrom.setPhone("123456789");
shipFrom.setEmail("mail@mail.com");
shipFrom.setType("business");
AddressshipTo = newAddress();
shipTo.setContactName("Jon Poole");
shipTo.setStreet1("test");
shipTo.setCity("Concord");
shipTo.setState("New Hampshire");
shipTo.setPostalCode("03301");
shipTo.setCountry("RUS");
shipTo.setPhone("12345");
shipTo.setEmail("test@test.com");
shipTo.setType("residential");
Shipmentshipment = newShipment();
shipment.addParcels(parcel);
shipment.setShipFrom(shipFrom);
shipment.setShipTo(shipTo);
req.setShipment(shipment);
Customscustoms = newCustoms();
customs.setPurpose("gift");
customs.setTermsOfTrade("ddu");
req.setCustoms(customs);
LabelServiceservice = newLabelService(config);
service.create(req);

Response Object

There are also 4 types of Response Objects

  1. LabelResponse
  2. RateResponse
  3. ManifestResponse
  4. CancelLabelResponse
  5. AddressResponse
LabelResponseresponse = labelService.create(req);
Labellabel = response.getData();
// label contains your label info

Retry Strategy

Rate Limit

if you set config.setRate(true), the sdk will help you handle the rate limit.

Retryable Error

if you set config.setRetry(true), the sdk will help you retry for errors returned by the server. There will be 5 retries, and then the SDK will throw a PostmenException. To catch the error:

try {
labelService.create(req);
} catch (PostmenExceptione) {
// returns the response of the API serverResponseresponse = e.getResponse()
// returns the messagee.getMessage();
} catch (IOExceptione1) {
}

Remember to catch PostmenException before IOException since PostmenException is a child of IOException.

ErrorHandling

As long as you set config.setRetry(true), the sdk will help you retry the request for 4 times, each with an increasing delay.

retrydelay
11s
22s
34s
48s

After the 4th retry, the service class will throw PostmenException. You may choose to catch or not to catch the error since the parent class of PostmenException is IOException. Available method for PostmenException:

MethodReturn TrypeExplanation
getCode()IntegerError code
isRetryable()BooleanIndicates if error is retryable
getMessage()StringError message (e.g. The request was invalid or cannot be otherwise served)
getDetails()ArrayError details (e.g. Destination country must be RUS or KAZ)

Examples

There are 5 example class in com.postmen.javasdk. To run, simple choose an operation and provide your API KEY.

Change the API key in CredentialHelper

FileDescription
RateExample.create()rates object creation
RateExample.get()rates object(s) retrieve
LabelExample.create()labels object creation
LabelExample.get()labels object(s) retrieve
ManifestExample.create()manifests object creation
ManifestExample.get()manifests object(s) retrieve
CancelLabelExample.create()cancel-labels object creation
CancelLabelExample.get()cancel-labels object(s) retrieve
AddressExample.create()address validation

Testing

if you want to contribute to the SDK, run the automated unit test before making a pull request. mvn test

License

Released under the MIT license. See the LICENSE file for details.

Contributors

  • Heinrich Chan -
  • Kyle Yang -

About

AfterShip Shipping (Postmen) API Client Library for Java (USPS, FedEx, UPS, DHL and more)

Topics

Resources

Stars

8 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages