Skip to content

feat: multipart/form-data and form-urlencoded content type generation#23

Open
halotukozak wants to merge 5 commits intomasterfrom
feat/content-types
Open

feat: multipart/form-data and form-urlencoded content type generation#23
halotukozak wants to merge 5 commits intomasterfrom
feat/content-types

Conversation

@halotukozak
Copy link
Member

Summary

  • Extend SpecParser to resolve content types with priority: multipart > form-urlencoded > JSON
  • Add 10 Ktor form/multipart constants to Names.kt
  • Implement buildMultipartBody in ClientGenerator: submitFormWithBinaryData + formData {} builder, ChannelProvider for file params, ContentDisposition headers
  • Implement buildFormUrlEncodedBody: submitForm + parameters {} builder, individual typed params with toString() conversion
  • Verify CONT-03: 201 Created returns typed body, 204 No Content returns Unit

Test plan

  • Parser content type resolution tests
  • CONT-03 verification: 201 typed response + 204/200 priority
  • Multipart: single file, mixed text+file, multiple files, ChannelProvider params
  • Form-urlencoded: basic form, typed params, optional fields, non-POST method override
  • Manual: test against real specs with multipart/form endpoints

🤖 Generated with Claude Code

halotukozak and others added 5 commits March 23, 2026 10:19
…multipart constants

- SpecParser resolves requestBody content type with priority: multipart > form-urlencoded > json
- Add MULTIPART_FORM_DATA and FORM_URL_ENCODED constants to SpecParser
- Add Ktor Forms & Multipart MemberName/ClassName constants to Names.kt

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Test 201 Created with schema returns typed response (not Unit)
- Test mixed 200/204 responses uses 200 schema type

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- multipart endpoint generates submitFormWithBinaryData call
- ChannelProvider param for binary fields
- text fields use simple append
- binary fields include ContentDisposition header
- existing JSON requestBody still generates setBody pattern

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Branch buildFunctionBody on content type (multipart/form/json)
- buildMultipartBody generates submitFormWithBinaryData with formData builder
- Binary fields generate ChannelProvider + fileName + contentType params
- Text fields use simple append(key, value) pattern
- ContentDisposition header with filename for binary parts
- Extract buildUrlString, addHeaderParams, addQueryParams helpers
- Add HEADERS_CLASS constant to Names.kt

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- form-urlencoded endpoint generates submitForm with parameters builder
- non-string params use toString() conversion
- string params do NOT use toString()
- optional fields generate nullable params with null guard

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings March 23, 2026 09:34
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds multipart/form-data and application/x-www-form-urlencoded support to the OpenAPI → Ktor client generation pipeline, spanning parsing (content-type selection), name constants, client codegen, and tests.

Changes:

  • Update SpecParser requestBody content-type resolution with priority multipart > form-urlencoded > JSON.
  • Add Ktor forms/multipart KotlinPoet name constants in Names.kt.
  • Extend ClientGenerator to generate submitFormWithBinaryData / submitForm request bodies and corresponding parameters; add tests for the new behaviors.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 8 comments.

File Description
core/src/test/kotlin/com/avsystem/justworks/core/gen/ClientGeneratorTest.kt Adds tests for response code typing and basic multipart/form-urlencoded generation behavior.
core/src/main/kotlin/com/avsystem/justworks/core/parser/SpecParser.kt Chooses requestBody media type by priority and stores the chosen contentType on RequestBody.
core/src/main/kotlin/com/avsystem/justworks/core/gen/Names.kt Introduces KotlinPoet MemberName/ClassName constants for Ktor forms/multipart APIs.
core/src/main/kotlin/com/avsystem/justworks/core/gen/ClientGenerator.kt Implements multipart and form-urlencoded request generation and parameter shaping; refactors URL/header/query helpers.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

return code.build()
}

private fun buildUrlString(endpoint: Endpoint, params: Map<ParameterLocation, List<Parameter>>,): CodeBlock {
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trailing comma in the parameter list (params: Map<...>,) violates this repo's ktlint setting with ktlint_standard_trailing-comma-on-declaration-site = disabled and will fail ./gradlew ktlintCheck in CI. Remove the trailing comma from the function signature.

Suggested change
private fun buildUrlString(endpoint: Endpoint, params: Map<ParameterLocation, List<Parameter>>,): CodeBlock {
private fun buildUrlString(endpoint: Endpoint, params: Map<ParameterLocation, List<Parameter>>): CodeBlock {

Copilot uses AI. Check for mistakes.
Comment on lines +523 to +550
@Test
fun `form-urlencoded endpoint generates submitForm call`() {
val ep = endpoint(
method = HttpMethod.POST,
operationId = "createUser",
requestBody = RequestBody(
required = true,
contentType = "application/x-www-form-urlencoded",
schema = TypeRef.Inline(
properties = listOf(
PropertyModel("username", TypeRef.Primitive(PrimitiveType.STRING), null, false),
PropertyModel("age", TypeRef.Primitive(PrimitiveType.INT), null, false),
),
requiredProperties = setOf("username", "age"),
contextHint = "request",
),
),
)
val cls = clientClass(listOf(ep))
val funSpec = cls.funSpecs.first { it.name == "createUser" }
val body = funSpec.body.toString()
assertTrue(body.contains("submitForm"), "Expected submitForm call")
assertTrue(body.contains("parameters"), "Expected parameters builder")

val paramTypes = funSpec.parameters.associate { it.name to it.type.toString() }
assertEquals("kotlin.String", paramTypes["username"])
assertEquals("kotlin.Int", paramTypes["age"])
}
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new form/multipart tests only cover inline request body schemas. Since OpenAPI request bodies are often $referenced, add coverage for RequestBody(schema = TypeRef.Reference(...)) to ensure multipart/form-urlencoded generation still produces parameters and form parts (or fails with a clear error). This would catch the current behavior where non-inline schemas result in an empty parameter list/body.

Copilot uses AI. Check for mistakes.
Comment on lines +245 to +252
code.endControlFlow() // formData
code.add(")\n")
code.beginControlFlow("")
code.addStatement("$APPLY_AUTH()")
addHeaderParams(code, params)
addQueryParams(code, params)
code.endControlFlow()
code.unindent()
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

buildMultipartBody uses code.add(")\n") followed by code.beginControlFlow(""), which will generate a standalone block on the next line instead of a trailing lambda () { ... }) for submitFormWithBinaryData. That output is not valid Kotlin and will break generated clients. Rework the CodeBlock construction so the request-builder lambda is attached directly to the submitFormWithBinaryData(...) call (no newline/statement separator between ) and {).

Copilot uses AI. Check for mistakes.
Comment on lines +288 to +301
code.endControlFlow() // parameters
code.add(")\n")
code.beginControlFlow("")
code.addStatement("$APPLY_AUTH()")
addHeaderParams(code, params)
addQueryParams(code, params)

if (endpoint.method != HttpMethod.POST) {
code.addStatement("method = %T.%L", HTTP_METHOD_CLASS, endpoint.method.name.toPascalCase())
}

code.endControlFlow()
code.unindent()
code.add("}.%M()\n", resultFun)
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same issue in buildFormUrlEncodedBody: code.add(")\n") then code.beginControlFlow("") will emit a separate block statement rather than the trailing lambda for submitForm(...). This will produce invalid Kotlin in the generated client. Build the code so the { ... } block is syntactically part of the submitForm(...) call (e.g., ) { on the same statement).

Copilot uses AI. Check for mistakes.
Comment on lines +372 to +382
private fun extractInlineProperties(requestBody: RequestBody): List<PropertyModel> =
when (val schema = requestBody.schema) {
is TypeRef.Inline -> schema.properties
else -> emptyList()
}

private fun extractRequiredProperties(requestBody: RequestBody): Set<String> =
when (val schema = requestBody.schema) {
is TypeRef.Inline -> schema.requiredProperties
else -> emptySet()
}
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

extractInlineProperties/extractRequiredProperties return empty for any non-TypeRef.Inline request body schema. For multipart/form-url-encoded request bodies defined via $ref (common in OpenAPI), SpecParser will produce TypeRef.Reference(...), so this generator will emit no parameters and an empty form body. Consider resolving TypeRef.Reference to its SchemaModel (via the ApiSpec passed into generate) or having the parser inline referenced object schemas specifically for form content types.

Copilot uses AI. Check for mistakes.
Comment on lines +343 to +361
private fun buildMultipartParameters(requestBody: RequestBody): List<ParameterSpec> {
val properties = extractInlineProperties(requestBody)
return properties.flatMap { prop ->
if (prop.type.isBinaryUpload()) {
listOf(
ParameterSpec(prop.name.toCamelCase(), CHANNEL_PROVIDER),
ParameterSpec("${prop.name.toCamelCase()}Name", STRING),
ParameterSpec("${prop.name.toCamelCase()}ContentType", CONTENT_TYPE_CLASS),
)
} else {
listOf(
ParameterSpec(
prop.name.toCamelCase(),
TypeMapping.toTypeName(prop.type, modelPackage),
),
)
}
}
}
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

buildMultipartParameters ignores required/optional information from the inline schema (e.g., requiredProperties / PropertyModel.nullable). As a result, optional multipart fields (including optional file uploads) would still be generated as non-null function parameters, forcing callers to always provide values. Use the schema's required set to make parameters nullable with defaults where appropriate, and align the body generation to conditionally append only when non-null.

Copilot uses AI. Check for mistakes.
Comment on lines +219 to +242
for (prop in properties) {
val paramName = prop.name.toCamelCase()
if (prop.type.isBinaryUpload()) {
code.beginControlFlow(
"append(%S, %L, %T.build",
prop.name,
paramName,
HEADERS_CLASS,
)
code.addStatement(
"append(%T.ContentType, %L.toString())",
HTTP_HEADERS_OBJECT,
"${paramName}ContentType",
)
code.addStatement(
"append(%T.ContentDisposition, %P)",
HTTP_HEADERS_OBJECT,
CodeBlock.of("filename=\"\${%L}\"", "${paramName}Name"),
)
code.endControlFlow()
code.add(")\n")
} else {
code.addStatement("append(%S, %L)", prop.name, paramName)
}
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

buildMultipartBody appends every multipart part unconditionally. If any multipart property is optional (nullable), the generated code will still try to append it, which either forces non-null parameters or risks appending invalid values. Mirror the optionalGuard approach used for form-urlencoded so optional parts are only appended when present.

Copilot uses AI. Check for mistakes.
code.beginControlFlow("")
code.addStatement("$APPLY_AUTH()")
addHeaderParams(code, params)
addQueryParams(code, params)
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

buildMultipartBody always uses submitFormWithBinaryData without overriding the HTTP method. submitFormWithBinaryData defaults to POST, so multipart endpoints declared as PUT/PATCH/DELETE would be generated incorrectly. Add the same non-POST method override logic you already have in buildFormUrlEncodedBody (or pass method = ... to the submit call).

Suggested change
addQueryParams(code, params)
addQueryParams(code, params)
if (endpoint.method != HttpMethod.POST) {
code.addStatement("method = %T.%L", HTTP_METHOD_CLASS, endpoint.method.name.toPascalCase())
}

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants