1
votes
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

1
@MrFuppes Yeah, I tried that too without a luck - Pei
You query parameter looks like this ?start_time=2021-01-19%2016%3A00%3A00%2B05%3A00 ? - alex_noname
@alex_noname No, what's that? - Pei
start_time is a query parameter in your case. How do you send it? - alex_noname
Could it be that you are forgetting the T of timezone in the datetime? Have you tried with 2021-01-19T16:00:00+05:00 ? - lsabi

1 Answers

2
votes

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.