question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using default for datetime query parameter without timezone leads to OpenAPI SpecValidationException

See original GitHub issue

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the “watch” button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Example

Here’s a self-contained, minimal, reproducible, example with my use case:

from datetime import datetime

from fastapi import FastAPI
import uvicorn

app = FastAPI()

start = datetime.today()


@app.get("/")
async def root(start_date: datetime = start):
    print(start_date)
    return {"start_date": start_date}

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)

Description

Run openapi-generator and see the following error:

$ openapi-generator --version
openapi-generator-cli 4.3.1
  commit : 003165c
  built  : 2020-05-06T09:38:39Z
  source : https://github.com/openapitools/openapi-generator
  docs   : https://openapi-generator.tech/

$ openapi-generator generate --input-spec http://localhost:8000/openapi.json --output api --generator-name typescript-axios
Exception in thread "main" org.openapitools.codegen.SpecValidationException: There were issues with the specification. The option can be disabled via validateSpec (Maven/Gradle) or --skip-validate-spec (CLI).
 | Error count: 1, Warning count: 0
Errors: 
	-attribute paths.'/'(get).parameters.[start_date].schemas.default=`2020-12-15T07:57:25.277303` is not of type `date-time`

	at org.openapitools.codegen.config.CodegenConfigurator.toContext(CodegenConfigurator.java:480)
	at org.openapitools.codegen.config.CodegenConfigurator.toClientOptInput(CodegenConfigurator.java:507)
	at org.openapitools.codegen.cmd.Generate.execute(Generate.java:423)
	at org.openapitools.codegen.cmd.OpenApiGeneratorCommand.run(OpenApiGeneratorCommand.java:32)
	at org.openapitools.codegen.OpenAPIGenerator.main(OpenAPIGenerator.java:61)

I would expect FastAPI to handle default datetime objects in a way that is compatible with standard OpenAPI generation tools.

Environment

  • OS: macOS 10.15.7
  • FastAPI Version: 0.62
  • Python version: 3.8.6

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:2
  • Comments:9 (9 by maintainers)

github_iconTop GitHub Comments

1reaction
johnthagencommented, Dec 15, 2020

The isoformat() returns a str so it is not needed. FastAPI converts to ISO format correctly by default. I think the issue is that if timezone information is not available, FastAPI still just serializes the datetime, but it is not a properly formed OpenAPI date-time (if missing the timezone).

A simplification of my earlier working example is:

async def root(start_date: datetime = datetime.now(timezone.utc)):
    ...

But I before closing this issue, I think a documentation note would be helpful, and perhaps maintainers of FastAPI want to decide if passing non-timezone datetimes should raise a warning or error given they don’t conform to the Spec they generate.

1reaction
johnthagencommented, Dec 15, 2020

According to the Python docs, a better way to get a timezone aware datetime is:

from datetime import datetime, timezone

from fastapi import FastAPI
import uvicorn

app = FastAPI()

start = datetime.now(timezone.utc)


@app.get("/")
async def root(start_date: datetime = start):
    print(start_date)
    return {"start_date": start_date}

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)
Read more comments on GitHub >

github_iconTop Results From Across the Web

Getting issue with date time in swagger UI
I am passing a date-time 31-05-2019 23:59:59 in query string using swagger UI but getting an exception for invalid date-time. Please see ...
Read more >
4 Datetime Data Types and Time Zone Support
The default date format for the TIMESTAMP WITH TIME ZONE data type is determined by the value of the NLS_TIMESTAMP_TZ_FORMAT initialization parameter.
Read more >
Working with Dates | Apache Solr Reference Guide 7.0
By default, all date math expressions are evaluated relative to the UTC TimeZone, but the TZ parameter can be specified to override this...
Read more >
JavaScript, Django and PostgreSQL timezone handling
js makes a GET request like this: ends_at parameter is expected to be an ISO 8601 formatted timestamp in UTC. All DjaoDjin APIs...
Read more >
Data Types for Dates, Timestamps and Intervals
If you are using Denodo 7.0u20210224 or earlier, execute CAST(CURRENT_TIMESTAMP AS TIMESTAMP WITHOUT TIME ZONE) instead. Converting a Datetime Value to Another ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found