Skip to content

Conversation

@sauravyadav2000
Copy link

@sauravyadav2000 sauravyadav2000 commented Mar 3, 2025

Implemented User Update, Deletion, Matching, and Email Validation Features

Update User Details Endpoint (PUT /users/{user_id})

Approach:

  1. Implemented a PUT request to update user details.
  2. Used model_dump(exclude_unset=True) to ensure only provided fields are updated.
  3. Stored interests as JSON to maintain list format.
def update_user(user_id: int, user_update: schemas.UserUpdate, db: Session = Depends(get_db)):
    db_user = db.query(models.User).filter(models.User.id == user_id, models.User.is_deleted == False).first()
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")

    update_data = user_update.model_dump(exclude_unset=True)

    if "email" in update_data and not schemas.validate_email(update_data["email"]):
        raise HTTPException(status_code=400, detail="Invalid email format")

    if "interests" in update_data:
        update_data["interests"] = json.dumps(update_data["interests"])

    for key, value in update_data.items():
        setattr(db_user, key, value)

    db.commit()
    db.refresh(db_user)
    db_user.interests = json.loads(db_user.interests) if db_user.interests else []
    return db_user

Soft Delete User Profile Endpoint (DELETE /users/{user_id})
Approach:

  1. Instead of permanently deleting users, we set is_deleted = True to mark them as inactive.
  2. Ensured all queries exclude soft-deleted users.
def delete_user(user_id: int, db: Session = Depends(get_db)):
    db_user = db.query(models.User).filter(models.User.id == user_id).first()
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")

    db_user.is_deleted = True  # Soft delete
    db.commit()
    return {"message": "User marked as deleted (soft delete)."}

Find Matches for Users (GET /users/{user_id}/matches)
Approach:

  1. Implemented an algorithm to find matches based on shared interests.
  2. Used set intersection to check common interests.
def find_matches(user_id: int, db: Session = Depends(get_db)):
    db_user = db.query(models.User).filter(models.User.id == user_id, models.User.is_deleted == False).first()
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")

    user_interests = json.loads(db_user.interests) if db_user.interests else []
    all_users = db.query(models.User).filter(models.User.is_deleted == False, models.User.id != user_id).all()

    matches = [
        user for user in all_users
        if set(json.loads(user.interests) if user.interests else []).intersection(user_interests)
    ]

    for match in matches:
        match.interests = json.loads(match.interests) if match.interests else []

    return matches

Email Validation
Approach:

  1. Implemented email validation using Pydantic’s EmailStr.
  2. Created a helper function validate_email(email: str).
  3. Used this validation in the update_user endpoint.

Changes in schem.py

from typing import List, Optional

class UserBase(BaseModel):
    name: Optional[str] = None
    age: Optional[int] = None
    gender: Optional[str] = None
    email: Optional[EmailStr] = None  # Email validation
    city: Optional[str] = None
    interests: Optional[List[str]] = None 

def validate_email(email: str) -> bool:
    """Validate email format manually."""
    try:
        EmailStr.validate(email)
        return True
    except ValidationError:
        return False

How to Test These Features

  1. Create User
curl -X POST "http://127.0.0.1:8000/users/" \
     -H "Content-Type: application/json" \
     -d '{
          "name": "Saurav",
          "age": 24,
          "gender": "Male",
          "email": "saurav@example.com",
          "city": "Gurgaon",
          "interests": ["coding", "music"]
        }'
  1. Update a User
curl -X PUT "http://127.0.0.1:8000/users/1" \
     -H "Content-Type: application/json" \
     -d '{
          "city": "Los Angeles",
          "interests": ["gaming", "music"]
        }'
  1. Delete a User
curl -X DELETE "http://127.0.0.1:8000/users/1"
  1. Find Matches
curl -X GET "http://127.0.0.1:8000/users/1/matches"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant