Skip to content

[BUG] Spring Boot fails to parse LocalDate query parameter #2053

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
5 of 6 tasks
macjohnny opened this issue Feb 4, 2019 · 12 comments · Fixed by #3860
Closed
5 of 6 tasks

[BUG] Spring Boot fails to parse LocalDate query parameter #2053

macjohnny opened this issue Feb 4, 2019 · 12 comments · Fixed by #3860
Milestone

Comments

@macjohnny
Copy link
Member

Bug Report Checklist

  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • What's the version of OpenAPI Generator used?
  • Have you search for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Bounty to sponsor the fix (example)
Description

When defining a query parameter of type: string and format: date

  /bla:
    get:
      parameters:
        - $ref: '#/parameters/analysisDate'
      produces:
        - application/json
      responses:
          200:
            description: 'Successful operation'

parameters:
  analysisDate:
    name: analysisDate
    in: query
    required: true
    type: string
    format: date

the server fails to parse a url like /bla?analysisDate=2017-11-30

The generated code looks like

 blaGet(@NotNull @ApiParam(value = "Analysis Date", required = true) @Valid @RequestParam(value = "analysisDate", required = true) LocalDate analysisDate) 
openapi-generator version

3.3.4

Related issues/PRs

https://blog.codecentric.de/en/2017/08/parsing-of-localdate-query-parameters-in-spring-boot/
spring-projects/spring-boot#9930

Suggest a fix

adding @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) resolves the issue:

blaGet(@NotNull @ApiParam(value = "Analysis Date", required = true) @Valid @RequestParam(value = "analysisDate", required = true) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate analysisDate)
@macjohnny
Copy link
Member Author

relevant code:

{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{^isContainer}}{{#defaultValue}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}) {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestParam(value = "{{baseName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{^isContainer}}{{#defaultValue}}, defaultValue={{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/defaultValue}}{{/isContainer}}) {{>optionalDataType}} {{paramName}}{{/isQueryParam}}

@macjohnny
Copy link
Member Author

macjohnny commented Sep 3, 2019

See also #3248

@melissapalmer
Copy link

melissapalmer commented Sep 5, 2019

See also #2053

@macjohnny which issue did you mean to link this too #2053 is this issue?

I am having the same issue that Spring server generated code is not parsing LocalDate correctly, reason I found is because the code being generated for these request parameters is as:

@ApiParam(value = "Filter on KYC applications since a date")  LocalDate filterDateFrom

where as it should (include @RequestParam)

 @RequestParam(value = "filterDateFrom", required = false) @ApiParam(value = "Filter on KYC applications since a date")  LocalDate filterDateFrom

I am using version 4.1.1 of the generator

And this seems to be caused by the change you pointed out at:
#2053 (comment)

What did you mean with these last comments you added please.

@macjohnny
Copy link
Member Author

I updated my comment to link the correct issue

@peyerroger
Copy link
Contributor

peyerroger commented Sep 8, 2019

Hi guys

Even with the RequestParam annotation spring is not able to parse date/date-time into LocalDate/OffsetDateTime.

The suggested fix of @macjohnny to add @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) is from my point of view the correct way. At the moment we add this on the implementation. But it would be nice to have it in the generated code. I will create a PR if you agree.

@macjohnny The line needs an import statement. Is it ok to add the full class name in the queryParam.mustache file to prevent unused imports if no date/datetime params are defined?

Solution:
If 'isDate' (found in CodegenParameter.java)

@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE)

If 'isDateTime' (found in CodegenParameter.java)

@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME)

@peyerroger
Copy link
Contributor

@macjohnny Had some time and created the PR right away. #3860 Could you take a look? Do you know who can add the technical committee? Could you do that?

Please note this only works correctly when issue #3248 is resolved as well.

@melissapalmer
Copy link

@peyerroger looks like there are a few people on the tech committee see here:
https://github.com/OpenAPITools/openapi-generator#62---openapi-generator-technical-committee

@macjohnny macjohnny added this to the 4.1.2 milestone Sep 9, 2019
@wing328 wing328 modified the milestones: 4.1.2, 4.1.3 Sep 11, 2019
macjohnny pushed a commit that referenced this issue Sep 11, 2019
)

Adds the format annotation so that Spring is able to serialize OpenApi date/date-time format into LocalDate/OffsetDateTime.
hokamoto pushed a commit to hokamoto/openapi-generator that referenced this issue Sep 12, 2019
…arameter (OpenAPITools#3860)

Adds the format annotation so that Spring is able to serialize OpenApi date/date-time format into LocalDate/OffsetDateTime.
wing328 pushed a commit that referenced this issue Sep 13, 2019
* First version of Nim Client

* Add some codes

* Add some codes

* Add some codes

* Add some codes

* Add some codes

* First version of Nim Client

* Add some codes

* Add some codes

* [Dart] Fix README template and update testing doco (#3809)

* [Dart] Fix README template and update testing doco

- deleted redundant shell script
- fixed and updated README template
- updated test package and moved to a dev_dependency
- removed old unused dev_dependency packages
- updated testing documentation in petstore sample

* Remove references to dart-flutter-petstore.sh

* Fix typos

* Fix typo

* Support custom git repository (#3757)

* add gitHost param to GeneratorSettings and related

* parameterize gitHost in READMEs

* parameterize gitHost in go.mod

* parameterize gitHost in git_push

* update petstore samples

* run ./bin/utils/export_docs_generators.sh

* run meta-codehen.sh

* Revert "run meta-codehen.sh"

This reverts commit d6d579f.

* Revert "run ./bin/utils/export_docs_generators.sh"

This reverts commit 1b81538.

* Revert "update petstore samples"

This reverts commit f513add.

* run ensure-up-to-date

* Add links to article and video (#3820)

* Better Go code format (#3819)

* better varible naming

* better comments

* better code format for go experimental client

* better comment, update samples

* Add some codes

* Add some codes

* Add some codes

* Add gRPC Protobuf schema generator (#3818)

* add grpc protobuf generator

* update doc

* add new doc

* add windows batch, comment out root proto

* 1792 fix remote spec handling and hash calculation (#3440)

* fixed bug where nullApi.java would be generated.  Instead, generated DefaultApi.java to match the default path /{pathParam} (#3821)

* Revert "1792 fix remote spec handling and hash calculation (#3440)"

This reverts commit 2a2eefe.

* Add  nickmeinhold to Dart technical committee (#3830)

* Bug #2845 typescript angular inheritance (#3812)

* issue #2845: enable 'supportsMultipleInheritance' on typescript angular client codegen

- note I reran ./bin/openapi3/typescript-angular-petstore-all.sh and no changes occurred.
  this suggests to me that the petstore.yaml sample should be improved to make use of the
  anyOf / allOf / oneOf keywords, in order to better show the effects of changes on generated code.

* issue #2845: run ./bin/openapi3/typescript-angular-petstore-all.sh

* run `mvn clean package && ./bin/typescript-angular-petstore-all.sh`

* revert extranous files

* fix warnings in csharp-netcore client (#3831)

* Add missing files to the form request (#3834)

* [client][go] avoid duplicated reflect imports (#3847)

* Following up for #3440 (1792 fix remote spec handling and hash calculation) (#3826)

* This patch fixes the bug that we cannot access to remote files when checking file updates.
Following up #3440, supporting auth.

* 1792 fix remote spec handling and hash calculation (#3440)

(cherry picked from commit 2a2eefe)

* fix detecting remote file / local file logic while finding the hash file, taking care of IllegalArgumentException for local files.

* add testcase

* Add a link (#3850)

* Add Element AI to the list (#3856)

* maven-plugin-plugin 3.6.0 (#3854)

*  [Java][okhttp-gson] fix failure to deserialize floats (#3846)

* fixed bug where nullApi.java would be generated.  Instead, generated DefaultApi.java to match the default path /{pathParam}

* fix to bug #3157

* update samples

* Adds Http Info To Dart Api (#3851)

* [C++][Pistache] Add missing setter for arrays (#3837)

* [C++][Pistache] Add missing setter for arrays

Fixes #3769

* [C++][Pistache] Update Petstore sample

* typescript-inversify: improve check for required parameters, support multiple media types (#3849)

* [typescript-inversify] Allow falsy parameters

A required parameter to an api method must not be `null` or `undefined`.
It can be any other falsy value, e.g. `""`, `0` or `false` though. This
change makes sure an error is only thrown in the former case and not in
the latter.

* [typescript-inversify] Handle multiple media types

The Accept and Content-Type HTTP headers can contain a list of media
types. Previously all but the first media type in the api definition
were ignored. Now the headers are properly generated.

* [typescript-inversify] Fix http client interface

The api service methods allow the `body` parameter to be optional. The
parameter is then passed to an `IHttpClient`. So it needs to be optional
there as well.
Also fixed the sample implementation `HttpClient`.

Fixes #3618.

* [typescript-inversify] Regenerate Petstore sample

* [typescript-inversify] Use more explicit null check

This does not change the semantic of the generated code, but makes it more explicit.

Co-Authored-By: Esteban Gehring <[email protected]>

* [typescript-angular] allow empty string basePath (#3489)

* [typescript-angular] Fixing #2731 - empty string basePath

* typescript-angular: refactor base path configuration

* typescript-angular: refactor base path configuration

* Fix/r/serialization fix and minor 3xx resp fix (#3817)

* fix(qlik): fix for minor serialization bug

* fix(r): add petsore generated classes

* fix(r): indendation fixes

* typescript-axios: Fix baseoptions (#3866)

* Fixed missing baseOptions of typescript-axios.

The typescript-axios template was missing the baseOptions setting when building an API Configuration. Set it.

* update sample.

* re-generate typescript axios samples

* Rename gRPC generator to "protobuf-schema" (#3864)

* rename grpc generator to protobuf-schema

* update doc

* Prepare v4.1.2 release (#3873)

* update samples

* update date

* fix version in readme

* BugFix #2053 Spring Boot fails to parse LocalDate query parameter (#3860)

Adds the format annotation so that Spring is able to serialize OpenApi date/date-time format into LocalDate/OffsetDateTime.

* update doc, samples (#3875)

* update stable release

* Update the batch for Windows

* Add a test snippet

* Update ensure-up-to-date

* Add Nim to README.md

* Ran ensure-up-to-date to pass CircleCI tests
jimschubert added a commit that referenced this issue Sep 13, 2019
* master: (22 commits)
  various minor improvements to nim generator (#3883)
  Add Nim client code generator (#3879)
  updated google-api-client version from 1.23.0 to 1.30.2.  Bugfix #3625 (#3882)
  typescript-fetch: fix missing comma in multiple imports (#3881)
  [scala][client] add Scala code generation test (#3859)
  typescript-node: Use HttpError class when rejecting promises (#3876)
  update stable release
  update doc, samples (#3875)
  BugFix #2053 Spring Boot fails to parse LocalDate query parameter (#3860)
  fix version in readme
  Prepare v4.1.2 release (#3873)
  Rename gRPC generator to "protobuf-schema" (#3864)
  typescript-axios: Fix baseoptions (#3866)
  Fix/r/serialization fix and minor 3xx resp fix (#3817)
  [typescript-angular] allow empty string basePath (#3489)
  typescript-inversify: improve check for required parameters, support multiple media types (#3849)
  [C++][Pistache] Add missing setter for arrays (#3837)
  Adds Http Info To Dart Api (#3851)
  [Java][okhttp-gson] fix failure to deserialize floats (#3846)
  maven-plugin-plugin 3.6.0 (#3854)
  ...
@baurceanu
Copy link
Contributor

4Googlers:
You can disable this OOTB validation by using custom formats for date / time.
yaml

- name: dateFrom
  in: query
  schema:
    type: string
    format: my-custom-date-format

pom.xml

<plugin>
  ...
  <executions>
    <execution>
      ...
      <configuration>
        ...
        <typeMappings>my-custom-date-format=java.time.LocalDate</typeMappings>
      </configuration>
    </execution>
  </executions>
</plugin>

@zalito12
Copy link
Contributor

zalito12 commented Jan 16, 2020

Hi! Note this is not working when you have your query parameters definied inside an object, for example:

paths:
  /elephants:
    get:
      operationId: getElephants
      parameters:
        - in: query
          name: count
          schema:
            type: integer
	- $ref: '#/components/parameters/SearchParams'
components:
  parameters:
    SearchParams:
      name: searchParams
      description: Possible search params to filter case search
      in: query
      style: form
      explode: true
      schema:
        type: object
        properties:
          prop1:
            type: integer
            example: 1
          start:
            type: string
            format: date
            example: '2019-12-31'
          end:
            type: string
            format: date
            example: '2019-12-31'

If I'm correct the @DateTimeFormat annotation also works in class fields. Has anyone faced this problem too?

@prateek2007
Copy link

in case of "dateLibrary": "java8", DateFormatter is =DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
which accepts date of format 12/6/19

@qbixsd
Copy link

qbixsd commented Feb 20, 2020

in case of "dateLibrary": "java8", DateFormatter is =DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
which accepts date of format 12/6/19

according to documentation, string with date format should be formatted with ISO format (yyyy-MM-dd): https://swagger.io/docs/specification/data-models/data-types/
So this default approach is in contradiction to openapi specification.

Also, is there a way to override this setting?

@fditolla
Copy link

fditolla commented May 6, 2021

In my case in the implemntation method I added @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) to the field and it seems to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

9 participants