liblab Java v2 SDK generator overview
The liblab Java SDK generator simplifies API integration by providing a structured, reliable, and user-friendly SDK generation process. The release of version 2 introduces several improvements that enhance the developer experience, ensuring faster integrations and reducing potential errors. This article will walk you through the key features of the liblab Java V2 SDK, explore what's new in this version, and guide you through the setup process.
Key Features of liblab's Java V2 SDK
-
Automatic SDK Generation: The SDK is automatically generated based on your API's OpenAPI specification. This saves development time and reduces manual errors in SDK implementation.
-
Improved Code Readability: The generated code is easier to read and interpret, improving developer productivity.
-
Synchronous and Asynchronous Methods: The SDK generates both synchronous and asynchronous versions for each method. The asynchronous methods return a
CompletableFuture
, offering non-blocking functionality similar to JavaScript promises. -
Cleaner Models: The SDK's models are now cleaner and easier to understand, thanks to the use of annotations such as
@Data
,@Builder
, and@ToString
. Although users are not encouraged to modify models directly, their clarity aids in understanding the code. -
Enhanced OpenAPI Support: Java V2 SDK supports complex models from OpenAPI specifications, such as
oneof
. This includes a dedicated directory structure and documentation that explains how to use and manage these complex models. -
Integrated Validation: All parameters are validated against the OpenAPI specification before sending a request to the API, ensuring that issues are caught early.
-
Pagination Support: The SDK provides pagination support with an iterator, enabling developers to loop through large datasets using
forEach
or similar methods. The SDK automatically manages request offsets. -
Flexible Serialization: The SDK supports all serialization methods defined in the OpenAPI documentation, giving developers greater flexibility in handling API requests.
-
Comprehensive Documentation: The SDK has extensive, built-in documentation that lets developers quickly grasp how to work with the API. The previous version grouped all documentation, including classes, methods, and examples, into a single README file. With Version 2, the documentation is now structured more logically, separating details for models and services. This improved organization and targeted code examples allow developers to easily navigate the SDK and integrate the API more efficiently.
What's New in Version 2?
Improved validation
The validation feature has been enhanced to ensure that all parameters comply with the OpenAPI specification before a request is made. For example, if the API defines a maximum value for a parameter, the SDK will enforce this limit during validation, reducing the likelihood of runtime errors. In addition, in case of any error, the SDK response will list all problems at once, ensuring you can fix everything instead of raising an error when the first error is found.
Asynchronous method support
Java V2 SDK generates asynchronous methods alongside synchronous ones, returning a CompletableFuture
. This enables non-blocking operations, allowing developers to handle multiple API calls concurrently, improving performance, scalability, and responsiveness, especially in high-demand or resource-intensive applications. The following code blocks present an example of the PetsService
class, which provides synchronous and asynchronous list methods.
/**
* PetsService Service
*/
public class PetsService extends BaseService {
public PetsService(@NonNull OkHttpClient httpClient, String serverUrl) {
super(httpClient, serverUrl);
}
/**
* Synchronous: List all pets with request parameters
*
* @param requestParameters {@link ListPetsParameters} Request Parameters Object
* @return response of {@code List<Pet>}
*/
public List<Pet> listPets(@NonNull ListPetsParameters requestParameters) throws ApiException {
Request request = this.buildListPetsRequest(requestParameters);
Response response = this.execute(request);
return ModelConverter.convert(response, new TypeReference<List<Pet>>() {});
}
/**
* Asynchronous: List all pets with request parameters
*
* @param requestParameters {@link ListPetsParameters} Request Parameters Object
* @return response of {@code List<Pet>}
*/
public CompletableFuture<List<Pet>> listPetsAsync(@NonNull ListPetsParameters requestParameters) throws ApiException {
Request request = this.buildListPetsRequest(requestParameters);
CompletableFuture<Response> response = this.executeAsync(request);
return response.thenApplyAsync(res -> {
return ModelConverter.convert(res, new TypeReference<List<Pet>>() {});
});
}
private Request buildListPetsRequest(@NonNull ListPetsParameters requestParameters) {
return new RequestBuilder(HttpMethod.GET, this.serverUrl, "pets")
.setOptionalQueryParameter("limit", requestParameters.getLimit())
.build();
}
}
Cleaner documentation structure
The updated Java V2 SDK introduces a system that automatically generates comprehensive documentation for all SDK functionalities and endpoints. This enhancement helps new users adopt the SDK more quickly and provides ongoing support for developers, ensuring proper usage of the available features. In version 1, all documentation was consolidated in a single README file. In version 2, the documentation is organized into separate folders for models and services, making it easier for developers to locate and access the relevant content. The image below shows an example of this new documentation structure.
java/
├── documentation/
│ ├── models/
│ │ ├── Address.md
│ │ ├── Car.md
│ │ ├── CarExtended.md
│ │ ├── CarOrAddress.md
│ │ ├── ModelWithOneOf.md
│ │ ├── ModelWithOneOfArray.md
│ │ ├── OneOfAnyTypes.md
│ │ ├── OneOfArrays.md
│ │ ├── OneOfDistinctModels.md
│ │ ├── OneOfExtendedModels.md
│ │ ├── OneOfModelAndPrimitive.md
│ │ ├── OneOfNestedOneOf.md
│ │ ├── OneOfNestedOneOf1.md
│ │ ├── OneOfNestedOneOf2.md
│ │ └── OneOfPrimitives.md
│ └── services/
│ └── OneOfService.md
├── example/
├── install.sh
├── LICENSE
├── pom.xml
└── README.md
Support for complex models
Java V2 SDK now supports complex OpenAPI models:
oneOf
: Ensures the value matches exactly one of the subschemas. This means the value must validate against only one of the defined schemas.allOf
: Ensures the value meets the criteria of all the subschemas. In this case, the value must be validated against every schema you define.anyOf
: Ensures that the value matches at least one of the subschemas. The value can be validated against one or more of the schemas.
The generated SDK provides specialized classes to handle these models. The generated documentation explains how to instantiate and handle complex models in API responses. In addition, example code snippets are included to make the implementation easier.
public class Main {
public static void main(String[] args) {
TestSdkConfig config = TestSdkConfig.builder().accessToken("YOUR_ACCESS_TOKEN").build();
TestSdk testSdk = new TestSdk(config);
Address address = Address.builder()
.street("street")
.city("city")
.number("number")
.state(State.CA)
.build();
Person person = Person
.builder()
.firstName("firstName")
.lastName("lastName")
.acceptedTerms(true)
.age(8L)
.address(address)
.build();
OneOfDistinctModels oneOfDistinctModels = OneOfDistinctModels.ofPerson(person);
OneOfDistinctModels response = testSdk.oneOfService.postDistictModels(oneOfDistinctModels);
System.out.println(response);
}
}
Streamlined code snippets
Code snippets have been restructured to improve readability and ease of use. Developers can now quickly copy and paste code examples to test the SDK.
- Version 1 (Old)
- Version 2 (New)
public class Main {
public static void main(String[] args) {
Testsdk client = new Testsdk(System.getenv("TESTSDK_BEARER_TOKEN"));
try {
Object response = client.petsService.listPets(3);
System.out.println(response);
} catch (ApiException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
TestSdkConfig config = TestSdkConfig.builder().accessToken("YOUR_ACCESS_TOKEN").build();
TestSdk testSdk = new TestSdk(config);
ListPetsParameters requestParameters = ListPetsParameters.builder().limit(81L).build();
List<Pet> response = testSdk.petsService.listPets(requestParameters);
System.out.println(response);
}
}
Setting Up liblab for Java V2 SDK
Before you begin, ensure you have the following:
- liblab CLI installed.
- An OpenAPI specification in JSON or YAML format.
- Java Development Kit (JDK) version 8 or higher.
1. Create the SDK
To create the SDK, follow these steps:
- Log into liblab. The following command opens a browser to authenticate your liblab account.
liblab login
- Initialize liblab with your API specification. Ensure your OpenAPI specification file is in JSON or YAML format.
liblab init --spec <OPEN_API_ADDRESS>
- Generate the SDK. Set the language to
["Java"]
during the setup process.
liblab build
The SDK will be generated according to your OpenAPI spec, and the folder structure will include separate directories for services and models.
2. Publish the SDK
After generating the SDK, you can publish it for public or internal use. You can integrate this step with GitHub Actions for continuous integration and automated updates. Refer to the liblab GitHub Actions documentation for more details.
3. Use the SDK
Once published, developers can import the SDK into their Java project using their package manager, such as Maven or Gradle. To use the SDK, instantiate the services as shown in the example below:
import com.swagger.petstore.TestSdk;
import com.swagger.petstore.config.TestSdkConfig;
public class Main {
public static void main(String[] args) {
TestSdkConfig config = TestSdkConfig.builder().accessToken("YOUR_ACCESS_TOKEN").build();
TestSdk testSdk = new TestSdk(config);
}
}
The SDK's auto-generated documentation will provide comprehensive usage instructions for each method and service.
Benefits of Java V2 SDK for End Users
The Java V2 SDK offers several key benefits for developers and end-users:
- Faster integrations: The automatic generation process and asynchronous methods accelerate your customers' integration processes.
- Reduced errors: Integrated validation ensures that incorrect API requests are caught early, reducing errors and the need for multiple calls to identify issues.
- Improved performance: Asynchronous methods allow for non-blocking API calls, improving performance in applications where multiple calls are made concurrently.
- Simplified development: Cleaner models, streamlined code snippets, and comprehensive documentation make it easier for developers to use and maintain the SDK.
- Better scalability: With pagination support and flexible serialization, the SDK can handle large datasets and complex API interactions more efficiently.
Conclusion
liblab's Java V2 SDK generator introduces several enhancements that make API integration faster, safer, and more efficient. With features like asynchronous methods, improved validation, and support for complex models, developers can focus on building great applications while reducing the time spent on SDK management. Start using the Java V2 SDK today and use these powerful tools to streamline your API integration.