Use Java SDKs generated in Postman
This guide provides instructions for using Java SDKs generated by Postman SDK Generator. It covers how to import the SDK into your project, run example code, and best practices for using the SDK effectively in your applications.
SDK structure
The Java SDK includes the following key files:
[SdkName].java— Main SDK client, instantiated with[SdkName]Configservices/— Service classes with both sync and async methodsmodels/— Data models (POJOs with Lombok builders, enums, typed exceptions) with Jackson serializationconfig/— Configuration classes for auth, retry, and SDK client settingspom.xml— Specifies dependencies (OkHttp, Jackson, Lombok)
The following is an example of the typical structure of a generated Java SDK:
Example usage
Each generated SDK includes an examples/ directory with a working project demonstrating SDK usage.
The example includes the following features:
- SDK initialization with config builder pattern
- Synchronous API calls
- Working with model builders
- Exception handling
Location
Run the example
Example code structure
examples/src/main/java/Main.java
Import the Java SDK locally
You can import the generated SDK using Maven, project file path, or Gradle. Below are instructions for each method.
Import using a Maven local repository
To import the generated SDK using a local Maven repository, do the following:
-
Install SDK to local Maven repository.
-
Add dependency to your project’s
pom.xml. -
Use the SDK in your code.
Import using the project file path
To import the generated SDK using the project file path, do the following:
-
Add SDK as a module in your project’s
pom.xml. -
Reference as dependency.
Import using Gradle
To import the generated SDK using Gradle, first install it to your local Maven repository:
Then, add the dependency to your build.gradle file:
Alternatively, if you want to reference the SDK as a JAR file, first build the fat JAR:
Then, add the JAR to your build.gradle:
Publish to Maven Central
To share your generated Java SDK with the community, you can publish it to Maven Central. This allows other developers to easily add it as a dependency in their Maven or Gradle projects. Follow the steps below to publish your SDK to Maven Central.
Prerequisites
To publish your SDK to Maven Central, you need the following:
- Sonatype Central Portal account (central.sonatype.com)
- GPG key for signing artifacts
- Namespace (group ID) verified on the Central Portal
Initial setup
To set up your environment for publishing to Maven Central, do the following:
-
Create account and verify your namespace:
- Register at central.sonatype.com.
- Verify your namespace (group ID, for example,
com.example) through DNS or GitHub verification. - Verification is typically automated and completes within minutes.
-
Generate a GPG key.
-
Configure Maven
settings.xml. Add the following to~/.m2/settings.xml:
Configure pom.xml
Add the following to your SDK’s pom.xml:
Publish your Java SDK to Maven Central
-
Deploy to Maven Central.
With
autoPublishset totrue, artifacts are automatically published after validation. If set tofalse, you can manually publish from the Central Portal UI at central.sonatype.com. -
Verify the publication. After deployment, verify that your artifacts are available in the staging repository on the Central Portal, for example,
https://repo1.maven.org/maven2/com/example/your-sdk/. Once verified, they’re released to Maven Central within 30 minutes.
Publish updates
To publish updates to your SDK, do the following:
Best practices for publishing Java SDKs
Use the following best practices when publishing your Java SDK to Maven Central:
- Use semantic versioning.
- Sign all artifacts with GPG.
- Include source and javadoc JARs.
- Provide comprehensive documentation.
- Tag releases in Git.
- Consider using the Maven Release Plugin for automated releases.
Advanced usage
You can further customize the SDK by modifying the generated code, adding new features, or integrating it with your existing codebase. Here are some advanced topics to explore.
Authentication
The SDK supports various authentication methods. You can configure authentication when initializing the SDK client.
The SDK includes authentication support based on the security schemes defined in your API specification. The following examples show the possible authentication methods.
API Key
Bearer Token
Basic Auth
OAuth 2.0
To update the credentials after initialization, run one of the following. The setApiKey, setAccessToken, and setBasicAuthCredentials methods are each only generated when the corresponding auth type is in the specification.
Synchronous and asynchronous calls
Every service method has a sync variant (methodName) and an async variant (methodNameAsync). Sync methods return the type directly (for example, Pet), while
async methods return CompletableFuture<T> (for example, CompletableFuture<Pet>).
For void methods, async returns CompletableFuture<Void>.
Environment management
The SDK supports multiple environments (for example, production, staging) with different base URLs.
Hierarchical configuration
Java supports all four levels of configuration: SDK (through SdkConfig or sdk.setEnvironment()/sdk.setBaseUrl()), and service, method, and request levels (through RequestConfig). Each level overrides the previous, with request being most specific.
Error handling
The SDK raises custom exceptions for API errors, which include details about the error message, status code, and response body. You can catch these exceptions to handle errors gracefully in your application.
To handle errors, do the following:
To handle specific error codes, do the following:
When the API specification defines error response models, the SDK generates typed exception classes (for example, NotFoundErrorException) that extend ApiError and include the deserialized error model. The exception’s getMessage() and getStatus() work directly, but to access specification-defined error fields, use getError().
Timeouts and retries
To set a global timeout, do the following:
To pass the retry configuration through SdkConfig, do the following:
Validation
The SDK generates validators that enforce OpenAPI constraints at runtime. These include minLength, maxLength, pattern, min, max, uniqueItems, and more.
Validation happens automatically when making API calls. The SDK validates parameters before sending the request. If validation fails, a ValidationException is thrown with a list of Violation objects describing what went wrong. You don’t need to call validators manually. They’re built into the service methods.
The list of supported constraints can also be grouped by type like this:
- String —
minLength,maxLength,pattern(regex) - Numeric —
min,max(inclusive or exclusive) - List/array —
minItems,maxItems,uniqueItems - Required fields — validated automatically based on the specification
Optional and nullable field handling
The SDK uses JsonNullable<T> wrappers for optional fields, providing clear distinction between undefined, null, and present values. This is important for users building request models. Omitting an optional field versus explicitly setting it to null produces different JSON payloads.
Additional resources
Consider the following resources for using and customizing your Java SDK:
- SDK documentation — Check the
documentation/directory in your SDK. - Javadoc — Generate with
mvn javadoc:javadoc. - Example usage — Refer to the
examples/directory for a working code sample demonstrating basic SDK usage. - Dependencies — The SDK uses the following dependencies:
- OkHttp: HTTP client
- Jackson: JSON serialization and
jackson-databind-nullable, a dependency used for optional nullable field handling - Lombok: Reduce boilerplate code