Tag-ids 404 error

Hi I’m new to API and maybe this question has been made 1000 times…
I’m developing a python routine to query all contacts with some detail infos. I’m using PAT for I don’t need great performances.
Now, I’ve read 100 times that tag_ids are to be queried one contact at time, I’m doing this but I keep receiving a 404 error even if contacts do have Tags.
Please help
My code is below:
Could it be a problem with the endpoint I’m using?

import requests
import csv
import os

Configuration of the Personal Access Token

PERSONAL_ACCESS_TOKEN = ‘MY_PERSONAL_ACCESS_TOKEN’

Base URL for the Keap REST API

BASE_URL = ‘https://api.infusionsoft.com/crm/rest/v2

Function to get all contacts without pagination

def get_all_contacts():
url = f"{BASE_URL}/contacts"
headers = {
‘Authorization’: f’Bearer {PERSONAL_ACCESS_TOKEN}',
‘Content-Type’: ‘application/json’
}

params = {
    'limit': 1000,  # Fetch a large number of contacts in one call; adjust if necessary
    'optional_properties': 'email_addresses, given_name, family_name'
}

print("Requesting all contacts in one call...")  # Debug point
response = requests.get(url, headers=headers, params=params)

if response.status_code == 200:
    data = response.json()
    contacts = data.get('contacts', [])
    print(f"Retrieved {len(contacts)} contacts.")  # Debug point
    
    # Print the IDs of the contacts received
    for contact in contacts:
        print(f"Received Contact ID: {contact.get('id')}")  # Debug point for individual contact IDs
    
    return contacts
else:
    print(f"Error retrieving contacts: {response.status_code} - {response.text}")
    return []

Function to retrieve tag IDs for a specific contact

def get_contact_tag_ids(contact_id):
url = f"{BASE_URL}/contacts/{contact_id}/tag_ids" # Correct endpoint for fetching tag IDs for a contact
headers = {
‘Authorization’: f’Bearer {PERSONAL_ACCESS_TOKEN}',
‘Content-Type’: ‘application/json’
}

print(f"Requesting tag IDs for contact {contact_id}...")  # Debug point
response = requests.get(url, headers=headers)

if response.status_code == 200:
    try:
        data = response.json()  # Ensure the response is in JSON format
        # Extract tag IDs from the response
        tag_ids = data.get('tagIds', [])  # Adjust key as per API response
        print(f"Retrieved tag IDs for contact {contact_id}: {tag_ids}")  # Debug point
        return tag_ids
    except ValueError:
        print(f"Error parsing JSON response for tag IDs of contact {contact_id}.")
        return []
else:
    print(f"Error retrieving tag IDs for contact {contact_id}: {response.status_code} - {response.text}")  # Debug point
    # Additional error detail
    print(f"Full response: {response.text}")
    return []

Function to save contact details to a CSV file

def save_contact_to_csv(contact):
file_name = ‘contacts_with_tag_ids.csv’
write_header = not os.path.isfile(file_name) or os.stat(file_name).st_size == 0

with open(file_name, mode='a', newline='', encoding='utf-8') as file:
    writer = csv.DictWriter(file, fieldnames=contact.keys())

    if write_header:
        writer.writeheader()  # Write the header row if needed

    writer.writerow(contact)  # Write the contact details
    print(f"Saved contact {contact['Contact ID']} to CSV.")  # Debug point

Main function to retrieve and save contacts with their tag IDs

def main():
print(“Starting to retrieve contacts…”) # Debug point
contacts = get_all_contacts()

for contact in contacts:
    contact_id = contact.get('id')
    given_name = contact.get('given_name', '')
    family_name = contact.get('family_name', '')
    emails = [email.get('email') for email in contact.get('email_addresses', [])]

    # Retrieve tag IDs specifically for the contact
    tag_ids = get_contact_tag_ids(contact_id)

    # Prepare contact details
    contact_details = {
        'Contact ID': contact_id,
        'Name': f"{given_name} {family_name}",
        'Emails': ', '.join(emails),  # Join multiple emails with commas
        'Tag IDs': ', '.join(map(str, tag_ids))  # Join tag IDs with commas for CSV
    }

    # Save the contact details to a CSV file
    save_contact_to_csv(contact_details)

    # Print the contact details for debugging
    print(contact_details)  # Debug point

Run the main function

if name == “main”:
main()

Welcome @Redazione_Figurella,

When you query the REST V2 API Contacts Endpoint, the Tag ID numbers are provided in the response as shown in the documentation below and attached picture.

https://developer.infusionsoft.com/docs/restv2/#tag/Contact/operation/listContactsUsingGET_1

There is no “/tag_ids” endpoint, hence why you are getting the 404 Error.

The REST V1 API requires using the “/tags” endpoint, as the Contact results do not supply the Tag ID numbers.

Hope that helps.