# client java

Source: https://apigenie.pl/techdocs/reference/cli-generate_client_java

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)](/techdocs/reference/cli-generate_client_java_asyncapi).

## Usage

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

## Description

The input must be an OpenAPI 3.0, 3.1 or 3.2 document. The generated project needs Java 17 and
Maven; its dependencies come from Maven Central.

```java
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 `Resource`s for
files, JSON parts for objects, the content type of the `encoding`), text or binary (`Resource`).
Binary responses are `Resource`s. 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, OAuth 2 and OpenID Connect schemes, whose tokens are obtained
  elsewhere), `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.

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`)

`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` and, in the base package,
`ApiClient`, `ApiException`, `ProblemDetailsException` (with a problem schema),
`ServerConfiguration`, `ServerVariable`, `StreamDecoder` (with streaming responses),
`RFC3339DateFormat`, `auth/` (`Authentication`, `HttpBearerAuth`, `HttpBasicAuth`,
`ApiKeyAuth`), `api/` and `model/`.

Not supported: callbacks and webhooks, OAuth 2 flows (tokens are set by hand), mutual TLS (set an
`SSLContext` on the request factory of the `RestClient.Builder` or `RestTemplate` given to
`ApiClient`), `prefixItems` (tuples are `List<Object>`), `patternProperties`, and constraints Bean
Validation can't express (`multipleOf`, conditional schemas).
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 |
| `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`:

```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
```

```sh
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.`).

### -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

```yaml
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 `Resource`s (`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 |
| `generationTimestamp` | Timestamp used in @Generated annotations |
| `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 |
| `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.
