How to retrieve leads from pipedrive, with current stage of the lead?

77 views Asked by At

My task is to fetch leads from Pipedrive with their current stage, as well as the lead creation date and the date of the last stage update.

I have a code that retrieves all this data through the API, but for some reason, it doesn't return the stage.

How can I solve this issue?

enter image description here

import requests
import pandas as pd

# Your Pipedrive API token
API_TOKEN = "TOKEN"

# Function to fetch leads and their details
def fetch_leads():
    leads = []
    start = 1000
    limit = 500

    while True:
        url = f"https://api.pipedrive.com/v1/leads?api_token={API_TOKEN}&start={start}&limit={limit}&include_deleted=0"
        response = requests.get(url)

        if response.status_code == 200:
            data = response.json()
            leads_data = data.get("data")
            if leads_data:
                leads += leads_data

            # Check if there are more leads to fetch
            pagination = response.headers.get("Link")
            if pagination:
                next_link = get_next_link_from_pagination(pagination)
                if next_link:
                    start += limit
                    continue

        break

    return leads

# Function to fetch the current stage of a lead
def fetch_current_stage(lead_id):
    url = f"https://api.pipedrive.com/v1/leads/{lead_id}?api_token={API_TOKEN}"
    response = requests.get(url)

    if response.status_code == 200:
        data = response.json()
        stages = data.get("data").get("stages")
        if stages and len(stages) > 0:
            current_stage = stages[-1].get("stage_id").get("name")
            return current_stage

    return None

# Create an empty DataFrame
df = pd.DataFrame(columns=["Lead ID", "Current Stage", "Creation Date", "Last Update Date"])

# Fetch leads and retrieve their details
leads = fetch_leads()

# Iterate through each lead and retrieve the desired information
for lead in leads:
    lead_id = lead.get("id")
    creation_date = lead.get("add_time")
    last_update_date = lead.get("update_time")

    # Fetch the current stage of the lead
    current_stage = fetch_current_stage(lead_id)

    # Append lead details to the DataFrame
    df = df.append({"Lead ID": lead_id, "Current Stage": current_stage, "Creation Date": creation_date, "Last Update Date": last_update_date}, ignore_index=True)

# Print the DataFrame
print(df)
1

There are 1 answers

0
Victor Hoang On

In Pipedrive, the Lead is not entering your pipeline (each pipeline have stages in it), and as a result, lead does not have a stage_id assigned to it.

You can only get stage_id of a Deal: https://developers.pipedrive.com/docs/api/v1/Deals#getDeal