Now that we’ve successfully added a phone_number column to our users table using Alembic, it’s time to enhance our FastAPI application to support this new field.
We’ll implement two main features:
Register a new user with a phone number.
Update an existing user’s phone number via an API endpoint.
⚡ Step 1: Add Phone Number to User Registration
Open the
routers/auth.pyrouter, where user registration occurs.Locate your
CreateUserRequestPydantic model. It currently has:
class CreateUserRequest(BaseModel):
email: str
username: str
first_name: str
last_name: str
password: str
role: strAdd the phone_number field:
class CreateUserRequest(BaseModel):
email: str
username: str
first_name: str
last_name: str
password: str
role: str
phone_number: str # New field addedScroll to where you instantiate the Users model in your registration function and include the phone number:
@router.post("/", status_code=status.HTTP_201_CREATED)
async def create_user(
create_user_request: CreateUserRequest,
db: db_dependency
):
# Create a new user model
create_user_model = Users(
email=create_user_request.email,
username=create_user_request.username,
first_name=create_user_request.first_name,
last_name=create_user_request.last_name,
role=create_user_request.role,
hashed_password=bcrypt_context.hash(create_user_request.password),
is_active=True
phone_number=create_user_request.phone_number
)
# Save to database
db.add(create_user_model)
db.commit()Restart your application:
uvicorn main:app --reloadOpen your browser and test the user registration endpoint. You should now see a phone number field when creating a new user.
⚡ Step 2: Add Change Phone Number Endpoint
Open
routes/users.pywhere user-related routes are defined.Add Pydantic model for Phone Number Update below UserVerification model
class UserVerification(BaseModel):
password: str
new_password: str = Field(min_length=6)
class PhoneNumberUpdate(BaseModel):
phone_number: strAdd a new PUT endpoint for updating a user’s phone number:
@router.put("/phone_number", status_code=status.HTTP_204_NO_CONTENT)
async def change_phone_number(
user: user_dependency,
db: db_dependency,
phone_data: PhoneNumberUpdate,
):
if user is None:
raise HTTPException(status_code=401, detail="Authentication failed")
# Fetch the user from the database
user_model = db.query(Users).filter(Users.id == user.get("id")).first()
# Update phone number
user_model.phone_number = phone_number
db.add(user_model)
db.commit()Save the file and restart the server:
uvicorn main:app --reload⚡ Step 3: Test the Change Phone Number Endpoint
Sign in with an existing user or create one.
Use the Change Phone Number endpoint in your API docs.
Enter a new phone number and execute the request.
✅ The user’s phone_number is now updated in the database.
Verify by fetching the user again through the Get User endpoint.