Developer-friendly & type-safe Java SDK specifically catered to leverage openapi API.
Important
This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
Gusto API: Welcome to Gusto's Embedded Payroll API documentation!
JDK 11 or later is required.
The samples below show how a published SDK artifact is used:
Gradle:
implementation 'com.gusto:embedded-api:0.3.2'Maven:
<dependency>
<groupId>com.gusto</groupId>
<artifactId>embedded-api</artifactId>
<version>0.3.2</version>
</dependency>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.signingOn Windows:
gradlew.bat publishToMavenLocal -Pskip.signingpackage hello.world;
import com.gusto.embedded_api.GustoEmbedded;
import com.gusto.embedded_api.models.operations.GetV1TokenInfoResponse;
import com.gusto.embedded_api.models.operations.XGustoAPIVersion;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws Exception {
GustoEmbedded sdk = GustoEmbedded.builder()
.companyAccessAuth(System.getenv().getOrDefault("COMPANY_ACCESS_AUTH", ""))
.build();
GetV1TokenInfoResponse res = sdk.introspection().getInfo()
.xGustoAPIVersion(XGustoAPIVersion.TWO_THOUSAND_AND_TWENTY_FIVE_MINUS06_MINUS15)
.call();
if (res.tokenInfo().isPresent()) {
System.out.println(res.tokenInfo().get());
}
}
}An asynchronous SDK client is also available that returns a CompletableFuture<T>. See Asynchronous Support for more details on async benefits and reactive library integration.
package hello.world;
import com.gusto.embedded_api.AsyncGustoEmbedded;
import com.gusto.embedded_api.GustoEmbedded;
import com.gusto.embedded_api.models.operations.XGustoAPIVersion;
import com.gusto.embedded_api.models.operations.async.GetV1TokenInfoResponse;
import java.util.concurrent.CompletableFuture;
public class Application {
public static void main(String[] args) {
AsyncGustoEmbedded sdk = GustoEmbedded.builder()
.companyAccessAuth(System.getenv().getOrDefault("COMPANY_ACCESS_AUTH", ""))
.build()
.async();
CompletableFuture<GetV1TokenInfoResponse> resFut = sdk.introspection().getInfo()
.xGustoAPIVersion(XGustoAPIVersion.TWO_THOUSAND_AND_TWENTY_FIVE_MINUS06_MINUS15)
.call();
resFut.thenAccept(res -> {
if (res.tokenInfo().isPresent()) {
System.out.println(res.tokenInfo().get());
}
});
}
}When a response field is a union model:
- Discriminated unions: branch on the discriminator (
switch) and then narrow to the concrete type. - Non-discriminated unions: use generated accessors (for example
string(),asLong(),simpleObject()) to determine the active variant.
For full model-specific examples (including Java 11/16/21 variants), see each union model's Supported Types section in the generated model docs.
The SDK provides comprehensive asynchronous support using Java's CompletableFuture<T> and Reactive Streams Publisher<T> APIs. This design makes no assumptions about your choice of reactive toolkit, allowing seamless integration with any reactive library.
Why Use Async?
Asynchronous operations provide several key benefits:
- Non-blocking I/O: Your threads stay free for other work while operations are in flight
- Better resource utilization: Handle more concurrent operations with fewer threads
- Improved scalability: Build highly responsive applications that can handle thousands of concurrent requests
- Reactive integration: Works seamlessly with reactive streams and backpressure handling
Reactive Library Integration
The SDK returns Reactive Streams Publisher<T> instances for operations dealing with streams involving multiple I/O interactions. We use Reactive Streams instead of JDK Flow API to provide broader compatibility with the reactive ecosystem, as most reactive libraries natively support Reactive Streams.
Why Reactive Streams over JDK Flow?
- Broader ecosystem compatibility: Most reactive libraries (Project Reactor, RxJava, Akka Streams, etc.) natively support Reactive Streams
- Industry standard: Reactive Streams is the de facto standard for reactive programming in Java
- Better interoperability: Seamless integration without additional adapters for most use cases
Integration with Popular Libraries:
- Project Reactor: Use
Flux.from(publisher)to convert to Reactor types - RxJava: Use
Flowable.fromPublisher(publisher)for RxJava integration - Akka Streams: Use
Source.fromPublisher(publisher)for Akka Streams integration - Vert.x: Use
ReadStream.fromPublisher(vertx, publisher)for Vert.x reactive streams - Mutiny: Use
Multi.createFrom().publisher(publisher)for Quarkus Mutiny integration
For JDK Flow API Integration: If you need JDK Flow API compatibility (e.g., for Quarkus/Mutiny 2), you can use adapters:
// Convert Reactive Streams Publisher to Flow Publisher
Flow.Publisher<T> flowPublisher = FlowAdapters.toFlowPublisher(reactiveStreamsPublisher);
// Convert Flow Publisher to Reactive Streams Publisher
Publisher<T> reactiveStreamsPublisher = FlowAdapters.toPublisher(flowPublisher);For standard single-response operations, the SDK returns CompletableFuture<T> for straightforward async execution.
Supported Operations
Async support is available for:
- Server-sent Events: Stream real-time events with Reactive Streams
Publisher<T> - JSONL Streaming: Process streaming JSON lines asynchronously
- Pagination: Iterate through paginated results using
callAsPublisher()andcallAsPublisherUnwrapped() - File Uploads: Upload files asynchronously with progress tracking
- File Downloads: Download files asynchronously with streaming support
- Standard Operations: All regular API calls return
CompletableFuture<T>for async execution
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
|---|---|---|
companyAccessAuth |
http | HTTP Bearer |
To authenticate with the API the companyAccessAuth parameter must be set when initializing the SDK client instance. For example:
package hello.world;
import com.gusto.embedded_api.GustoEmbedded;
import com.gusto.embedded_api.models.operations.GetV1TokenInfoResponse;
import com.gusto.embedded_api.models.operations.XGustoAPIVersion;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws Exception {
GustoEmbedded sdk = GustoEmbedded.builder()
.companyAccessAuth(System.getenv().getOrDefault("COMPANY_ACCESS_AUTH", ""))
.build();
GetV1TokenInfoResponse res = sdk.introspection().getInfo()
.xGustoAPIVersion(XGustoAPIVersion.TWO_THOUSAND_AND_TWENTY_FIVE_MINUS06_MINUS15)
.call();
if (res.tokenInfo().isPresent()) {
System.out.println(res.tokenInfo().get());
}
}
}Some operations in this SDK require the security scheme to be specified at the request level. For example:
package hello.world;
import com.gusto.embedded_api.GustoEmbedded;
import com.gusto.embedded_api.models.components.VersionHeader;
import com.gusto.embedded_api.models.errors.UnprocessableEntityErrorObject;
import com.gusto.embedded_api.models.operations.*;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws UnprocessableEntityErrorObject, Exception {
GustoEmbedded sdk = GustoEmbedded.builder()
.build();
PostV1PartnerManagedCompaniesResponse res = sdk.companies().createPartnerManaged()
.security(PostV1PartnerManagedCompaniesSecurity.builder()
.systemAccessAuth(System.getenv().getOrDefault("SYSTEM_ACCESS_AUTH", ""))
.build())
.xGustoAPIVersion(VersionHeader.TWO_THOUSAND_AND_TWENTY_FIVE_MINUS06_MINUS15)
.requestBody(PostV1PartnerManagedCompaniesRequestBody.builder()
.user(User.builder()
.firstName("Frank")
.lastName("Ocean")
.email("[email protected]")
.phone("2345558899")
.build())
.company(Company.builder()
.name("Frank's Ocean, LLC")
.tradeName("Frank’s Ocean")
.ein("123456789")
.contractorOnly(false)
.build())
.build())
.call();
if (res.object().isPresent()) {
System.out.println(res.object().get());
}
}
}Available methods
- getAll - Get all ACH transactions for a company
- get - Get all company bank accounts
- create - Create a company bank account
- verify - Verify a company bank account
- createFromPlaidToken - Create a bank account from a plaid processor token
- deleteV1CompaniesCompanyIdBankAccountsBankAccountId - Delete a company bank account
- createPartnerManaged - Create a partner managed company
- get - Get a company
- update - Update a company
- getV1PartnerManagedCompaniesCompanyUuidMigrationReadiness - Check company migration readiness
- acceptTermsOfService - Accept terms of service for a company user
- retrieveTermsOfService - Retrieve terms of service status for a company user
- createAdmin - Create an admin for the company
- listAdmins - Get all the admins at a company
- getOnboardingStatus - Get company onboarding status
- finishOnboarding - Finish company onboarding
- getCustomFields - Get the custom fields of a company
- getDownloadUrl - Get a temporary url to download the Company Attachment file
- getDetails - Get Company Attachment Details
- getList - Get List of Company Attachments
- create - Create Company Attachment and Upload File
- create - Create a company benefit
- list - Get benefits for a company
- get - Get a company benefit
- update - Update a company benefit
- delete - Delete a company benefit
- getAll - Get all supported benefits
- getSupported - Get a supported benefit
- getSummary - Get company benefit summary by company benefit id.
- getEmployeeBenefits - Get all employee benefits for a company benefit
- updateEmployeeBenefits - Bulk update employee benefits for a company benefit
- getRequirements - Get benefit fields requirements by benefit type
- getV1CompanyBenefitsCompanyBenefitIdContributionExclusions - Get contribution exclusions for a company benefit
- putV1CompanyBenefitsCompanyBenefitIdContributionExclusions - Update contribution exclusions for a company benefit
- getAll - Get all company forms
- get - Get a company form
- getPdf - Get a company form pdf
- sign - Sign a company form
- getAll - Get all contractor documents
- get - Get a contractor document
- getPdf - Get the contractor document pdf
- sign - Sign a contractor document
- list - Get all contractor forms
- get - Get a contractor form
- getPdf - Get the contractor form pdf
- generate1099 - Generate a 1099 form [DEMO]
- getList - Get contractor payment groups for a company
- create - Create a contractor payment group
- preview - Preview a contractor payment group
- get - Get a contractor payment group
- delete - Cancel a contractor payment group
- fund - Fund a contractor payment group [DEMO]
- getV1ContractorPaymentGroupsIdPartnerDisbursements - Get partner disbursements for a contractor payment group
- patchV1ContractorPaymentGroupsIdPartnerDisbursements - Update partner disbursements for a contractor payment group
- getBankAccounts - Get all contractor bank accounts
- get - Get a contractor's payment method
- update - Update a contractor's payment method
- createBankAccount - Create a contractor bank account
- getReceipt - Get a single contractor payment receipt
- fund - Fund a contractor payment [DEMO]
- create - Create a contractor payment
- list - Get contractor payments for a company
- get - Get a single contractor payment
- delete - Cancel a contractor payment
- preview - Preview contractor payment debit date
- create - Create a contractor
- list - Get contractors of a company
- get - Get a contractor
- update - Update a contractor
- delete - Delete a contractor
- getOnboardingStatus - Get the contractor's onboarding status
- updateOnboardingStatus - Change the contractor's onboarding status
- getAddress - Get a contractor address
- updateAddress - Create or update a contractor's address
- getV1CompaniesCompanyIdContractorsPaymentDetails - List contractor payment details
- create - Create a department
- getAll - Get all departments of a company
- get - Get a department
- update - Update a department
- delete - Delete a department
- addPeople - Add people to a department
- removePeople - Remove people from a department
- create - Create a custom earning type
- list - Get all earning types for a company
- update - Update an earning type
- delete - Deactivate an earning type
- get - Get an employee's home addresses
- create - Create an employee's home address
- retrieveHomeAddress - Get an employee's home address
- update - Update an employee's home address
- delete - Delete an employee's home address
- getWorkAddresses - Get an employee's work addresses
- createWorkAddress - Create an employee work address
- retrieveWorkAddress - Get an employee work address
- updateWorkAddress - Update an employee work address
- deleteWorkAddress - Delete an employee's work address
- create - Create an employee benefit
- get - Get all benefits for an employee
- retrieve - Get an employee benefit
- update - Update an employee benefit
- delete - Delete an employee benefit
- getYtdBenefitAmountsFromDifferentCompany - Get year-to-date benefit amounts from a different company
- createYtdBenefitAmountsFromDifferentCompany - Create year-to-date benefit amounts from a different company
- getV1EmployeesEmployeeUuidSection603HighEarnerStatuses - Get all Section 603 high earner statuses for an employee
- postV1EmployeesEmployeeUuidSection603HighEarnerStatuses - Create a Section 603 high earner status
- getV1EmployeesEmployeeUuidSection603HighEarnerStatusesEffectiveYear - Get a Section 603 high earner status for a specific year
- patchV1EmployeesEmployeeUuidSection603HighEarnerStatusesEffectiveYear - Update a Section 603 high earner status
- createTermination - Create an employee termination
- getTerminations - Get terminations for an employee
- deleteTermination - Delete an employee termination
- updateTermination - Update an employee termination
- createRehire - Create an employee rehire
- rehire - Update an employee rehire
- getRehire - Get an employee rehire
- deleteRehire - Delete an employee rehire
- getHistory - Get employment history for an employee
- generateW2 - Generate a W2 form [DEMO]
- list - Get all employee forms
- get - Get an employee form
- getPdf - Get the employee form pdf
- sign - Sign an employee form
- create - Create an employee bank account
- deleteBankAccount - Delete an employee bank account
- updateBankAccount - Update an employee bank account
- get - Get payment method for an employee
- update - Update payment method for an employee
- getBankAccounts - Get all employee bank accounts
- list - Get employees of a company
- create - Create an employee
- getV1CompaniesCompanyIdEmployeesPaymentDetails - Get employee payment details for a company
- createHistorical - Create a historical employee
- get - Get an employee
- update - Update an employee.
- delete - Delete an onboarding employee
- getCustomFields - Get an employee's custom fields
- updateOnboardingDocumentsConfig - Update employee onboarding documents config
- getOnboardingStatus - Get the employee's onboarding status
- updateOnboardingStatus - Update the employee's onboarding status
- getTimeOffActivities - Get employee time off activities
- getFederalTaxes - Get federal taxes for an employee
- updateFederalTaxes - Update federal taxes for an employee
- getStateTaxes - Get an employee's state taxes
- updateStateTaxes - Update an employee's state taxes
- get - Get all events
- create - Create a new external payroll for a company
- get - Get external payrolls for a company
- retrieve - Get an external payroll
- delete - Delete an external payroll
- update - Update an external payroll
- calculateTaxes - Get tax suggestions for an external payroll
- listTaxLiabilities - Get tax liabilities
- updateTaxLiabilities - Update tax liabilities
- finalizeTaxLiabilities - Finalize tax liabilities options and convert into processed payrolls
- create - Create a flow
- create - Create a garnishment
- list - Get garnishments for an employee
- get - Get a garnishment
- update - Update a garnishment
- getChildSupportData - Get child support garnishment data
- get - Get a generated document
- update - Update a historical employee
- get - Get a company's holiday pay policy
- create - Create a holiday pay policy for a company
- update - Update a company's holiday pay policy
- delete - Delete a company's holiday pay policy
- addEmployees - Add employees to a company's holiday pay policy
- removeEmployees - Remove employees from a company's holiday pay policy
- previewPaidHolidays - Preview a company's paid holidays
- getAuthorization - Get an employee's I-9 authorization
- update - Create or update an employee's I-9 authorization
- getDocumentOptions - Get an employee's I-9 verification document options
- getDocuments - Get an employee's I-9 verification documents
- createDocuments - Create an employee's I-9 authorization verification documents
- deleteDocument - Delete an employee's I-9 verification document
- employerSign - Employer sign an employee's Form I-9
- getInformationRequests - Get all information requests for a company
- submit - Submit information request responses
- getInfo - Get info about the current access token
- oauthAccessToken - Create a System Access Token or Refresh an Access Token
- get - Retrieve invoicing data for companies
- createJob - Create a job
- getJobs - Get jobs for an employee
- getJob - Get a job
- update - Update a job
- delete - Delete an individual job
- getCompensations - Get compensations for a job
- createCompensation - Create a compensation
- getCompensation - Get a compensation
- updateCompensation - Update a compensation
- deleteCompensation - Delete a compensation
- create - Create a company location
- get - Get all company locations
- retrieve - Get a location
- update - Update a location
- getMinimumWages - Get minimum wages for a location
- getDetails - Get a notification's details
- getCompanyNotifications - Get notifications for company
- list - Get all payrolls for a company
- createOffCycle - Create an off-cycle payroll
- getApprovedReversals - Get approved payroll reversals
- get - Get a single payroll
- update - Update a payroll by ID
- delete - Delete a payroll
- prepare - Prepare a payroll for update
- getReceipt - Get a single payroll receipt
- getBlockers - Get all payroll blockers for a company
- calculateGrossUp - Calculate gross up for a payroll
- calculate - Calculate a payroll
- submit - Submit payroll
- cancel - Cancel a payroll
- getPayStub - Get an employee pay stub (pdf)
- getPayStubs - Get an employee's pay stubs
- generatePrintableChecks - Generate printable payroll checks (pdf)
- getV1CompaniesCompanyIdPayrollsIdPartnerDisbursements - Get partner disbursements for a payroll
- patchV1CompaniesCompanyIdPayrollsIdPartnerDisbursements - Update partner disbursements for a payroll
- create - Create a new pay schedule
- getAll - Get the pay schedules for a company
- getPreview - Preview pay schedule dates
- get - Get a pay schedule
- update - Update a pay schedule
- getPayPeriods - Get pay periods for a company
- getUnprocessedTerminationPeriods - Get termination pay periods for a company
- getAssignments - Get pay schedule assignments for a company
- previewAssignment - Preview pay schedule assignments for a company
- assign - Assign pay schedules for a company
- postV1CompaniesCompanyIdPeopleBatches - Create a people batch
- getV1PeopleBatchesPeopleBatchUuid - Get a people batch
- getV1EmployeesEmployeeIdRecurringReimbursements - Get recurring reimbursements for an employee
- postV1EmployeesEmployeeIdRecurringReimbursements - Create a recurring reimbursement
- getV1RecurringReimbursements - Get a recurring reimbursement
- putV1RecurringReimbursements - Update a recurring reimbursement
- deleteV1RecurringReimbursements - Delete a recurring reimbursement
- createCustom - Create a custom report
- postPayrollsPayrollUuidReportsGeneralLedger - Create a general ledger report
- getReportsRequestUuid - Get a report
- getTemplate - Get a report template
- postV1CompaniesCompanyIdReportsEmployeesAnnualFicaWage - Create an employees annual FICA wage report
- postV1EmployeesEmployeeIdSalaryEstimates - Create a salary estimate for an employee
- getV1SalaryEstimatesId - Get a salary estimate
- putV1SalaryEstimatesId - Update a salary estimate
- postV1SalaryEstimatesUuidAccept - Accept a salary estimate
- getV1SalaryEstimatesOccupations - Search for BLS occupations
- create - Create a signatory
- list - Get the signatories for a company
- invite - Invite a signatory
- update - Update a signatory
- delete - Delete a signatory
- get - Get tax requirements for a state
- updateState - Update tax requirements for a state
- getAll - Get all tax requirements for a company
- calculateAccruingTimeOffHours - Calculate accruing time off hours
- get - Get a time off policy
- update - Update a time off policy
- getAll - Get all time off policies for a company
- create - Create a time off policy
- addEmployees - Add employees to a time off policy
- removeEmployees - Remove employees from a time off policy
- updateBalance - Update employee time off balances
- deactivate - Deactivate a time off policy
- createSubscription - Create a webhook subscription
- listSubscriptions - List webhook subscriptions
- updateSubscription - Update a webhook subscription
- getSubscription - Get a webhook subscription
- deleteSubscription - Delete a webhook subscription
- verify - Verify the webhook subscription
- requestVerificationToken - Request the webhook subscription verification_token
- getV1WebhooksHealthCheck - Get the webhooks health status
Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.
GustoEmbeddedException 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) |
package hello.world;
import com.gusto.embedded_api.GustoEmbedded;
import com.gusto.embedded_api.models.components.EntityErrorObject;
import com.gusto.embedded_api.models.components.VersionHeader;
import com.gusto.embedded_api.models.errors.GustoEmbeddedException;
import com.gusto.embedded_api.models.errors.UnprocessableEntityErrorObject;
import com.gusto.embedded_api.models.operations.*;
import java.io.UncheckedIOException;
import java.lang.Exception;
import java.util.List;
import java.util.Optional;
public class Application {
public static void main(String[] args) throws UnprocessableEntityErrorObject, Exception {
GustoEmbedded sdk = GustoEmbedded.builder()
.build();
try {
PostV1PartnerManagedCompaniesResponse res = sdk.companies().createPartnerManaged()
.security(PostV1PartnerManagedCompaniesSecurity.builder()
.systemAccessAuth(System.getenv().getOrDefault("SYSTEM_ACCESS_AUTH", ""))
.build())
.xGustoAPIVersion(VersionHeader.TWO_THOUSAND_AND_TWENTY_FIVE_MINUS06_MINUS15)
.requestBody(PostV1PartnerManagedCompaniesRequestBody.builder()
.user(User.builder()
.firstName("Frank")
.lastName("Ocean")
.email("[email protected]")
.phone("2345558899")
.build())
.company(Company.builder()
.name("Frank's Ocean, LLC")
.tradeName("Frank’s Ocean")
.ein("123456789")
.contractorOnly(false)
.build())
.build())
.call();
if (res.object().isPresent()) {
System.out.println(res.object().get());
}
} catch (GustoEmbeddedException ex) { // all SDK exceptions inherit from GustoEmbeddedException
// 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 UnprocessableEntityErrorObject) {
var e = (UnprocessableEntityErrorObject) ex;
// Check error data fields
e.data().ifPresent(payload -> {
List<EntityErrorObject> errors = payload.errors();
});
}
// 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)
} }
}Primary error:
GustoEmbeddedException: The base class for HTTP error responses.
Less common errors (11)
Network errors:
java.io.IOException(always wrapped byjava.io.UncheckedIOException). Commonly encountered subclasses ofIOExceptionincludejava.net.ConnectException,java.net.SocketTimeoutException,EOFException(there are many more subclasses in the JDK platform).
Inherit from GustoEmbeddedException:
com.gusto.embedded_api.models.errors.NotFoundErrorObject: Not Found The requested resource does not exist. Make sure the provided ID/UUID is valid. Applicable to 162 of 280 methods.*com.gusto.embedded_api.models.errors.UnprocessableEntityErrorObject: Unprocessable Entity This may happen when the body of your request contains errors such asinvalid_attribute_value, or the request fails due to aninvalid_operation. See the Errors Categories guide for more details. Applicable to 143 of 280 methods.*com.gusto.embedded_api.models.errors.PeopleBatchConflictError: Error response when a people batch idempotency key conflict occurs. Status code409. Applicable to 1 of 280 methods.*com.gusto.embedded_api.models.errors.GetCompaniesCompanyUuidContractorPaymentsPreviewResponseBody: Unprocessable Entity (WebDAV). Status code422. Applicable to 1 of 280 methods.*com.gusto.embedded_api.models.errors.CompanySuspensionCreationErrors: Unprocessable Entity This may happen when the body of your request contains errors such asinvalid_attribute_value, or the request fails due to aninvalid_operation. See the Errors Categories guide for more details. Status code422. Applicable to 1 of 280 methods.*
* Check the method documentation to see if the error is applicable.
You can override the default server globally using the .server(AvailableServers server) builder method when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:
| Name | Server | Description |
|---|---|---|
demo |
https://api.gusto-demo.com |
Demo |
prod |
https://api.gusto.com |
Prod |
package hello.world;
import com.gusto.embedded_api.GustoEmbedded;
import com.gusto.embedded_api.models.operations.GetV1TokenInfoResponse;
import com.gusto.embedded_api.models.operations.XGustoAPIVersion;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws Exception {
GustoEmbedded sdk = GustoEmbedded.builder()
.server(GustoEmbedded.AvailableServers.DEMO)
.companyAccessAuth(System.getenv().getOrDefault("COMPANY_ACCESS_AUTH", ""))
.build();
GetV1TokenInfoResponse res = sdk.introspection().getInfo()
.xGustoAPIVersion(XGustoAPIVersion.TWO_THOUSAND_AND_TWENTY_FIVE_MINUS06_MINUS15)
.call();
if (res.tokenInfo().isPresent()) {
System.out.println(res.tokenInfo().get());
}
}
}The default server can also be overridden globally using the .serverURL(String serverUrl) builder method when initializing the SDK client instance. For example:
package hello.world;
import com.gusto.embedded_api.GustoEmbedded;
import com.gusto.embedded_api.models.operations.GetV1TokenInfoResponse;
import com.gusto.embedded_api.models.operations.XGustoAPIVersion;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws Exception {
GustoEmbedded sdk = GustoEmbedded.builder()
.serverURL("https://api.gusto-demo.com")
.companyAccessAuth(System.getenv().getOrDefault("COMPANY_ACCESS_AUTH", ""))
.build();
GetV1TokenInfoResponse res = sdk.introspection().getInfo()
.xGustoAPIVersion(XGustoAPIVersion.TWO_THOUSAND_AND_TWENTY_FIVE_MINUS06_MINUS15)
.call();
if (res.tokenInfo().isPresent()) {
System.out.println(res.tokenInfo().get());
}
}
}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 and asynchronous (sendAsync) methods. The sendAsync method
is used to power the async SDK methods and returns a CompletableFuture<HttpResponse<Blob>> for non-blocking operations.
The following example shows how to add a custom header and handle errors:
import com.gusto.embedded_api.GustoEmbedded;
import com.gusto.embedded_api.utils.HTTPClient;
import com.gusto.embedded_api.utils.SpeakeasyHTTPClient;
import com.gusto.embedded_api.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;
}
}
};
GustoEmbedded sdk = GustoEmbedded.builder()
.client(httpClient)
.build();
}
}Custom HTTP Client Configuration
You can also provide a completely custom HTTP client with your own configuration:
import com.gusto.embedded_api.GustoEmbedded;
import com.gusto.embedded_api.utils.HTTPClient;
import com.gusto.embedded_api.utils.Blob;
import com.gusto.embedded_api.utils.ResponseWithBody;
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;
import java.util.concurrent.CompletableFuture;
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());
}
@Override
public CompletableFuture<HttpResponse<Blob>> sendAsync(HttpRequest request) {
// Convert response to HttpResponse<Blob> for async operations
return client.sendAsync(request, HttpResponse.BodyHandlers.ofPublisher())
.thenApply(resp -> new ResponseWithBody<>(resp, Blob::from));
}
};
GustoEmbedded sdk = GustoEmbedded.builder()
.client(customHttpClient)
.build();
}
}You can also enable debug logging on the default SpeakeasyHTTPClient:
import com.gusto.embedded_api.GustoEmbedded;
import com.gusto.embedded_api.utils.SpeakeasyHTTPClient;
public class Application {
public static void main(String[] args) {
SpeakeasyHTTPClient httpClient = new SpeakeasyHTTPClient();
httpClient.enableDebugLogging(true);
GustoEmbedded sdk = GustoEmbedded.builder()
.client(httpClient)
.build();
}
}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.
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.gusto.embedded_api.utils.JSON;
String json = JSON.getMapper().writeValueAsString(response);To compose with your own ObjectMapper, register the provided GustoEmbeddedJacksonModule, which
bundles all the same modules and feature flags as a single plug-and-play module:
import com.gusto.embedded_api.utils.GustoEmbeddedJacksonModule;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper myMapper = new ObjectMapper()
.registerModule(new GustoEmbeddedJacksonModule());
String json = myMapper.writeValueAsString(response);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.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.