I'm relatively new to Python and I'm working on a demo backend project which is a users API in with FastAPI.
My API is connected to a MongoDB database to save the data.
I'm seeing this error on postman when I try to add a new user:
This is my model class for User:
from typing import Optional
from pydantic import BaseModel
class User(BaseModel):
id: Optional[str] # Optional and str for mongo
username: str
email: str
And this is the logic in my endpoint to create the new User:
@router.post("/", response_model=User, status_code=status.HTTP_201_CREATED) # status_code = default code if OK
async def create_user(new_user: User):
# if user is found in the database, raise an exception
if type(search_user("email", new_user.email)) == User:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="User already exists.")
# else, create the user
new_user_dict = dict(new_user)
del new_user_dict["id"]
user_id = db_client.users.insert_one(new_user_dict).inserted_id
transformed_user = user_schema(db_client.users.find_one({"_id": user_id}))
return User(**transformed_user)
I already compared line by line the code from my tutor, and I see no differences but mine does not work... can somebody help me solve this problem? By the way... Im using Python 3.11..
Thanks, everyone for your comments, I found that the problem was being generated in an auxiliary function (search_user). I was not handling correctly, the case where the id is None like many of you mentioned here... I'm closing the question, thanks again!