CodexBloom - Programming Q&A Platform

How to implement guide with fastapi and dependency injection causing type mismatch in response models in python 3.10

👀 Views: 84 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-22
fastapi pydantic dependency-injection Python

I recently switched to I'm experimenting with I'm working with a frustrating scenario with FastAPI when trying to use dependency injection for a service that returns a data model... I have a service that fetches user data from a database and returns an instance of a Pydantic model. However, I'm working with a `ValueError` indicating a type mismatch when FastAPI tries to serialize the response. The behavior message states: `ValueError: invalid literal for int() with base 10: 'None'`. My code looks like this: ```python from fastapi import FastAPI, Depends from pydantic import BaseModel from typing import Optional app = FastAPI() class UserModel(BaseModel): id: int name: str age: Optional[int] class UserService: def get_user(self, user_id: int) -> UserModel: # Simulated database fetch if user_id == 1: return UserModel(id=1, name='Alice', age=30) else: return UserModel(id=user_id, name='Unknown', age=None) # This line causes issues user_service = UserService() @app.get('/users/{user_id}', response_model=UserModel) async def get_user(user_id: int, service: UserService = Depends(lambda: user_service)): return service.get_user(user_id) ``` The question seems to be that when I return `UserModel(id=user_id, name='Unknown', age=None)`, FastAPI expects `age` to be of type `int`, but it's receiving `None`, which causes the serialization to unexpected result. I've tried changing the Pydantic model to make `age` default to `0` instead of `None`, but that doesn't seem to reflect the actual absence of an age, which I want to represent with `None`. I've also considered implementing a custom validator in Pydantic, but I'm unsure how to proceed. Any advice on how to resolve this would be greatly appreciated! I'd love to hear your thoughts on this. I'm using Python 3.9 in this project. What's the correct way to implement this?