Repository navigation
Description
Bug Report Checklist
- Have you provided a full/minimal spec to reproduce the issue?
- Have you validated the input using an OpenAPI validator (example)?
- Have you tested with the latest master to confirm the issue still exists?
- Have you searched for related issues/PRs?
- What's the actual output vs expected output?
- [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description
In Java CodeGeneration openapiNullable is used to determine if the special type JsonNullable should be used or not.
The description of this type from the original documentation is as follows:
The JsonNullable wrapper shall be used to wrap Java bean fields for which it is important to distinguish between an explicit "null" and the field not being present. A typical usage is when implementing Json Merge Patch where an explicit "null"has the meaning "set this field to null / remove this field" whereas a non-present field has the meaning "don't change the value of this field".
So, in a request body (especially in PATCH requests) it is utilized to signalize, if a specifc field was specified in the body or not. This can be used to just ignore any change to the property and keep the old value or to apply a new value to it.
BUT. The current implementation is using the nullable property of a field instead of the required property. So nullable should actually tell about if a field can be null or not IF it is specified. nullable tells nothing about if a field must be present or can be omitted. This is what required is for. required declares, if a field as to be present or not, independent of if it may be nullable or not.
The fix would be to swap nullable and required for the usage of JsonNullable.
openapi-generator version
6.4.0, but goes back until 5.6.0 minimum (probably since openapiNullable was implemented first).
OpenAPI declaration file content or url
Existing /3_0/petstore-with-nullable-required.yaml can be used as an example
Taking the following Pet model from the referency specification:
Pet:
title: a Pet
description: A pet for sale in the pet store
type: object
required:
- name
- photoUrls
properties:
id:
type: integer
format: int64
category:
$ref: '#/components/schemas/Category'
name:
type: string
example: doggie
nullable: true
photoUrls:
type: array
xml:
name: photoUrl
wrapped: true
items:
type: string
The Pet class would be generated like:
public class Pet {
@JsonProperty("id")
private Long id;
@JsonProperty("category")
private Category category;
@JsonProperty("name")
private String name;
@JsonProperty("photoUrls")
@Valid
private List<String> photoUrls = new ArrayList<>();
}
Although, because only name and photoUrls are declared as required, all other properties should be wrapped in JsonNullable and name should be initialized with null as it is declared as nullable additionally.
public class Pet {
@JsonProperty("id")
private JsonNullable<Long> id = JsonNullable.undefined();
@JsonProperty("category")
private JsonNullable<Category> category = JsonNullable.undefined();
@JsonProperty("name")
private String name = null;
@JsonProperty("photoUrls")
@Valid
private List<String> photoUrls = new ArrayList<>();
}
Generation Details
./bin/generate-samples.sh bin/configs/spring-openapi-nullable-required.yaml
Steps to reproduce
I already created a pull request: #14766
Related issues/PRs
Didn't find any existing issue to this (which is quite suprising).
Suggest a fix
I already created a pull request: #14766
I am totally aware that this is a huge breaking change so I would like to discuss this issue openly. Maybe we need some kind of flag for the new behaviour. Any critics to this behaviour are welcome.
Activity
[Java][Spring] Implement JsonNullable in openapiNullable correctly - f…
daberni commentedon Feb 20, 2023
Just stumbled around an additional mustache template
>beanValidationwhererequiredandisNullableare also mixed up.welshm commentedon Feb 20, 2023
I disagree with the assessment that
JsonNullableshould be set based onrequired. For the purpose of this discussion,nullis considered a value.nullableindicates that the field may accept thenullvalue.requiredindicates that a field must be set and have a value.If a field is both
nullableandrequired- that value may benullor any other valid value for that field.JsonNullableis used to determine whether anullvalue was explicitly set or not. If a field is notnullable- then there is no need to useJsonNullable; anullvalue is not permitted and can be ignored. Whether it isrequiredor not is irrelevant.If a field is
requiredandnullableit does not needJsonNullablebecause there must be a value set. There cannot be an absence of a value.So I think
JsonNullableshould be used only when a field is bothnullableand notrequired(which is what the generator is currently doing). In your example,idandcategoryare not declared nullable and so do not needJsonNullable.borsch commentedon Feb 20, 2023
@daberni in general there are 4 possible scenarion for
nullable+requirednull. No need to addJsonNullablea) can have valid value
b) can be set to
nullwith the meaning "let's set value (ex. in DB) explicitly tonull"c) can be absent which mean "do nothing with this field"
nulldoes not allowed. No need to useJsonNullableb)does not applicable here since can not be set tonull. No need to useJsonNullableSo based on all these cases only for point 2 we can use
JsonNullabl, because that's the only case wherevalid value,null&undefined(not present) can happendaberni commentedon Feb 21, 2023
@welshm Interesting approach, I didn't see it this way so far but I understand the idea.
Probably this would be a somehow working approach, the problem is, that it is not implemented this way right now.
Currently, usage of
JsonNullableis only determined by the definition ofnullable. You can find this in the nullableDataType.mustache template. As far as I can see, there is no further differentiation.If this would be combined with
requiredthis might be one way.But additionally, which is quite confusing, the beanValidation.mustache depends on
requiredinstead ofnullable.So that this would work as you described, one would have to combine this together with
openapiNullabletoo.One problem which currently also arises, probably because of the combination of the above incomplete implementations, that Spring Model Binding Validation doesn't work properly either.
@NotNullannotations are missing onnullable=falseannotations, etc.Also after generating the code it is no longer clear which combination of flags resulted in the current code. So as a developer I would have to write different validation and mapping logic depending on required/nullable attributes, instead of coupling my mapping logic to the present types directly, which would be way more straight forward.
I see that optimizing away the one case
required=false & nullable=falsewhere theoreticallyJsonNullablecould be determined by if the value isnullor not might be an idea. But this kinda doesn't work with real life scenarios, where only because the openapi-spec tells it this way, clients of the API wouldn't sentnullalthough it is definednullable=false.So as a developer one must still be able to determine, if a client did send
nullfor anullable=false & required=falseproperty to throw proper errors. This is currently not possible and the source of why we started to discuss this topic.For better understanding, It would be more verbose to couple
JsonNullableto therequiredattribute, and@NotNullto thenullableattribute.welshm commentedon Feb 22, 2023
openApiNullableis respected - it's used in both nullableDataType as well as pojo - and likely should be used in beanValidation as well.I think if the
@NotNullannotations are missing or incorrect, that is likely a separate issue that should also be resolved. I would also argue that beanValidation should be updated to account for nullability, since you cannot mark a field as@NotNullif isrequiredandnullable(since it may receive a value ofnull).I think that is likely a matter of perspective - but I agree it could definitely be more clear.
That's more of a discussion on whether the generated code should be done to allow determining violations of the API contract (explicitly sending a
nullwhen it's notnullableand notrequired) or whether the generated code should enforce API conformance (if you do sendnull, the value is ignored because it's not a valid value in the contract). Are you able to determine the error ifnullable=false & required=truecurrently? Since that would also be a violation to send an explicitnull.In my opinion,
JsonNullableand@NotNullare both connected to the relationship betweenrequiredandnullableand not connected to just one of the properties, but always both.One way to resolve this would be to introduce a flag in the generator that could produce
JsonNullablein the pattern you desire - and then the user of the generator can decide what pattern they prefer. This would have the added benefit of also being backwards compatible for users of the generator.generateJsonNullableForAllNonRequiredFields- what do you think?daberni commentedon Feb 23, 2023
Usage of
openApiNullableis absolutely fine, and is set totrueby default anyway.The issue is, that
@NotNulis bound torequired, andJsonNullableis bound tonullableonly. This is not implemented as highlighted previously ("not required and nullable"). So these two topics would need to be addressed anyway. These changes would also be backwards incompatible, as maybe many developers now already rely on the unintuitive implementation or adopted their specifications in a way to meet the desired result (as we did so far).Regarding validation, because it is implemented incomplete right now it is not possible to validate correctly at the moment.
Having a property which is
nullable = falseandrequired = false(e.g. a PATCH request for non-nullable property), a client can sendnullfor this without any issues. In the backend, one would have to assume that the property might not be passed at all, because there is no differentiation possible because of missingJsonNullable, and also javax bean validation doesn't work because of missing@NotNullannotation.I don't see why
JsonNullableand@NotNullwould require do be connected to bothrequiredandnullableat the same time, just for the sake of optimizing one case whereJsonNullablemay be not absolutely necessary. But I get the idea behind this.The PR was just to highlight a radical change on how I would see the correct implementation of
requiredandnullable. It's nothing which would ever could be merged that way because it would break every existing code generation. Some configuration for a backwards compatible change is definitely necessary.The question is, how do we want to specify the behaviour.
JsonNullableand just stumbled onto it when debugging it. The current beanValidation.mustache doesn't work right now for some cases. I would prefer to bind this only to thenullableproperty, because I don't see why the simple validation of nullability should be bound to theJsonNullabletype. Even in the desired behaviour described above, this should not be necessary.This would be independent from the
openapiNullableconfig but would also need some backwards compatible migration I guess (extenduseBeanValidationoption)Should the existing
JsonNullableusage be fixed in a way to represent the desired behaviour above? Because currentlyJsonNullableis only bound tonullable. Then a combination would be necessary with fixes to nullableDataType.mustache and pojo.mustacheShould there be the option to configure the generator to use a more explicit and verbose version, where
nullableandrequireddo not influence each other and have their well defined associations to@NotNullandJsonNullable.I would definitely vote for 3) from our side (obviously :D) because 1) and 2) wouldn't matter in that case. But I would also see a clear definition and implementation for 1) and 2).
Maybe utilizing the existing
openapiNullableoption would be better, because all the rest is depending on it anyway.Extending it with custom values instead of
true/falsewould imho work best.So keeping
openapiNullablewithtrue/falsefor backwards compatibility but adding new values like:true(deprecated)false(deprecated)none(=false)combined(=true, default) = required & nullable will be respectedrequiredOnlyDjerem- commentedon Mar 19, 2023
@borsch Am I correct that the behavior you describe, if validation is also considered, should be:
We can accept omission as a null value and consider it to be always provided.
-> No use of
JsonNullableand no validationThe absence of a value can be considered equivalent to a provided null value.
-> No use of
JsonNullablebut use of@NotNullfor validation.We need to know if a value is provided (e.g. for patch) but we can accept a null value.
-> Use
JsonNullablebut no validationWe need to know if a value is provided (e.g. for patch) and it cannot be a null value.
-> Use
JsonNullableand use of a @NotNullIfPresent** annotation** I do not know the validation behavior of
JsonNullablebut, in this case, we want it to be valid on:isPresent() == false || get() != nullddnyer commentedon Mar 23, 2023
@Djerem- To perform correctly all validations you need to use
JsonNullablefor required fields as well. Else you can not detect when a required field is missing. Consider that a missing required field is equivalent to this field being null is not correct. But for those required fields, the getter/setter can use the raw type and hide theJsonNullableto the user, it's only needed for bean validation and does not need to be exposed.We need to validate that the field is present but the developers should directly use the raw type
-> Use
JsonNullableto store the property, use the raw type on getter/setter and use a@Presentannotation on the property (not on the getter) for validationWe need to validate that the field is present but the developers should directly use the raw type
-> Use
JsonNullableto store the property, use the raw type on getter/setter, use a@Presentannotation on the property (not on the getter) and a@NotNullon the getter for validationObviously the
@Presentannotation checks that theJsonNullablehas a value (null or not).That said for retrocompatibility this strict validation for required fields should probably be optional with a parameter to enable it.
MelleD commentedon May 30, 2023
From my point of view, you/we should basically think again about the
JsonNullable.In my use cases it would make sense to return
Optionaleverywhere except for the PATCH endpoints and I think that's exactly what the JsonNullable is for. IMHO the TriState only makes sense for PATCH otherwise it's not needed.See https://github.com/OpenAPITools/jackson-databind-nullable.
"typical usage is when implementing Json Merge Patch where an explicit "null"has the meaning "set this field to null / remove this field" whereas a non-present field has the meaning "don't change the value of this field"."
Currently i habe no other good RESTful usecase for
JsonNullablewelshm commentedon May 30, 2023
I think if it's valid for PATCH it's valid for POST as well. Some projects just use POST instead of PATCH - even it it's not "correct"
daberni commentedon May 30, 2023
I absolutely agree that it is primarily relevant in a PATCH request where one can define, it is important to know if the value was passed or not.
But you can't decide on this based on the HTTP method but you have to define something different for that, and for me this is the
requiredattribute of the properties (or the required-list).If it is "not required" this implies that it is "optional". And in an optional manner I must be able to check if it was present or not.
If it is "not optional", it would be okay to me that the Spring implementation then uses the default value of the property if it is not present. And then an additional validation like "not null"/"nullable" would kick in. But this way you could clearly differentiate between these two configurations
daberni commentedon May 30, 2023
As a sidenote: we have already adopted the mustache templates in this manner and are very happy with this approach. It would be interesting if someone else would have different requirements to this. It would be nice if we wouldn't have to maintain these templates again all the time (reintegrate with upstream changes) and in my opinion others may would benefit from this approach too.
I think the main aspect would be, when one doesn't define the "required-list" completely, every property would be JsonNullable and break a lot of stuff immediatelly. It is a bit cumbersome that everything has to be specified again in the required list, but imho that's the more correct way anyway. I don't know if there would be any simpler solution to this.
MelleD commentedon May 31, 2023
Yeah you are right, that why I said in good RESTful Api(s) ;)
@daberni I think you need the nullable + required field, if you would like to have a general solution for every operation. If you say it's only for PATCH (maybe POST) then you have other solutions.
See discussion here @welshm have a good conclusion
How I said in our use cases, I would like to have everywhere
Optionaland forPATCHJsonNullable. There you could decide if you like to use required or nullable.22 remaining items
gnuemacscoin commentedon Nov 26, 2023
So I made an attempt at implementing
except I named it
OptionalProperty, you may find it at https://github.com/gnuemacscoin/jackson-databind-optional-propertyrobertop87 commentedon Feb 15, 2024
Just a small question, I could not get the JsonNullable generated for a simple project. I just created a sample repository to show the issue.
https://github.com/robertop87/opengen
Basically the yaml definition has a non required 'tag' property defined like this:
But the generated java code is:
private String tag;And expected is:
private JsonNullable<String> tag = JsonNullable.undefined();am I doing something wrong?
tofi86 commentedon Feb 15, 2024
@robertop87 I think that's not related to this issue here. You also opened an issue and it should be handled there...
tofi86 commentedon Feb 15, 2024
While I'm here, I'd like to get back to the actual discussion after it drifted off a bit recently... Let me jump back a year as I want to focus on a bug which has been mentioned, but never resolved...
On Feb 20 2023 @welshm and @borsch enlightend us about the different scenarios for JsonNullable which I absolutely agree with.
@welshm even mentioned
@daberni replied, that...
and @welshm replied:
and @daberni replied:
Then discussion drifted off...
Long story short: I think @daberni is still right with his statement - even with version 7.3.0 this is not generated as @welshm stated and it is still based exclusively(!) on the nullable property.
This is my example which I just ran with v7.3.0:
Config:
Schema:
which results in the following Java code:
For
nullableTrueRequiredTrueExpectStringas tri-state JsonNullable is generated but technically isn't needed!So it looks like v7.3.0 does not adhere to the description of JsonNullable generation @welshm and @borsch gave a year ago.
Does anyone have a mustache workaround for this? Or does this need a proper bugfix in the code generator?
Addendum:
Since v7.2.0 i guess
useOptional: truealso has an effect on the models:but this doesn't solve the above issue and doesn't make things better in my eyes...
It's just making your models worse if you previously used
useOptional: truefor your controller methods...MelleD commentedon Feb 16, 2024
A technically correct answer (there are also other opinions) has been given a long time ago.
The question, however, is what is your need? What is your use case? What does it mean semantically? So far no one has been able to describe a use case for this case.
What does it mean if field has to be in the payload but can be null. What is the semantic difference between
nullin the payload and the attribute does not exist?And yes off course you can customize and override the existing template:
https://openapi-generator.tech/docs/templating/
here is the template:
https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/JavaSpring/nullableDataType.mustache
By the way, I think that not only JsonNullable is a problem but also beanvalidation because it sets a @NotNull for required fields
jspetrak commentedon Feb 16, 2024
I can say that openapi beginners have quite a hard time to understand the correct semantics of required and nullable. And, based on actual generator implementations, tend to bend the actual api definitions to product the source code they desire.
This would be usable for partial patch. Attribute missing means "do not touch the current value and I am not stating what the current value is". For POST, PUT, I would expect a default value so there can be clearing substitute for property not available in the payload.
MelleD commentedon Feb 16, 2024
Correct thats the reason why there is the JsonNullable. If you don't want to use a Container class which handles this then you can disable it. And now you have arguments why it is like it is currently ;) and not to change it. You can do it right now your case no change necessary
But there is in open api no semantic for that.
That why I use different DTO for POST and PATCH
POST without json nullable and PATCH for JSON Merge PATCH with JsonNullable. But also currently complete possible without changes. Thats why I ask, for case 1
required true and nullable trueI know no use case.That's true but another issue ;)
jgosmann commentedon Feb 19, 2024
@MelleD
Our use case would be to generate consistent types for our TypeScript client and Java/Spring backend and ensure that certain parameters must be passed. In TypeScript/JavaScript the distinction of nullable and required is represented with
undefinedandnullable. In particular, a required, but nullable field will allow the assignment ofnull, but not ofundefined. In TypeScript this enforces that the field must be set either to a value or explicitlynull. This can be quite useful to prevent that a developer forgets to set a parameter when making a request with the client.While the TypeScript types are generated in exactly the way I expect, the Java/Spring types are actually generated in an incompatible way and just seem plainly wrong to me, no matter if there is a use case or not (which there is as described above). In fact, it is not even working properly. When I send
nullfor a nullable required property in the JSON request body (the Java type beingJsonNullable), the endpoint will return a 400/bad request because the validation of the request body fails; complaining that the property must not be null (though, I'm not quite sure why because it deserializes fine). Bottom line, we would like to use nullable required properties, but we cannot because it breaks the handling in the Java code, effectively making client and server incompatible.jgosmann commentedon Feb 19, 2024
The problem I'm describing might be in part due to #11969, but even when I set
openApiNullabletofalse(so that noJsonNullabletype is used), the validation fails when sending annullfor a nullable required field.Edit: Ah well, it has been mentioned before:
MelleD commentedon Feb 19, 2024
But you're talking about symptoms with different technologies and maybe problems there. I'am talking more about good API design and if the request really make sense.
From a purely technical perspective, I don't understand what the difference is between setting a field in the JSON to
nullor simply leaving it out.What's the difference for you? Why is the request valid if you put
nullin it and invalid if the field is missing?What use is this information and distinction to the backend? I think this is a simple question :)
I've never had to distinguish between them unless you use JSON Merge Patch.
This is the only reason why JsonNullable exists, when you really need a tri state.
https://github.com/OpenAPITools/jackson-databind-nullable
What is stopping you?
jspetrak commentedon Feb 19, 2024
@MelleD How do you apply default value other then omitting the property and having the default used? Passing property: null means "the value is null" not "the value is default". This is other use case than merge patch. And please, don't tell me that properties with default cannot be null.
MelleD commentedon Feb 19, 2024
I'm not saying anything, I haven't had the case yet. Of course we can now conjure up a case artificially. But no one was able to describe a real use case.
There is no question that there is a lot that can be done technically. But no one can describe a single use case to me without getting technical.
Just to make it clear, this doesn't concern me at all, I'm just interested in how you design APIs and why.
Even if the case is really "somehow" fixed, it won't affect me because, as I said, I've never designed an API like this before and no one can describe it.
But anyway see technical no issue here and also no need for a required attribute
@jspetrak solved or not?
dcebotarenco commentedon Aug 23, 2024
Hey curious of any progress on the issue?
example:
I spotted that if I have a PUT request with a
requiredfield that that hasnullvalue then the@NotNullkicks in.Read all the issues threads around.
requiredso the@NotNullis removed (kinda weird going against the json schema)requiredand implement something like [BUG][SPRING] Using useBeanValidation together with openApiNullable creates model classes that validate null values incorrectly #11969 (comment) , satisfy the meaning ofrequired, but then i'll have to maintain my templates, and always make sure on the next upgrade I have a compatible mustache templateThanks
daberni commentedon May 31, 2026
Coming back to this after a while to see if we can find something that works for everyone here.
First, a quick status check, since it's been a couple of years: the behavior is unchanged on current master (checked today). The two couplings are exactly as originally reported:
JavaSpring/nullableDataType.mustachekeysJsonNullable<>purely onisNullable—requiredis never consulted.JavaSpring/beanValidation.mustacheemits@NotNullpurely onrequired—isNullableis never consulted.So
required: true, nullable: truestill generates@NotNull JsonNullable<T>: it doesn't need the tri-state, and the@NotNullrejects the explicitnullthat the schema says is legal — that's the 400 @jgosmann and @dcebotarenco ran into.I want to deliberately untangle two things that kept getting argued as one:
1. The
@NotNull+nullablebug. Independent of any JsonNullable philosophy:@NotNullshouldn't be emitted for anullable: truefield, becausenullis an explicitly permitted value there. I think everyone in this thread already agrees this part is simply a bug (@NotNull⇒required && !nullable).2. The JsonNullable selection policy. This is where the genuine disagreement is, and I no longer think there's a single correct answer — there are (at least) two legitimate ones:
JsonNullableis a tri-state and is only semantically necessary forrequired:false, nullable:true. Everywhere else, a plain type (orOptional) suffices. This is the minimal-surprise reading of the spec and I fully agree it's correct as a reading of the spec.nullable— not because the spec forces it, but because uniformity is the entire point downstream (MapStruct, below).I'm explicitly not asking to change the default, and not asking anyone to accept that one reading beats the other. They serve different downstream styles. So the resolution that costs no one anything is the one @welshm already proposed in this very thread:
That's exactly it. Concretely, I'd let
openApiNullableaccept a string value alongside the existingtrue/false(which remain the default and keep working byte-for-byte):openApiNullableJsonNullable<T>used whenfalsetrue(default)nullableoptional(new)!required(every optional field)In the new mode only,
@NotNullbecomesrequired && !nullable, fixing problem (1) without touching legacy output. (A fourthstrictvalue —JsonNullableonly for!required && nullable, i.e. exactly @borsch's minimal set — could be added the same way if anyone wants it; I'd keep the first PR to a single new value to stay simple.)The concrete use case @MelleD rightly kept asking for:
We map PATCH/PUT DTOs onto JPA entities with MapStruct. When every optional field is
JsonNullable<T>, the mapping is uniform and fully declarative:JsonNullable.undefined()→ property skipped via@ConditiononisPresent(); entity untouchednull→ entity field set tonullOne
@Condition+ unwrap pair covers the whole model — no per-field branching on whether a field happened to be declarednullable. That uniformity is the only value, and it exists only if all optional fields share the wrapper. This is precisely why the minimal!required && nullableset is right for others but doesn't work for us — and why this belongs behind an opt-in flag, not in the default.If there's appetite, I'll rebase #14766 down to just this: one new
openApiNullablemode + the@NotNull/nullablefix scoped to that mode, with samples, so nothing changes for anyone who doesn't set it.lorenzolazzarato commentedon Jun 17, 2026
@daberni
I found this tread in the last week after stumbling in the bug @dcebotarenco mentioned and I started following the whole discussion, since I'm trying to use JsonNullable in an application I'm working on and basically encountered all the problems mentioned here.
I agree that the solution to point 1 is what you propose: if a field is marked both
requiredandnullable, it can not contain the annotation@NotNull, since it would violate the nullable clause.As of point 2 and the main discussion of the thread, I think both proposed behaviours have their merit and I don't think there's an inherently correct one. I'd also add @borsch proposed solution to the configuration though.