import os
import requests
import json
import sys
def cancel_cal_appointment_by_uid(api_key, booking_uid, reason="Cancelled by user via API script"):
"""
Cancels an appointment in Cal.com by its UID.
This is a two-step process:
1. Fetch the booking by UID to get its numeric ID.
2. Cancel the booking by its numeric ID.
"""
if not api_key:
print("Error: CALCOM_API_KEY not found in environment variables.")
return False
# 1. Fetch the booking by UID to get its numeric ID
get_url = f"https://api.cal.com/v1/bookings?apiKey={api_key}&uid={booking_uid}"
booking_id = None
try:
response = requests.get(get_url)
response.raise_for_status()
# The response is a list of bookings, so we need to get the first element
bookings = response.json().get('bookings', [])
if not bookings:
print(f"Error: No booking found with UID: {booking_uid}")
return False
booking_data = bookings[0]
booking_id = booking_data.get('id')
if not booking_id:
print(f"Error: Could not find numeric 'id' for booking with UID: {booking_uid}")
return False
print(f"Found numeric ID {booking_id} for UID {booking_uid}.")
except requests.exceptions.RequestException as e:
print(f"Error fetching booking details: {e}")
return False
# 2. Cancel the booking by its numeric ID
cancel_url = f"https://api.cal.com/v1/bookings/{booking_id}?apiKey={api_key}&reason={reason}"
try:
# The API requires a DELETE request to cancel.
response = requests.delete(cancel_url)
response.raise_for_status()
print(f"Successfully cancelled appointment with ID: {booking_id} (UID: {booking_uid})")
return True
except requests.exceptions.RequestException as e:
print(f"Error cancelling appointment: {e}")
if e.response is not None:
print(f"Response status code: {e.response.status_code}")
try:
print(f"Response JSON: {e.response.json()}")
except json.JSONDecodeError:
print(f"Response text: {e.response.text}")
return False
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python3 delete_appointment.py <booking_uid>")
sys.exit(1)
calcom_api_key = os.getenv("CALCOM_API_KEY")
booking_to_delete_uid = sys.argv[1]
cancel_cal_appointment_by_uid(calcom_api_key, booking_to_delete_uid)