apigenie-generator client java

Tier 1 · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · Verification

Generate a Java client of an OpenAPI document: a Maven project using Spring’s RestClient (the default) or RestTemplate, Spring Cloud OpenFeign interfaces, or Spring HTTP interfaces.

From an AsyncAPI document, the command generates a Java Kafka client library instead; see apigenie-generator client java (AsyncAPI).

Usage

apigenie-generator client java [...OPTIONS] INPUT_FILE

Description

The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see Swagger 2.0 input). The generated project needs Java 17 and Maven; its dependencies come from Maven Central.

ApiClient client = new ApiClient();
client.setBearerToken("token");
PetsApi pets = new PetsApi(client);

List<Pet> page = pets.listPets(10, null);
ResponseEntity<Pet> response = pets.getPetWithHttpInfo(42L);
try (Stream<PetEvent> events = pets.watchPetsStream()) {
    events.limit(5).forEach(System.out::println);
}

--library selects how the client calls the API:

Library Output
restclient (default) ApiClient on Spring’s RestClient, one class per API
resttemplate the same classes, with ApiClient on Spring’s RestTemplate
feign Spring Cloud OpenFeign: @FeignClient interfaces extending Spring MVC interfaces, request interceptors of the security schemes
http-interface Spring HTTP interfaces (@HttpExchange) and a configurator creating their proxies with a RestClient (or a WebClient with reactive)

The feign and http-interface libraries are the clients the spring-cloud and spring-http-interface libraries of apigenie-generator server spring generate, with the options of the client.

The rest of this section describes the restclient and resttemplate libraries. Their API classes are grouped by the first tag of operations (<Tag>Api); each operation has:

  • op(...), returning the body of the response (void without content);
  • opWithHttpInfo(...), returning the ResponseEntity, with the status and the headers;
  • opStream(...) when the response can be streamed as text/event-stream, application/jsonl, application/x-ndjson or application/json-seq: a Stream of the items, typed by the itemSchema of the media type (x-itemSchema before 3.2) or the contentSchema of the data of events, read as they arrive. Closing the stream (try-with-resources) closes the connection.
  • opWith<MediaType>(...) for each further request media type taking another Java type, e.g. updateShipmentWithJsonPatch(...) for application/json-patch+json.

Required parameters come first. Parameters are serialized with their style (form, spaceDelimited, pipeDelimited, deepObject, simple); parameters described with content are sent as JSON. Bodies are JSON, JSON Lines (a List of items), form fields, multipart parts (Spring Resources for files, JSON parts for objects, the content type of the encoding), text or binary (Resource). Binary responses are Resources. Methods other than the eight classic ones (QUERY, additionalOperations) are sent as they are; the JDK HttpClient the client uses allows them.

ApiClient holds:

  • the servers of the document (setServerIndex, setServerVariables) or a base path (setBasePath); operations with servers of their own are sent to them, unless setOperationBasePath(operationId, url) says otherwise;
  • one Authentication per security scheme, added to the operations requiring it: setBearerToken (HTTP bearer and OpenID Connect schemes, and OAuth 2 schemes whose tokens are obtained elsewhere), setOAuthClientCredentials (OAuth 2, since 0.12.0), setApiKey (headers, query parameters and cookies), setUsername and setPassword (HTTP basic);
  • the ObjectMapper (createObjectMapper(): Java time, JsonNullable, absent properties left out, unknown properties ignored), default headers and cookies.

Since 0.12.0, an OAuth 2 scheme gets an OAuth authentication (with the RestClient and RestTemplate libraries). It holds the endpoints and scopes of the client credentials, authorization code and device authorization flows of the scheme, and each flow uses its own token URL:

OAuth oauth = (OAuth) client.getAuthentication("oauth2"); // the name of the security scheme
oauth.setClientCredentials("client-id", "secret"); // a null secret for a public client
oauth.setScopes(List.of("shipments:read"));         // none by default: the server's default

String url = oauth.authorizationUrl("https://app.example.com/callback", state);
oauth.exchangeAuthorizationCode(code, "https://app.example.com/callback");

OAuth.DeviceAuthorization device = oauth.requestDeviceAuthorization();
oauth.pollDeviceToken(device); // waits until the user enters device.userCode()
  • With a client credentials flow and client credentials, the client requests a token before the first request, and again once it expires.
  • A token that comes with a refresh token is renewed with it at the refresh URL of its flow (its token URL without one).
  • authorizationUrl and requestDeviceAuthorization send the client id, so call setClientCredentials first. authorizationUrl adds a PKCE challenge, whose verifier exchangeAuthorizationCode sends. A second authorizationUrl replaces the verifier of the first, so one authorization runs at a time.
  • The methods of the authorization code and device authorization flows throw an IllegalStateException when the scheme has no such flow.
  • Token requests use a JDK HttpClient of their own, which setHttpClient replaces: a client certificate of withClientCertificate isn’t sent to the token endpoint.
  • A token set with setBearerToken takes precedence, and setRefreshToken sets a refresh token obtained elsewhere.

A token request that fails raises an OAuth.OAuthException, from the API call or from the method that sent it. Its getError() tells what happened:

getError() When The refresh token
invalid_grant the server refused the grant dropped
another error code of the answer the server refused the request kept
http_<status> an error status without an error code kept
request_failed the server could not be reached, or its answer isn’t JSON kept
interrupted the thread was interrupted kept

When a refresh fails and the scheme has a client credentials flow with client credentials set, the client requests a new token with them instead of raising the exception.

Since 0.12.0, with a mutualTLS scheme (OpenAPI 3.1 and 3.2), ApiClient.withClientCertificate creates a client that presents the certificate of a key store. It checks the certificate of the server against a trust store, or against the CAs of the JDK when the trust store is null. loadKeyStore reads a PKCS #12 or JKS file, and sslContext gives the SSLContext for a request factory of your own.

Responses with an error status raise an ApiException with the status, the headers and the body; application/problem+json responses raise a ProblemDetailsException with the RFC 9457 problem details, typed as the problem schema of the document.

Models are the Jackson classes of apigenie-generator server spring, without Swagger annotations:

  • classes for objects, with the properties of allOf members (the properties of anyOf and oneOf alternatives are optional)
  • interfaces for oneOf: with a discriminator, @JsonTypeInfo and @JsonSubTypes, its defaultMapping (x-defaultMapping before 3.2) as defaultImpl and the const values of the members as the names of implicit mappings; without one, the members are told apart by a property with constant values (useImplicitOneOfDiscriminator) or by their properties (useDeductionForOneOfInterfaces)
  • enums, JsonNullable for nullable properties, Bean Validation annotations, java.time types
  • readOnly properties only read from responses and writeOnly ones only sent (jsonAccessForReadWriteOnly)
  • since 0.12.0, tuples (prefixItems without an items schema): a list of the type their items share (Object when they differ), with @Size(max = …) when items: false closes them
  • since 0.12.0, patternProperties (when additionalProperties is absent or false). An object without properties or additionalProperties whose keys match one pattern is a Map. Other objects hold the entries like additional properties (getAdditionalProperties()), and read each value as the type of the pattern its key matches. Keys that match no pattern are kept there too. With additionalProperties: false, putAdditionalProperty throws an IllegalArgumentException for them instead, so the object fails to deserialize.
  • since 0.12.0, with useBeanValidation (the default, except with the http-interface library): multipleOf, checked by MultipleOf, a constraint generated in the configuration package. Numbers with a multipleOf are annotated with it.
  • since 0.12.0, with useBeanValidation: conditions of a schema (if/then/else, dependentRequired, dependentSchemas) as @AssertTrue methods, such as isConditionSatisfied(), is<Property>DependentRequiredSatisfied() and is<Property>DependentSchemaSatisfied(). They test which properties are present and the const or enum values of string, enum and boolean properties; other conditions are left out.

Unknown properties of other models are ignored, unevaluatedProperties: false included.

x-internal operations and paths are left out.

The project contains pom.xml (Spring Framework, Jackson and Jakarta versions from the Spring Boot BOM, without Spring Boot), README.md, .openapi-generator-ignore (written only when it doesn’t exist) and, in the base package, ApiClient, ApiException, ProblemDetailsException (with a problem schema), ServerConfiguration, ServerVariable, StreamDecoder (with streaming responses), RFC3339DateFormat, auth/ (Authentication, HttpBearerAuth, HttpBasicAuth, ApiKeyAuth, and OAuth with an OAuth 2 scheme), configuration/ (MultipleOf, with a multipleOf and useBeanValidation), api/ and model/.

Not supported: callbacks and webhooks, and the password and implicit flows of OAuth 2 (set their tokens with setBearerToken). With the feign and http-interface libraries, OAuth 2 flows and mutual TLS are not supported: set tokens by hand, and the SSLContext on the HTTP client. The feign library leaves out operations of methods other than the classic ones.

Extensions

Extension Effect
x-class-extra-annotation annotations of the class of a schema, e.g. ['@Entity']
x-implements interfaces the class of a schema implements
x-field-extra-annotation annotations of the field of a property, or of the method parameter of a parameter (feign, http-interface)
x-extra-annotation annotations of the getter of a property
x-setter-extra-annotation annotations of the setter of a property
x-pattern-message, x-size-message, x-minimum-message, x-maximum-message message of the @Pattern, @Size, @Min/@DecimalMin and @Max/@DecimalMax annotations of a property or a parameter, on its schema, and since 0.12.0 on the parameter itself, as in Swagger 2.0 documents
x-jackson-json-include-policy @JsonInclude policy of a property, e.g. non_empty (none for no annotation)
x-jackson-json-setter-nulls @JsonSetter(nulls = ...) of a property, e.g. skip (none for no annotation)
x-enum-varnames names of the constants of an enum
x-enum-descriptions Javadoc of the constants of an enum
x-parent true makes a schema the superclass of the schemas extending it with allOf, without a discriminator
x-discriminator-value the discriminator value of a subclass in @JsonSubTypes (default: the name of its schema)
x-jackson-default-impl defaultImpl of the @JsonTypeInfo of a class with a discriminator
x-defaultMapping defaultMapping of a discriminator in OpenAPI 3.0 and 3.1 documents: the defaultImpl of @JsonTypeInfo, without x-jackson-default-impl
x-itemSchema itemSchema of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a streamed response
x-codegen-request-body-name on an operation or its request body: the name of the body parameter
x-apigenie.codegen.controller-name on an operation: the API class of the operation, instead of its tag or path
x-apigenie.codegen.action-name name of the method of an operation, instead of its operationId
x-apigenie.codegen.disabled true on an operation or its path item leaves the operation out, with skipDisabled
x-internal true on an operation or its path item leaves the operation out
x-operation-extra-annotation annotations of the method of an operation (feign)
x-version-param true on a header or query parameter adds it to the headers or params of the @RequestMapping (feign)

The extensions can live in an overlay for this target instead of in the document, e.g. java.overlay.yaml:

overlay: 1.0.0
info:
  title: Java annotations
  version: 1.0.0
actions:
  - target: $.components.schemas.Pet
    update:
      x-class-extra-annotation: ['@com.acme.Audited']
      x-implements: [java.io.Serializable]
  - target: $.components.schemas.Pet.properties.name
    update:
      x-pattern-message: Lower-case letters only
apigenie-generator client java openapi.yaml --overlay java.overlay.yaml -o out

Options

-c, –config

Path to the configuration file to use. See the “Configuration” section for more information.

–overlay OVERLAY

Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the “Extensions” section. Can be repeated: the overlays apply in order, after those listed under commands.generate.client_java.overlay in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay.

–strict

Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.).

–check

Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See Check that generated code is up to date.

-o, –output

Directory where the project is generated.

–package-name

Base package of the generated code, e.g. com.acme.pets; the api, model and configuration packages are derived from it unless set explicitly. Defaults to org.openapitools.client.

–package-version

Version of the Maven artifact. Defaults to the version of the API.

–library

restclient (default), resttemplate, feign or http-interface. Overrides the library of the configuration file.

-p, –property

An option of the “Configuration” section as name=value, e.g. -p useBeanValidation=false. Can be repeated; overrides the configuration file.

Configuration

version: '1.0'
commands:
  generate:
    client_java:
      library: restclient
      basePackage: com.acme.pets
      groupId: com.acme
      artifactId: pets-client
      useBeanValidation: true
      openApiNullable: true
      typeMappings:
        DateTime: java.time.Instant

The main options:

Option Description
library restclient (default), resttemplate, feign or http-interface
basePackage, apiPackage, modelPackage Packages of the code (org.openapitools.client, .api, .model by default)
groupId, artifactId, artifactVersion Coordinates of the Maven artifact (org.openapitools, openapi-java-client, the version of the API)
useSpringBoot4 The versions of Spring Boot 4 (Spring Framework 7) instead of Spring Boot 3.5
useBeanValidation Bean Validation annotations on models (true by default)
openApiNullable JsonNullable for nullable properties (true by default)
useTags Group operations by tag (true by default) or by the first segment of their path
generateStreamMethods Stream methods for streaming responses (true by default)
allHttpMethods Operations of every HTTP method (true by default; false with feign)
contentMediaTypeAsBinary Strings with a non-JSON contentMediaType are binary Resources (true by default)
useImplicitOneOfDiscriminator Dispatch oneOf schemas on a property with constant values (true by default)
jsonAccessForReadWriteOnly @JsonProperty(access) for readOnly and writeOnly properties (true by default)
typeMappings, importMappings, schemaMappings Java types of OpenAPI types and schemas

All options:

Option Description
basePackage Base package for generated code
invokerPackage Alias of basePackage
apiPackage Package for generated API classes
modelPackage Package for generated models
configPackage Package for generated configuration classes
groupId groupId in the generated pom.xml
artifactId artifactId in the generated pom.xml
artifactVersion Artifact version in the generated pom.xml
artifactDescription Artifact description in the generated pom.xml
artifactUrl Artifact URL in the generated pom.xml
licenseName License name in the generated pom.xml
licenseUrl License URL in the generated pom.xml
developerName Developer name in the generated pom.xml
developerEmail Developer email in the generated pom.xml
developerOrganization Developer organization in the generated pom.xml
developerOrganizationUrl Developer organization URL in the generated pom.xml
scmConnection SCM connection in the generated pom.xml
scmDeveloperConnection SCM developer connection in the generated pom.xml
scmUrl SCM URL in the generated pom.xml
parentGroupId groupId of the parent pom
parentArtifactId artifactId of the parent pom
parentVersion Version of the parent pom
snapshotVersion Append -SNAPSHOT to the artifact version
title Server title, used in property names (defaults to info.title)
useSpringBoot3 Generate code for Spring Boot 3 (jakarta); false means Spring Boot 2
useSpringBoot4 Generate code for Spring Boot 4
useJackson3 Use Jackson 3 (tools.jackson) instead of Jackson 2; requires useSpringBoot4
optionalAcceptNullable Use Optional.ofNullable in fluent setters of Optional properties
useJspecify Use JSpecify (org.jspecify.annotations.Nullable) for null checks
hideGenerationTimestamp Omit the generation date from @Generated annotations (default: true since 0.12.0, false before)
generationTimestamp Timestamp used in @Generated annotations when hideGenerationTimestamp is false
generatorVersion Generator version written into generated files
dateLibrary Date library: java8, java8-localdatetime, joda or legacy
documentationProvider springdoc, source or none
annotationLibrary swagger2 or none
interfaceOnly Generate only API interfaces, without controllers
skipDefaultInterface Don’t generate default implementations of API methods
useTags Group operations by tag instead of the first path segment
requestMappingMode Where to put the class-level @RequestMapping: controller, api_interface or none
useResponseEntity Wrap return types in ResponseEntity
useOptional Use Optional for optional parameters
returnSuccessCode Return the success code instead of 501 Not Implemented
unhandledException Declare ‘throws Exception’ on API methods
async Return CompletableFuture from API methods
reactive Generate reactive (WebFlux) code
responseWrapper Wrapper of return types: CompletableFuture, Callable, Future, ListenableFuture, DeferredResult or a fully qualified class name
includeHttpRequestContext Add the HTTP request (ServerWebExchange / HttpServletRequest) to API methods
singleContentTypes Use a single content type per operation
sortParamsByRequiredFlag Put required parameters before optional ones
apiNameSuffix Suffix of API class names
skipDeprecated Don’t generate code for deprecated operations
skipDisabled Don’t generate code for operations disabled with x-apigenie
implicitHeaders Describe header parameters with @Parameters instead of method parameters
implicitHeadersRegex Regular expression of header parameters described with @Parameters
useHttpServiceProxyFactoryInterfacesConfigurator Use a HttpServiceProxyFactory in HttpInterfacesAbstractConfigurator (spring-http-interface)
clientRegistrationId @ClientRegistrationId of API interfaces (spring-http-interface, Spring Boot 4)
useFeignClientUrl Use the url attribute of @FeignClient (spring-cloud)
useFeignClientContextId Use the contextId attribute of @FeignClient (spring-cloud)
useBeanValidation Use Bean Validation annotations
performBeanValidation Use Hibernate Validator annotations
useSpringBuiltInValidation Rely on Spring’s built-in validation (no @Validated)
additionalNotNullAnnotations Add @NotNull to required path and body parameters
openApiNullable Use JsonNullable for nullable properties
serializableModel Make models implement Serializable
useOneOfInterfaces Represent oneOf schemas as interfaces
useDeductionForOneOfInterfaces Deduce oneOf subtypes from their properties
generatedConstructorWithRequiredArgs Generate constructors with required arguments
generateConstructorWithAllArgs Generate constructors with all arguments
generateBuilders Generate builders for models
sortModelPropertiesByRequiredFlag Put required properties first in constructors
enumPropertyNaming Naming of enum constants: MACRO_CASE, original, legacy, camelCase, PascalCase, snake_case or UPPERCASE
useEnumCaseInsensitive Match enum values ignoring case
withXml Add XML annotations to models
useSealed Use sealed classes and interfaces (Java 17+)
containerDefaultToNull Initialize containers with null instead of empty ones
legacyDiscriminatorBehavior Use the legacy discriminator behavior
disableDiscriminatorJsonIgnoreProperties Don’t ignore discriminator properties during serialization
modelNamePrefix Prefix of model names
camelCaseDollarSign Keep the case of the first letter after a leading $ in names
useEnumValueInterface Make enums implement the ValuedEnum interface
generateJsonIncludeAnnotations Add @JsonInclude annotations to model properties
optionalNonNullPropertyJsonInclude @JsonInclude policy of optional, non-nullable properties: NON_NULL, NON_EMPTY, NON_DEFAULT or NONE
generateJsonSetterNullsAnnotations Add @JsonSetter(nulls = …) annotations to optional, non-nullable properties
optionalNonNullPropertyJsonSetterNulls @JsonSetter(nulls = …) mode of optional, non-nullable properties: SKIP or FAIL
modelNameSuffix Suffix of model names
additionalModelTypeAnnotations Annotations added to model classes, separated by semicolons
additionalEnumTypeAnnotations Annotations added to enum classes, separated by semicolons
additionalOneOfTypeAnnotations Annotations added to oneOf interfaces, separated by semicolons
typeInfoDefaultImpls Classes used as defaultImpl of @JsonTypeInfo, by schema name (Schema=Class,…)
typeMappings Mappings of OpenAPI types to Java types (type=JavaType,…)
importMappings Mappings of Java types to imports (Type=package.Type,…)
schemaMappings Mappings of schemas to existing classes (Schema=package.Class,…)
modelNameMappings Mappings of schema names to model names (Schema=Model,…)
nameMappings Mappings of property names to Java names (name=javaName,…)
parameterNameMappings Mappings of parameter names to Java names (name=javaName,…)
enumNameMappings Mappings of enum values to constant names (value=NAME,…)
contentMediaTypeAsBinary Map strings with a non-JSON contentMediaType to binary types, like format: binary (on by default)
useImplicitOneOfDiscriminator Dispatch oneOf schemas without a discriminator on a property whose value is constant in every member
jsonAccessForReadWriteOnly Read readOnly properties from JSON only and write writeOnly ones only (@JsonProperty access)
library Client library: restclient (Spring RestClient, the default), resttemplate, feign (Spring Cloud OpenFeign) or http-interface (Spring HTTP interfaces)
allHttpMethods Generate operations of every HTTP method (QUERY, COPY, …), not only the eight classic ones
generateStreamMethods Generate Stream<T> methods for text/event-stream and application/jsonl responses

Unknown options are errors.

Verification

The codegen conformance suite runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. All targets.

This target's support tier is Tier 1. It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first.

ResultsLevel 1Level 2Level 3
Release 0.12.0✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0)✓ 39 of 39 operations pass (java)
Development version✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yetruns before a releaseruns before a release
Was this helpful?