Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1297,6 +1297,8 @@ private PathItem buildPathItem(RequestMethod requestMethod, Operation operation,
String name = parameter.getName();
if (!StringUtils.containsAny(operationPath, "{" + name + "}", "{*" + name + "}"))
paramIt.remove();
else
SpringDocUtils.fixNullablePathParameter(parameter);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ private TypeAndTypeAnnotations resolveTypeAndTypeAnnotationsForParameter(MethodP
&& delegatingMethodParameter.getField() != null) {
AnnotatedType annotated = delegatingMethodParameter.getField().getAnnotatedType();
Type type = GenericTypeResolver.resolveType(annotated.getType(), methodParameter.getContainingClass());
return new TypeAndTypeAnnotations(type, annotationsFromAnnotatedTypeArguments(annotated));
return new TypeAndTypeAnnotations(type, annotationsFromAnnotatedType(annotated));
}

Type type = GenericTypeResolver.resolveType(methodParameter.getGenericParameterType(), methodParameter.getContainingClass());
Expand All @@ -462,6 +462,20 @@ private TypeAndTypeAnnotations resolveTypeAndTypeAnnotationsForParameter(MethodP
private record TypeAndTypeAnnotations(Type type, Annotation[] typeAnnotations) {
}

/**
* Collects annotations declared on the type itself and on each type argument of an
* {@link AnnotatedParameterizedType}.
*
* @param annotatedType the annotated type
* @return a new array, possibly empty
*/
private static Annotation[] annotationsFromAnnotatedType(AnnotatedType annotatedType) {
return Stream.concat(
Arrays.stream(annotatedType.getAnnotations()),
Arrays.stream(annotationsFromAnnotatedTypeArguments(annotatedType)))
.toArray(Annotation[]::new);
}

/**
* Collects annotations declared on each type argument of an {@link AnnotatedParameterizedType}.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
Expand Down Expand Up @@ -215,6 +216,30 @@ else if (types == null && "null".equals(addPropSchema.getType())) {
}
}

/**
* Removes nullability from a path parameter's schema. A path parameter is always
* required and can never be {@code null}, so a nullable schema (e.g. propagated from a
* JSpecify {@code @Nullable} annotation on a backing {@code @ParameterObject} field that
* is reused as both a path and an optional query parameter) is invalid here.
*
* @param parameter the path parameter
*/
public static void fixNullablePathParameter(Parameter parameter) {
Schema<?> schema = parameter.getSchema();
if (schema == null)
return;
Set<String> types = schema.getTypes();
if (types != null) {
types.remove("null");
if (types.isEmpty())
schema.setTypes(null);
}
if ("null".equals(schema.getType()))
schema.setType(null);
if (Boolean.TRUE.equals(schema.getNullable()))
schema.setNullable(null);
}

/**
* Handle schema types.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,39 @@ springDocProviders, new SpringDocCustomizers(Optional.empty(), Optional.empty(),
assertThat(parameterWithoutSchema.getIn(), is(ParameterIn.QUERY.toString()));
}

@Test
void removesNullableFromPathParameterSchema() {
resource = new EmptyPathsOpenApiResource(
GROUP_NAME,
openAPIBuilderObjectFactory,
requestBuilder,
responseBuilder,
operationParser,
new SpringDocConfigProperties(),
springDocProviders, new SpringDocCustomizers(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty())
);

final String pathParamName = "clinicId";
final Parameter nullablePathParameter = new Parameter()
.name(pathParamName)
.in(ParameterIn.PATH.toString())
.schema(new StringSchema().nullable(true));

final Operation operation = new Operation();
operation.setParameters(singletonList(nullablePathParameter));

final RouterOperation routerOperation = new RouterOperation();
routerOperation.setMethods(new RequestMethod[] { GET });
routerOperation.setOperationModel(operation);
routerOperation.setPath(PATH + "/{" + pathParamName + "}");

resource.calculatePath(routerOperation, Locale.getDefault(), this.openAPI);

final Parameter pathParameter = resource.getOpenApi(null, Locale.getDefault())
.getPaths().get(PATH + "/{" + pathParamName + "}").getGet().getParameters().get(0);
assertThat(pathParameter.getSchema().getNullable(), nullValue());
}

@Test
void preLoadingModeShouldNotOverwriteServers() throws InterruptedException {
doCallRealMethod().when(openAPIService).updateServers(any(), any());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
*
* *
* * *
* * * *
* * * * *
* * * * * * Copyright 2019-2026 the original author or authors.
* * * * * *
* * * * * * Licensed under the Apache License, Version 2.0 (the "License");
* * * * * * you may not use this file except in compliance with the License.
* * * * * * You may obtain a copy of the License at
* * * * * *
* * * * * * https://www.apache.org/licenses/LICENSE-2.0
* * * * * *
* * * * * * Unless required by applicable law or agreed to in writing, software
* * * * * * distributed under the License is distributed on an "AS IS" BASIS,
* * * * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * * * * See the License for the specific language governing permissions and
* * * * * * limitations under the License.
* * * * *
* * * *
* * *
* *
*
*/

package test.org.springdoc.api.v30.app176;

import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import org.springdoc.core.annotations.ParameterObject;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
class HelloController {

@GetMapping("/clinics/{clinicId}/vets")
@Parameter(name = "clinicId", in = ParameterIn.PATH)
public void find(@ParameterObject SearchCriteria searchCriteria) {
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
*
* *
* * *
* * * *
* * * * *
* * * * * * Copyright 2019-2026 the original author or authors.
* * * * * *
* * * * * * Licensed under the Apache License, Version 2.0 (the "License");
* * * * * * you may not use this file except in compliance with the License.
* * * * * * You may obtain a copy of the License at
* * * * * *
* * * * * * https://www.apache.org/licenses/LICENSE-2.0
* * * * * *
* * * * * * Unless required by applicable law or agreed to in writing, software
* * * * * * distributed under the License is distributed on an "AS IS" BASIS,
* * * * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * * * * See the License for the specific language governing permissions and
* * * * * * limitations under the License.
* * * * *
* * * *
* * *
* *
*
*/

package test.org.springdoc.api.v30.app176;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
@interface Nullable {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
*
* *
* * *
* * * *
* * * * *
* * * * * * Copyright 2019-2026 the original author or authors.
* * * * * *
* * * * * * Licensed under the Apache License, Version 2.0 (the "License");
* * * * * * you may not use this file except in compliance with the License.
* * * * * * You may obtain a copy of the License at
* * * * * *
* * * * * * https://www.apache.org/licenses/LICENSE-2.0
* * * * * *
* * * * * * Unless required by applicable law or agreed to in writing, software
* * * * * * distributed under the License is distributed on an "AS IS" BASIS,
* * * * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * * * * See the License for the specific language governing permissions and
* * * * * * limitations under the License.
* * * * *
* * * *
* * *
* *
*
*/

package test.org.springdoc.api.v30.app176;

import io.swagger.v3.oas.annotations.Parameter;

/**
* A parameter object whose {@code clinicId} field is reused as both an optional, nullable
* query parameter and a (required, non-null) path parameter, depending on the controller.
*/
class SearchCriteria {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What is the reason for wanting reuse this object in different contexts where @Nullable is not always correct? For the case where it is used in a path-parameter context, then the annotation misleads the consumer using the object, since the object says nullable but it actually is required?

Isn't the better approach to have an object specifically for the path scenario, so that it both documents the nullable correctly inwards and outwards?

@tthornton3-chwy tthornton3-chwy Jun 26, 2026

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

An example: we follow the CQRS-pattern, and have types that get deserialized for some queries. There's an "admin" path in, something like /admin/vet which can do whatever it wants (add a resource id as a query param, not add an id, put any id it wants). But there is also a "scoped" path, think of something like /resource/{resourceId}/vet that requires it (and authenticates that it is able to access said resourceId). They do the absolute same thing though, and come back to the same type. Sure, we could have an AdminSearchCriteria vs ScopedSearchCriteria, but now we have two methods in our service and gotta map one probably back to the other so we can stay DRY.
So the case where a PathParameter exists, is valid, then its required no matter what, and this helps us do that! Swagger Core didn't seem the right place to think about this, since that's a layer deeper than it probably should be. And with this I get both:

{
                        "name": "resourceId",
                        "in": "path",
                        "description": "Find something affiliated with something id.",
                        "required": true,
                        "schema": {
                            "type": "string",
                            "description": "Find Something affiliated with this something id.",
                            "example": 11111
                        },
                        "example": 1111
                    }

for the scoped and

                    {
                        "name": "resourceId",
                        "in": "query",
                        "description": "Find something affiliated with this something id.",
                        "required": false,
                        "schema": {
                            "type": [
                                "string",
                                "null"
                            ],
                            "description": "Find Something affiliated with this something id.",
                            "example": 11111
                        },
                        "example": 11111
                    },

which is exactly what we want :)

This use case may be semi-niche, but I don't think the case of forcing a path parameter to be required is niche at all!


@Parameter(description = "Find vets affiliated with this clinic id.")
private @Nullable String clinicId;

@Parameter(description = "Find vets with this name.")
private @Nullable String name;

public String getClinicId() {
return clinicId;
}

public void setClinicId(String clinicId) {
this.clinicId = clinicId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
*
* *
* * *
* * * *
* * * * *
* * * * * * Copyright 2019-2026 the original author or authors.
* * * * * *
* * * * * * Licensed under the Apache License, Version 2.0 (the "License");
* * * * * * you may not use this file except in compliance with the License.
* * * * * * You may obtain a copy of the License at
* * * * * *
* * * * * * https://www.apache.org/licenses/LICENSE-2.0
* * * * * *
* * * * * * Unless required by applicable law or agreed to in writing, software
* * * * * * distributed under the License is distributed on an "AS IS" BASIS,
* * * * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * * * * See the License for the specific language governing permissions and
* * * * * * limitations under the License.
* * * * *
* * * *
* * *
* *
*
*/

package test.org.springdoc.api.v30.app176;

import com.jayway.jsonpath.JsonPath;
import net.minidev.json.JSONArray;
import org.junit.jupiter.api.Test;
import org.springdoc.core.utils.Constants;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* Verifies that {@code nullable: true} (propagated from a TYPE_USE {@code @Nullable}
* annotation on a {@code @ParameterObject} field under OpenAPI 3.0) is cleared when that
* field is reused as a path parameter, while it is preserved for query parameters.
*/
@ActiveProfiles("test")
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(properties = "springdoc.api-docs.version=openapi_3_0")
class SpringDocApp176Test {

private static final String PATH = "$.paths.['/clinics/{clinicId}/vets'].get.parameters";

@Autowired
protected MockMvc mockMvc;

private static Object readSingle(String result, String jsonPath) {
return ((JSONArray) JsonPath.parse(result).read(jsonPath)).get(0);
}

@Test
void pathParameterIsNotNullableButQueryParameterIs() throws Exception {
MvcResult mockMvcResult = mockMvc.perform(get(Constants.DEFAULT_API_DOCS_URL))
.andExpect(status().isOk()).andReturn();
String result = mockMvcResult.getResponse().getContentAsString();

// A path parameter is always required and can never be null.
assertThat(readSingle(result, PATH + "[?(@.name == 'clinicId')].required"))
.isEqualTo(Boolean.TRUE);
assertThat(readSingle(result, PATH + "[?(@.name == 'clinicId')].schema.type"))
.isEqualTo("string");
assertThat((JSONArray) JsonPath.parse(result).read(PATH + "[?(@.name == 'clinicId')].schema.nullable"))
.isEmpty();

// A nullable query parameter keeps nullable: true.
assertThat(readSingle(result, PATH + "[?(@.name == 'name')].required"))
.isEqualTo(Boolean.FALSE);
assertThat(readSingle(result, PATH + "[?(@.name == 'name')].schema.type"))
.isEqualTo("string");
assertThat(readSingle(result, PATH + "[?(@.name == 'name')].schema.nullable"))
.isEqualTo(Boolean.TRUE);
}

@SpringBootApplication
static class SpringDocTestApp {
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
*
* *
* * *
* * * *
* * * * *
* * * * * * Copyright 2019-2026 the original author or authors.
* * * * * *
* * * * * * Licensed under the Apache License, Version 2.0 (the "License");
* * * * * * you may not use this file except in compliance with the License.
* * * * * * You may obtain a copy of the License at
* * * * *
* * * * * * https://www.apache.org/licenses/LICENSE-2.0
* * * * * *
* * * * * * Unless required by applicable law or agreed to in writing, software
* * * * * * distributed under the License is distributed on an "AS IS" BASIS,
* * * * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * * * * See the License for the specific language governing permissions and
* * * * * * limitations under the License.
* * * * *
* * * *
* * *
* *
*
*/

package test.org.springdoc.api.v31.app175;

import org.springdoc.core.annotations.ParameterObject;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
class HelloController {

@GetMapping("/vets")
public void find(@ParameterObject SearchCriteria searchCriteria) {
}

}
Loading