How to generate the client API for an OpenAPI REST service

Last modified: October 4, 2022 by   in REST

In this article, we are going to see how to generate a client based on the OpenAPI specification using OpenAPI Generator.


Why do you need to generate a client?

If you want to call a REST service, you typically use Postman as a client. This is working fine if you just want to call the REST service manually or for testing purposes.

But if you want to call a REST service from your software application, you would need a client API.

OpenAPI Generator or Swagger Codegen

There are two solutions used in general to generate a client for a REST service: OpenAPI Generator and Swagger Codegen.

Based on our own tests we have seen that OpenAPI Generator better generates the client API and this is what we are going to use in this article.

Generate the client manually

In this section, we will generate a Java a client for our PEPPOL REST API which can be used to send and receive invoices in in the PEPPOL network. PEPPOL REST API is documented using OpenAPI 3 specification.

The first step is to download the OpenAPI Generator and save it in a directory on your local machine. Then switch into that directory and execute the following command:

java -jar openapi-generator-cli-6.1.0.jar generate -i https://ademico-software.com/peppol-rest-api/openapi.json -g java

OpenAPI Generator will generate a Maven project with a following structure:

|- api
|- docs
|- gradle
|- src
|- README.md
|- build.gradle
|- build.sbt
|- git_push.sh
|- gradle.properties
|- gradlew
|- gradlew.bat
|- pom.xml
|- settings.gradle

Note: In the command above we have generated a Java client. If you want to generate a client for other languages just replace java with your preferred language eg csharp or php. For a complete list of languages supported by OpenAPI Generator you can have a look on their GitHub repository.

In the directory src/org/openapitools/client/api you can find the client generated APIs eg InvoiceCreditNoteApi.java that you can use to call the server side REST service. In the directory docs you can find the API documentation with code examples like the one below eg InvoiceCreditNoteApi.md.

// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.auth.*;
import org.openapitools.client.models.*;
import org.openapitools.client.api.InvoiceCreditNoteApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://test-as4.ademico-software.com");

// Configure HTTP basic authorization: PeppolBasicAuth
HttpBasicAuth PeppolBasicAuth = (HttpBasicAuth) defaultClient.getAuthentication("PeppolBasicAuth");
PeppolBasicAuth.setUsername("YOUR USERNAME");
PeppolBasicAuth.setPassword("YOUR PASSWORD");

InvoiceCreditNoteApi apiInstance = new InvoiceCreditNoteApi(defaultClient);
String transmissionId = "transmissionId_example"; // String | 
try {
	String result = apiInstance.getInvoiceInUBLFormat(transmissionId);
	System.out.println(result);
} catch (ApiException e) {
	// you must replace System.err.println and e.printStackTrace() with a logger from your logging library  
	System.err.println("Exception when calling InvoiceCreditNoteApi#getInvoiceInUBLFormat");
	System.err.println("Status code: " + e.getCode());
	System.err.println("Reason: " + e.getResponseBody());
	System.err.println("Response headers: " + e.getResponseHeaders());
	e.printStackTrace();
}

Note: The generated code is not perfect and it must be adapted a bit, especially the error handling part. You need to use a logging framework instead of System.err.println and properly handle the exception.

Generate the client using Maven

We have seen above how to manually generate a Java client for a REST service documented with OpenAPI 3.

Normally you want to automatically generate the client using Maven and include it in . This way when the OpenAPI changes on the server side you are always up to date on the client side.

To generate the client API using maven we will use the openapi-generator-maven-plugin. Below you can find an example how to generate the client for our PEPPOL REST API.

<plugin>
	<groupid>org.openapitools</groupid>
	<artifactid>openapi-generator-maven-plugin</artifactid>
	<version>6.1.0</version>
	<executions>
		<execution>
			<goals>
				<goal>generate</goal>
			</goals>
			<configuration>
				<inputspec>https://ademico-software.com/peppol-rest-api/openapi.json</inputspec>
				<generatorname>java</generatorname>
				<configoptions>
					<library>resttemplate</library>
					<sourcefolder>src/gen/java/main</sourcefolder>
					<java8>true</java8>
					<datelibrary>java8</datelibrary>
					<apipackage>com.ademicosoftware.peppol.client.handler</apipackage>
					<modelpackage>com.ademicosoftware.peppol.client.model</modelpackage>
					<invokerpackage>com.ademicosoftware.peppol.client.handler</invokerpackage>
				</configoptions>
			</configuration>
		</execution>
	</executions>
</plugin>

As you can see above, the openapi-generator-maven-plugin can support many configuration parameters like the library used for the REST client or the packages in which the source file are generated. For a list of all possible configuration parameters you can execute the following command:

java -jar openapi-generator-cli-6.1.0.jar config-help -g java

Conclusion

Generating a client for an REST service documented using OpenAPI is easy using a tool like OpenAPI Generator. The generated code must be a bit polished before using it in production, especially the error handling part, but it is a good starting point to integrate your software application with a REST service.

Send and receive Invoices in the PEPPOL network using our PEPPOL REST API

About the author 

Cosmin Baciu

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}