FastAPI - Beginner to Pro / Project 3.5 - Alembic Data Migration

Enhancing Users with Phone Numbers

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:

  1. Register a new user with a phone number.

  2. Update an existing user’s phone number via an API endpoint.


⚡ Step 1: Add Phone Number to User Registration

  1. Open the routers/auth.py router, where user registration occurs.

  2. Locate your CreateUserRequest Pydantic model. It currently has:

class CreateUserRequest(BaseModel):
    email: str
    username: str
    first_name: str
    last_name: str
    password: str
    role: str

Add 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 added

Scroll 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 --reload

Open 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

  1. Open routes/users.py where user-related routes are defined.

  2. 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: str
  1. Add 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

  1. Sign in with an existing user or create one.

  2. Use the Change Phone Number endpoint in your API docs.

  3. Enter a new phone number and execute the request.

✅ The user’s phone_number is now updated in the database.

  1. Verify by fetching the user again through the Get User endpoint.