5
from fastapi import FastAPI
from datetime import datetime
from ..models import Contact
from ..database import Database


app = FastAPI()

# Dependency
def get_db():
    db = Database()
    try:
        yield db
    finally:
        db.disconnect()

@app.get("/contacts/", response_model=List[Contact])
async def get_contacts(address: int, start_time: datetime, end_time: datetime, duration: int, distance: int, db: Database = Depends(get_db)):
    contacts = detect_contacts(db, address, start_time, end_time, duration, distance)
    return contacts

I'm trying to get query parameters start_time and end_time as datetime values with timezone, based on ISO 8601 or RFC 3339. It works fine without timezone, for example, "2021-01-19 16:00:00" or "2021-01-19T16:00:00", but not with timezone, for example, "2021-01-19 16:00:00+05:00" or "2021-01-19T16:00:00+05:00", returning such error:

{
    "detail": [
        {
            "loc": [
                "query",
                "start_time"
            ],
            "msg": "invalid datetime format",
            "type": "value_error.datetime"
        }
    ]
}

FYI, it's explicitly mentioned in the documentation that it supports ISO 8601 format for datetime.datetime type:

Extra Data Type - FastAPI

Pei
  • 11,452
  • 5
  • 41
  • 45

1 Answers1

2

Seeing the comments above it looks like alex_noname might have gotten to the heart of the issue. He has shown how the ISO string should be encoded to be safely sent within a query parameter.

The + sign used for the timezone is a reserved character that should be encoded in a url, otherwise it might be interpreted in another way, often as a space: e.g. if you google "datetime not working" the url of the result will look like google.com/search?q=datetime+not+working.

This is likely what is causing issues with the timezone. You can try to print to the terminal the parameter to check if it's decoded properly, you might see a space in place of the plus sign.

Sushi2all
  • 475
  • 5
  • 11