Skip to content

Commit 0393d39

Browse files
authored
feat: add support for oneOf in sttp4 client (#22916)
* feat: add support for `oneOf` in sttp4 client * fix: pass `Option[String]` directly to .header * fix: use oneOf mapping to map discriminator values to types * fix: remove unecessary whitespaces * fix: generate samples, make a new one for sttp4-circe * fix: make partial function total * fix: only use semiauto derivation On large APIs this can dramatically speed up compilation. * fix: missing comma * fix: re-run generate-samples script * docs: update documentation * fix: spaces, not tabs * ci: add new samples directory * fix: bump scala version * fix: url-form-encoded cases * chore: regenerate sttp4 samples after upstream merge * fix: sttp4 json4s JsonSupport uses sealed trait serializers instead of Enumeration-based EnumNameSerializer The json4s variant of JsonSupport.scala used EnumNameSerializer which expects Scala Enumeration types, but sttp4 model templates generate sealed traits with case objects for enums. This caused compilation errors since the types are incompatible. Replace EnumNameSerializer with direct references to the implicit Serializer objects already defined in each enum's companion object. * fix: sttp4 oneOf with parent properties - resolve aliased children, propagate parent props When a schema has both its own properties and a oneOf composition, the sttp4 generator previously had three issues: 1. Empty oneOf children (no type, no properties) were silently dropped because DefaultCodegen's unaliasSchema treated them as type aliases, replacing the model name with the language type (e.g. io.circe.Json). 2. Parent-owned properties (e.g. cancellation_datetime) were lost entirely - they didn't appear on the sealed trait or any child. 3. Sibling properties from other oneOf children could contaminate each child's vars list via DefaultCodegen's property merging. This fix: - Resolves aliased oneOf children by looking at the original OpenAPI schema's $refs to restore correct model names - Identifies parent-owned properties and propagates them to each child model's allVars so they appear in generated case classes - Renders parent properties as abstract def members on the sealed trait for compile-time enforcement - Adds a test covering the CancellationInfo pattern (parent with properties + oneOf with empty and non-empty children) * fix: use wrapper composition for shared oneOf members in sttp4 client When a schema is referenced by multiple oneOf parents (e.g., Dog and Cat used by both Pet and Animal), the generator cannot inline them into any single parent. Previously this produced broken code: sealed traits with no subtypes, causing circe derivation and json4s serialization to fail. This fix introduces wrapper composition for shared members: each parent generates wrapper case classes (e.g., DogPet, CatAnimal) inside its companion object that delegate to the standalone type. Hand-written codecs replace semiauto derivation when wrappers are present. Exclusive members (used by only one parent) continue to be inlined directly, preserving the existing behavior. Fixes compilation errors reported in PR #22916. * fix: new issues after merging master branch * fix: use propertyBaseName for discriminator in sttp4 serialization When the discriminator property name is a Scala keyword (e.g., `type`), the codegen escapes it with backticks for use as a Scala identifier. However, the serialization templates (circe and json4s) were using `discriminator.propertyName` which contains the escaped form, producing incorrect JSON field names like `\`type\`` instead of `type`. Switch all 10 usages in model.mustache to `discriminator.propertyBaseName` which holds the original, unescaped wire name from the OpenAPI spec. Add test case with Shape/Circle/Square using `type` as discriminator.
1 parent 99662a2 commit 0393d39

46 files changed

Lines changed: 2213 additions & 149 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/samples-scala-client.yaml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ on:
1111
- samples/client/petstore/scala-sttp/**
1212
- samples/client/petstore/scala-sttp-circe/**
1313
- samples/client/petstore/scala-sttp4/**
14+
- samples/client/petstore/scala-sttp4-circe/**
1415
pull_request:
1516
paths:
1617
- samples/client/petstore/scalaz/**
@@ -21,6 +22,7 @@ on:
2122
- samples/client/petstore/scala-sttp/**
2223
- samples/client/petstore/scala-sttp-circe/**
2324
- samples/client/petstore/scala-sttp4/**
25+
- samples/client/petstore/scala-sttp4-circe/**
2426
jobs:
2527
build:
2628
name: Build sbt/Scala
@@ -38,6 +40,7 @@ jobs:
3840
- samples/client/petstore/scala-sttp
3941
- samples/client/petstore/scala-sttp-circe
4042
- samples/client/petstore/scala-sttp4
43+
- samples/client/petstore/scala-sttp4-circe
4144
services:
4245
petstore-api:
4346
image: swaggerapi/petstore

‎bin/configs/scala-sttp4-circe.yaml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
generatorName: scala-sttp4
2+
outputDir: samples/client/petstore/scala-sttp4-circe
3+
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
4+
templateDir: modules/openapi-generator/src/main/resources/scala-sttp4
5+
additionalProperties:
6+
hideGenerationTimestamp: "true"
7+
jsonLibrary: "circe"

‎docs/generators/scala-sttp4.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
2020
| ------ | ----------- | ------ | ------- |
2121
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
2222
|apiPackage|package for generated api classes| |null|
23+
|circeExtrasVersion|The version of circe-generic-extras library| |0.14.4|
24+
|circeVersion|The version of circe library| |0.14.15|
2325
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (preferred for JDK 1.8+)</dd></dl>|java8|
2426
|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.</dd></dl>|true|
2527
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
@@ -36,7 +38,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
3638
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
3739
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
3840
|sourceFolder|source folder for generated code| |null|
39-
|sttpClientVersion|The version of sttp client| |4.0.0-M1|
41+
|sttpClientVersion|The version of sttp client| |4.0.15|
4042

4143
## IMPORT MAPPING
4244

‎modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttp4ClientCodegen.java‎

Lines changed: 277 additions & 11 deletions
Large diffs are not rendered by default.

‎modules/openapi-generator/src/main/resources/scala-sttp4/api.mustache‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class {{classname}}(baseUrl: String) {
2020
{{>javadoc}}
2121

2222
{{/javadocRenderer}}
23-
def {{operationId}}({{>methodParameters}}): Request[{{#separateErrorChannel}}Either[ResponseException[String, Exception], {{>operationReturnType}}]{{/separateErrorChannel}}{{^separateErrorChannel}}{{>operationReturnType}}{{/separateErrorChannel}}] =
23+
def {{operationId}}({{>methodParameters}}): Request[{{#separateErrorChannel}}Either[ResponseException[String], {{>operationReturnType}}]{{/separateErrorChannel}}{{^separateErrorChannel}}{{>operationReturnType}}{{/separateErrorChannel}}] =
2424
basicRequest
2525
.method(Method.{{httpMethod.toUpperCase}}, uri"$baseUrl{{{path}}}{{#queryParams.0}}?{{/queryParams.0}}{{#queryParams}}{{baseName}}=${ {{paramName}} }{{^-last}}&{{/-last}}{{/queryParams}}{{#authMethods}}{{#isApiKey}}{{#isKeyInQuery}}{{#queryParams.0}}&{{/queryParams.0}}{{^queryParams.0}}?{{/queryParams.0}}{{keyParamName}}=${apiKeyQuery}{{/isKeyInQuery}}{{/isApiKey}}{{/authMethods}}")
2626
.contentType({{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}}){{#headerParams}}
@@ -31,11 +31,11 @@ class {{classname}}(baseUrl: String) {
3131
.cookie("{{keyParamName}}", apiKeyCookie){{/isKeyInCookie}}{{/isApiKey}}{{/authMethods}}{{#formParams.0}}{{^isMultipart}}
3232
.body(Map({{#formParams}}
3333
{{>paramFormCreation}}{{^-last}},{{/-last}}{{/formParams}}
34-
)){{/isMultipart}}{{#isMultipart}}
34+
).collect { case (k, Some(v)) => k -> v }){{/isMultipart}}{{#isMultipart}}
3535
.multipartBody(Seq({{#formParams}}
3636
{{>paramMultipartCreation}}{{^-last}}, {{/-last}}{{/formParams}}
3737
).flatten){{/isMultipart}}{{/formParams.0}}{{#bodyParam}}
38-
.body({{paramName}}){{/bodyParam}}
38+
.body(asJson({{paramName}})){{/bodyParam}}
3939
.response({{#separateErrorChannel}}{{^returnType}}asString.mapWithMetadata(ResponseAs.deserializeRightWithError(_ => Right(()))){{/returnType}}{{#returnType}}asJson[{{>operationReturnType}}]{{/returnType}}{{/separateErrorChannel}}{{^separateErrorChannel}}{{^returnType}}asString.mapWithMetadata(ResponseAs.deserializeRightWithError(_ => Right(()))).getRight{{/returnType}}{{#returnType}}asJson[{{>operationReturnType}}].getRight{{/returnType}}{{/separateErrorChannel}})
4040

4141
{{/operation}}

‎modules/openapi-generator/src/main/resources/scala-sttp4/build.sbt.mustache‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ version := "{{artifactVersion}}"
22
name := "{{artifactId}}"
33
organization := "{{groupId}}"
44

5-
scalaVersion := "2.13.16"
5+
scalaVersion := "2.13.18"
66
crossScalaVersions := Seq(scalaVersion.value, "2.12.20")
77

88
libraryDependencies ++= Seq(
@@ -15,7 +15,9 @@ libraryDependencies ++= Seq(
1515
"org.json4s" %% "json4s-jackson" % "{{json4sVersion}}"
1616
{{/json4s}}
1717
{{#circe}}
18-
"com.softwaremill.sttp.client4" %% "circe" % "{{sttpClientVersion}}"
18+
"com.softwaremill.sttp.client4" %% "circe" % "{{sttpClientVersion}}",
19+
"io.circe" %% "circe-generic" % "{{circeVersion}}",
20+
"io.circe" %% "circe-generic-extras" % "{{circeExtrasVersion}}",
1921
{{/circe}}
2022
)
2123

‎modules/openapi-generator/src/main/resources/scala-sttp4/jsonSupport.mustache‎

Lines changed: 4 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -7,34 +7,11 @@ import {{modelPackage}}._
77
{{#json4s}}
88
import org.json4s._
99
import sttp.client4.json4s.SttpJson4sApi
10-
import scala.reflect.ClassTag
1110

1211
object JsonSupport extends SttpJson4sApi {
1312
def enumSerializers: Seq[Serializer[_]] = Seq[Serializer[_]](){{#models}}{{#model}}{{#isEnum}} :+
14-
new EnumNameSerializer({{classname}}){{/isEnum}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+
15-
new EnumNameSerializer({{classname}}Enums.{{datatypeWithEnum}}){{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}}
16-
17-
private class EnumNameSerializer[E <: Enumeration: ClassTag](enumeration: E) extends Serializer[E#Value] {
18-
import JsonDSL._
19-
val EnumerationClass: Class[E#Value] = classOf[E#Value]
20-
21-
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), E#Value] = {
22-
case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) =>
23-
json match {
24-
case JString(value) => enumeration.withName(value)
25-
case value => throw new MappingException(s"Can't convert $value to $EnumerationClass")
26-
}
27-
}
28-
29-
private[this] def isValid(json: JValue) = json match {
30-
case JString(value) if enumeration.values.exists(_.toString == value) => true
31-
case _ => false
32-
}
33-
34-
def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
35-
case i: E#Value => i.toString
36-
}
37-
}
13+
{{classname}}.{{classname}}Serializer{{/isEnum}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+
14+
{{classname}}Enums.{{datatypeWithEnum}}.{{datatypeWithEnum}}Serializer{{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}}
3815

3916
implicit val format: Formats = DefaultFormats ++ enumSerializers ++ DateSerializers.all ++ AdditionalTypeSerializers.all
4017
implicit val serialization: org.json4s.Serialization = org.json4s.jackson.Serialization
@@ -43,17 +20,9 @@ object JsonSupport extends SttpJson4sApi {
4320
{{#circe}}
4421
import io.circe.{Decoder, Encoder}
4522
import io.circe.generic.AutoDerivation
46-
import sttp.client3.circe.SttpCirceApi
23+
import sttp.client4.circe.SttpCirceApi
4724

4825
object JsonSupport extends SttpCirceApi with AutoDerivation with DateSerializers with AdditionalTypeSerializers {
49-
50-
{{#models}}
51-
{{#model}}
52-
{{#isEnum}}
53-
implicit val {{classname}}Decoder: Decoder[{{classname}}.{{classname}}] = Decoder.decodeEnumeration({{classname}})
54-
implicit val {{classname}}Encoder: Encoder[{{classname}}.{{classname}}] = Encoder.encodeEnumeration({{classname}})
55-
{{/isEnum}}
56-
{{/model}}
57-
{{/models}}
26+
// Enum encoders/decoders are defined in their respective companion objects
5827
}
5928
{{/circe}}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{{#authMethods.0}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}}apiKeyHeader: String{{/isKeyInHeader}}{{#isKeyInQuery}}apiKeyQuery: String{{/isKeyInQuery}}{{#isKeyInCookie}}apiKeyCookie: String{{/isKeyInCookie}}{{/isApiKey}}{{#isBasic}}{{#isBasicBasic}}username: String, password: String{{/isBasicBasic}}{{#isBasicBearer}}bearerToken: String{{/isBasicBearer}}{{/isBasic}}{{^-last}}, {{/-last}}{{/authMethods}})({{/authMethods.0}}{{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}{{#isContainer}}{{dataType}}{{/isContainer}}{{^isContainer}}Option[{{dataType}}]{{/isContainer}}{{/required}}{{^defaultValue}}{{^required}}{{^isContainer}} = None{{/isContainer}}{{/required}}{{/defaultValue}}{{^-last}}, {{/-last}}{{/allParams}}
1+
{{#authMethods.0}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}}apiKeyHeader: String{{/isKeyInHeader}}{{#isKeyInQuery}}apiKeyQuery: String{{/isKeyInQuery}}{{#isKeyInCookie}}apiKeyCookie: String{{/isKeyInCookie}}{{/isApiKey}}{{#isBasic}}{{#isBasicBasic}}username: String, password: String{{/isBasicBasic}}{{#isBasicBearer}}bearerToken: String{{/isBasicBearer}}{{/isBasic}}{{^-last}}, {{/-last}}{{/authMethods}})({{/authMethods.0}}{{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}Option[{{dataType}}]{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{^-last}}, {{/-last}}{{/allParams}}

0 commit comments

Comments
 (0)