Can anyone let me know, how come below pydantic model code works without instantiating UserIn and UserOut class object? Is this something handled internally by pydantic library?
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
app = FastAPI()
class UserIn(BaseModel):
username: str
password: str
email: EmailStr
full_name: Optional[str] = None
class UserOut(BaseModel):
username: str
email: EmailStr
full_name: Optional[str] = None
class UserInDB(BaseModel):
username: str
hashed_password: str
email: EmailStr
full_name: Optional[str] = None
def fake_password_hasher(raw_password: str):
return "supersecret" + raw_password
def fake_save_user(user_in: UserIn):
hashed_password = fake_password_hasher(user_in.password)
user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
print("User saved! ..not really")
return user_in_db
@app.post("/user/", response_model=UserOut)
async def create_user(user_in: UserIn):
user_saved = fake_save_user(user_in)
print(user_saved.__dict__)
return user_saved
You don't need to instantiate the objects in your code because FastAPI creates them automatically for pydantic schemas in both cases.
For arguments to endpoint methods that are Pydantic models like the user_in: UserIn in your example, it's interpreted as a Request Body, as explained in the docs here. It's worth noting the explanation about how the input data binding works for the endpoint parameters in FastAPI documentation:
- If the parameter is also declared in the path, it will be used as a path parameter.
- If the parameter is of a singular type (like int, float, str, bool, etc) it will be interpreted as a query parameter.
- If the parameter is declared to be of the type of a Pydantic model, it will be interpreted as a request body.
For the endpoint output, when you define the response_model, it will also convert it, as explained in the documentation here:
FastAPI will use this response_model to:
- Convert the output data to its type declaration.
- Validate the data.
- Add a JSON Schema for the response, in the OpenAPI path operation.
- Will be used by the automatic documentation systems.