Learn how the Square Java SDK supports the common Square API features.
Some of the Square API patterns are used across various APIs. These include the following:
- Pagination - Many Square API operations limit the size of the response. When the result of the API operation exceeds the limit, the API truncates the result. You must make a series of requests to retrieve all the data. This is referred to as pagination.
- Idempotency key - Most Square APIs that perform create, update, or delete operations require idempotency keys to protect against making duplicate calls that can have negative consequences (for example, charging a card on file twice).
- Object versioning - Some Square resources (for example, the
Customer
object) have versions assigned. The version numbers enable optimistic concurrency, which is the ability for multiple transactions to complete without interfering with each other. - Clear API object fields - Square API update endpoints that support sparse updates allow you to clear fields by setting the value to
null
. Note thatupdateOrderAsync
requires anX-Clear-Null: true
HTTP header to indicate that the request contains anull
field update.
These Square API patterns are exposed in the Square Java SDK.
Square API pagination support lets you split a full query result set into pages that are retrieved over a sequence of requests. For example, when you call listCustomersAsync
, you can limit the number of customers returned in the response. If there are more customers to retrieve, the response includes a pagination cursor. You include this cursor in your subsequent listCustomersAsync
request to retrieve the next set of customers. When the response no longer returns a cursor (the cursor is null), there are no more customers to retrieve.
The following code example calls the listCustomersAsync
method. The request limits the number of customers returned to 10. The do...while
loop repeats while the pagination cursor isn't null. After the first listCustomersAsync
call, the subsequent call includes the pagination cursor returned by the previous call.
CustomersApi customersApi = client.getCustomersApi();
int limit = 10;
customersApi.listCustomersAsync(
null,
limit,
"DEFAULT",
"DESC",
false)
.thenAccept(result -> {
List<Customer> custs = result.getCustomers();
while (custs != null && !custs.isEmpty()) {
for (Customer cust : result.getCustomers()) {
System.out.printf(
"customer: ID: %s, Version: %s, Given name: %s, Family name: %s\n",
cust.getId(), cust.getVersion(),
cust.getGivenName(), cust.getFamilyName());
}
String c = result.getCursor();
if (c != null && !c.isEmpty()) {
result = customersApi.listCustomersAsync(
c,
limit,
"DEFAULT",
"DESC",
false)
.join();
custs = result.getCustomers();
} else {
break;
}
}
}).exceptionally(exception -> {
try {
throw exception.getCause();
} catch (ApiException ae) {
for (Error err : ae.getErrors()) {
System.out.println(err.getCategory());
System.out.println(err.getCode());
System.out.println(err.getDetail());
}
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}).join();
When an application calls a Square API, it must be able to repeat an API operation when needed and get the same result each time. For example, if a network error occurs while updating a catalog item, the application might retry the same request and must ensure that the item updates only once.
This behavior is called idempotency. Most Square APIs that modify data (create, update, or delete) require you to provide an idempotency key that uniquely identifies the request. This allows you to retry the request if necessary, without duplicating work.
You can provide a custom unique key or simply generate one. There are language specific functions that you can use to generate unique keys. For more information, see Idempotency.
Some Square API resources support versioning. For example, each Customer
object has a version field. Initially, the version number is 0. Each update increases the version number. If you don't specify a version number in the request, the latest version is assumed.
This resource version number enables optimistic concurrency; multiple transactions can complete without interfering with each other. As a best practice, you should include the version field in the request to enable optimistic concurrency. The value must be set to the current version. For more information, see Optimistic Concurrency.
The following code example updates a customer name. The update request also includes a version number. It succeeds only if the specified version number is the latest version of the Customer
object on the server.
UpdateCustomerRequest body = new UpdateCustomerRequest.Builder()
.givenName("Fred")
.familyName("Jones")
.version(7L)
.build();
customersApi.updateCustomerAsync("GZ48C4P2CWVXV7F7K2ZH795RSG", body)
.thenAccept(result -> {
System.out.printf(
"customer updated:\n Id: %s, Version:{%s} Given name:{%s}, Family name: {%s}",
result.getCustomer().getId(),
result.getCustomer().getVersion(),
result.getCustomer().getGivenName(),
result.getCustomer().getFamilyName());
}).exceptionally(exception -> {
try {
throw exception.getCause();
} catch (ApiException ae) {
for (Error err : ae.getErrors()) {
System.out.println(err.getCategory());
System.out.println(err.getCode());
System.out.println(err.getDetail());
}
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}).join();
For update operations that support sparse updates, your request only needs to specify the fields you want to change (along with any fields required by the update operation). If you want to clear a field without setting a new value, set its value to null
. For more information, see Clear a field with a null.
The following updateLocationAsync
example clears the twitterUsername
field and sets the websiteUrl
field:
package com.square.examples;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.squareup.square.*;
import com.squareup.square.api.*;
import com.squareup.square.authentication.BearerAuthModel;
import com.squareup.square.models.*;
import com.squareup.square.models.Error;
import com.squareup.square.exceptions.*;
public class UpdateLocation {
public static void main(String[] args) {
InputStream inputStream =
UpdateLocation.class.getResourceAsStream("/config.properties");
Properties prop = new Properties();
try {
prop.load(inputStream);
} catch (IOException e) {
System.out.println("Error reading properties file");
e.printStackTrace();
}
SquareClient client = new SquareClient.Builder()
.bearerAuthCredentials(new BearerAuthModel.Builder(prop.getProperty("SQUARE_ACCESS_TOKEN")).build())
.environment(Environment.SANDBOX)
.build();
String location_id = "M8AKAD8160XGR";
Location loc = new Location.Builder()
.twitterUsername(null)
.websiteUrl("https://developer.squareup.com")
.build();
UpdateLocationRequest body = new UpdateLocationRequest.Builder()
.location(loc)
.build();
LocationsApi locationsApi = client.getLocationsApi();
locationsApi.updateLocationAsync(location_id, body)
.thenAccept(result -> {
Location location = result.getLocation();
System.out.println(location);
}).exceptionally(exception -> {
try {
throw exception.getCause();
} catch (ApiException ae) {
for (Error err : ae.getErrors()) {
System.out.println(err.getCategory());
System.out.println(err.getCode());
System.out.println(err.getDetail());
}
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}).join();
SquareClient.shutdown();
}
}
updateOrderAsync
requests require an additional header.
If you're using null
to clear fields in an order, you must add the X-Clear-Null: true
HTTP header to signal your intention. In the Square Java SDK, the SquareClient
class provides an additionalHeaders
parameter that you can use for this purpose:
import com.squareup.square.http.Headers;
...
Headers headers = new Headers() {{
add("X-Clear-Null","true");
}};
SquareClient client = new SquareClient.Builder()
.bearerAuthCredentials(new BearerAuthModel.Builder(prop.getProperty("SQUARE_ACCESS_TOKEN")).build())
.environment(Environment.SANDBOX)
.additionalHeaders(headers)
.build();