FastAPI uses ENCODERS_BY_TYPE (from pydantic.json) to encode some basic data type.

ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
    bytes: lambda o: o.decode(),
    Color: str,
    datetime.date: isoformat,
    datetime.datetime: isoformat,
    datetime.time: isoformat,
    datetime.timedelta: lambda td: td.total_seconds(),
    Decimal: decimal_encoder,
    Enum: lambda o: o.value,

so for me to override the default datetime encode, just like

 ENCODERS_BY_TYPE[datetime] = lambda date_obj: date_obj.strftime("%Y-%m-%d %H:%M:%S")
Answer from coder vx on Stack Overflow
🌐
GitHub
github.com › fastapi › fastapi › pull › 5718
♻️ Refactor `jsonable_encoder` to optimize subclass encoder resolution using MRO by ramnes · Pull Request #5718 · fastapi/fastapi
The current implementation doesn't handle subclass instances when fastapi.encoders.ENCODERS_BY_TYPE is modified after fastapi.encoders import. For example, in this example we could expect the /...
Author   fastapi
Discussions

fastapi - reportMissingImports Python error but import works fine - Stack Overflow
When I install package with python and import it, I often get a missing imports message such as: Import "fastapi" could not be resolvedPylancereportMissingImports The imports always work More on stackoverflow.com
🌐 stackoverflow.com
Cannot import ENCODERS_BY_TYPE
Initial Checks I confirm that I'm using Pydantic V2 Description I am migrating my code from V1 to V2. In my V1 code, I modified ENCODERS_BY_TYPE to turn bson ObjectIds. I can no longer import E... More on github.com
🌐 github.com
8
December 22, 2023
python - ImportError: cannot import name 'FastAPI' from partially initialized module 'fastapi' : circular import - Stack Overflow
My initial project setup was working fine but, after installing psutil, I started getting a circular import error for fastApi. I tried uninstalling psutil but, the error persists. File ".\proj... More on stackoverflow.com
🌐 stackoverflow.com
FastAPI ignores json_encoders in the Model
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 integ... More on github.com
🌐 github.com
15
September 25, 2020
🌐
GitHub
github.com › fastapi › fastapi › issues › 714
jsonable_encoder does not use custom_encoder if Config.json_encoders is not defined. · Issue #714 · fastapi/fastapi
November 19, 2019 - from datetime import datetime import factory import faker.utils.datetime_safe from fastapi.encoders import jsonable_encoder from pydantic import BaseModel class MyModel(BaseModel): dt_field: datetime class MyModelFactory(factory.Factory): dt_field = factory.Faker("date_time") # should return a datetime class Meta: model = MyModel inst = MyModelFactory.build() assert isinstance(inst, MyModel) assert isinstance(inst.dt_field, faker.utils.datetime_safe.datetime) assert isinstance(inst.dt_field, datetime) inst_encoded = jsonable_encoder(inst) assert isinstance(inst_encoded["dt_field"], dict) assert inst_encoded["dt_field"] != inst.dt_field.isoformat() inst_encoded = jsonable_encoder( inst, custom_encoder={faker.utils.datetime_safe.datetime: lambda o: o.isoformat()} ) assert isinstance(inst_encoded["dt_field"], str) assert inst_encoded["dt_field"] == inst.dt_field.isoformat()
Author   fastapi
🌐
Sling Academy
slingacademy.com › article › resolving-fastapi-error-could-not-import-module-api
Resolving FastAPI Error: ‘Could not import module ‘api” - Sling Academy
This results in an error because neither module can be fully imported without the other. Identifying and restructuring the code to remove circular dependencies can resolve the error. Review your api module and any other modules it imports to identify circular references.
🌐
GitHub
github.com › pydantic › pydantic › issues › 8426
Cannot import ENCODERS_BY_TYPE · Issue #8426 · pydantic/pydantic
December 22, 2023 - Initial Checks I confirm that I'm using Pydantic V2 Description I am migrating my code from V1 to V2. In my V1 code, I modified ENCODERS_BY_TYPE to turn bson ObjectIds. I can no longer import E...
Author   pydantic
Find elsewhere
🌐
GitHub
github.com › zed-industries › zed › discussions › 32362
Python imports don't work in virtual enviroments · zed-industries/zed · Discussion #32362
I am working on a project in a venv, and am importing fastapi. In VSCode, everything works fine, but in Zed I was getting the error Import "fastapi" could not be resolved (Pyright reportMissingImports). I Googled it, and found that I needed to configure Pyright settings.
Author   zed-industries
🌐
GitHub
github.com › fastapi › fastapi › issues › 2091
FastAPI ignores json_encoders in the Model · Issue #2091 · fastapi/fastapi
September 25, 2020 - # GOOD # '{"stuff": ["a", "d", ... calling the `sort_func` The primary issue is that when a Pydantic model defines special serialization behavior, fastapi is not obeying it....
Author   fastapi
🌐
FastAPI
fastapi.tiangolo.com › tutorial › encoder
JSON Compatible Encoder - FastAPI
So, a datetime object would have to be converted to a str containing the data in ISO format. The same way, this database wouldn't receive a Pydantic model (an object with attributes), only a dict. You can use jsonable_encoder for that. It receives an object, like a Pydantic model, and returns a JSON compatible version: ... from datetime import datetime from fastapi import FastAPI from fastapi.encoders import jsonable_encoder from pydantic import BaseModel fake_db = {} class Item(BaseModel): title: str timestamp: datetime description: str | None = None app = FastAPI() @app.put("/items/{id}") def update_item(id: str, item: Item): json_compatible_item_data = jsonable_encoder(item) fake_db[id] = json_compatible_item_data
🌐
Sentry
sentry.io › sentry answers › vs code › fix pylance resolvemissingimports in vs code
Fix Pylance resolveMissingImports in VS Code | Sentry
July 15, 2024 - If you previously installed fastapi to the virtual environment, the resolveMissingImports error should now disappear.
🌐
GitHub
github.com › fastapi › fastapi › discussions › 8947
Cannot control json serialization with custom response_class · fastapi/fastapi · Discussion #8947
serialize_response calls the default FastAPI jsonable_encoder meaning response_data has been encoded before the actual_response_class is invoked. It seems like the recommendation in this thread is to explicitly return a custom Response inside each route -- that does work, but it would be nice if we could ...
Author   fastapi
🌐
GitHub
github.com › fastapi › fastapi › discussions › 8322
Cannot specify encoding style for object and array elements · fastapi/fastapi · Discussion #8322
Describe the bug OpenAPI defines a number of encoding styles for complex types like arrays and objects, and specifically reccomends using them for things like form data encoding. While the underlying OpenAPI models for parameters appear to support this, using them does not affect the resulting OpenAPI definition. from fastapi import FastAPI, Form, Query from pydantic import BaseModel from typing import List api = FastAPI() @api.post('/list_form.json') def test_list_form( id: int = Form(...), list: List[str] = Form(..., style = 'spaceDelimited', explode=False) ): pass @api.get('/list_query.json
Author   fastapi
🌐
GitHub
github.com › fastapi › fastapi › discussions › 8942
FastAPI ignores json_encoders in the Model · fastapi/fastapi · Discussion #8942
The desired behavior is for fastapi to be consistent and obey Pydantic's conventions. I also looked at other issues that are similar, but not quite the same: json_encoders from parent class is ignored in inherited pydantic models during serialization #1722
Author   fastapi
🌐
Bobby Hadz
bobbyhadz.com › blog › python-no-module-named-fastapi
ModuleNotFoundError: No module named 'fastapi' in Python | bobbyhadz
April 10, 2024 - To solve the error, install the module by running the pip install fastapi command. Open your terminal in your project's root directory and install the fastapi module. ... Copied!# 👇️ In a virtual environment or using Python 2 pip install ...
🌐
GitHub
github.com › fastapi › fastapi › issues › 2951
Import FastAPI does not work. · Issue #2951 · fastapi/fastapi
March 14, 2021 - I already checked if it is not related to FastAPI but to Swagger UI.
Author   fastapi
🌐
GitHub
github.com › fastapi › fastapi › issues › 4281
Import Error in Main.py · Issue #4281 · fastapi/fastapi
December 15, 2021 - 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 ...
Author   fastapi