Python code to use the Capterra API key to extract the data.

Python code to use the Gartner Click Report API key to extract Capterra data.

Get Capterra click report using API key.

Welcome visitor! Thanks so much for stopping by. Today we will get Capterra API and learn how python can be used to make API calls to extract Capterra data.

It might be possible you have no idea What is Capterra? What do they do? Don’t worry. Will get the above question answered briefly below.

Capterra is an online marketplace data intelligence platform serving as an intermediary between buyers and technology vendors within the software industry. It helps consumers search, compare, and choose the right software according to their needs with user reviews and research.

What are you about to learn?

  1. Process of getting Capterra API.
  2. Python code to use API Key to extract Capterra Insights.

Generating Capterra API:

To get the API key one needs to reach out to the Capterra account manager. You can find the instructions for the API KEY in the vendor portal under the insights tab, called API documentation

Clicking on the above link will ask you to log in to your Capterra account, after login your screen should look similar to something like the below screengrab.

NOTE: Same API key can be used for GetApp if the GetApp account and Capterra account are mapped together.

Python code to use API Key to extract Capterra Insights (click report):

In this step, we will be creating a python file with several functions to perform separate tasks. This file will consist of a function to make API calls with an API key and other essential parameters, a function to validate data format, and a function to read command line parameters like dates.

#!/usr/local/bin/python3
#command to run file : $ python ./python/capterra_data.py -s 2021-07-16 -e 2021-07-16
 
import pandas as pd
import os.path
import sys
import getopt
import json
import requests
from datetime import datetime, timedelta
 
def isFile(fileName):
    if(not os.path.isfile(fileName)):
        raise ValueError("\n *** You must provide a valid filename as parameter *** ", fileName)
 
#function read to command line parameter.
def readfile(argv):
    global start_date
    global end_date
    tmp_domain_id = None
    try:
        opts, args = getopt.getopt(argv,"s:e:")
    except getopt.GetoptError:
        sys.exc_info()
    for opt, arg in opts:
        if opt == "-s":
            start_date = arg
        elif opt == "-e":
            end_date = arg
        else:
            print("\n*** Invalid Option in command line *** ")
 
#function for date validation
def date_validation(date_text):
    try:
        if date_text != datetime.strptime(date_text, '%Y-%m-%d').strftime('%Y-%m-%d'):
            raise Exception('Input Date does not match format yyyy-mm-dd ')
        else:
            return datetime.strptime(date_text,'%Y-%m-%d').date()
    except:
        raise Exception('date_validation Failed : ',sys.exc_info()[:-1])
 
#function to use API key and make a REST api call to get data.
def get_capterra_data(api_key,start_date,end_date):
    try:
        startDate = date_validation(start_date)
        dt = startDate+timedelta(1)
        week_number = dt.isocalendar()[1]
 
        endDate = date_validation(end_date)
 
        #Define Data Frame
        cp_data_df = pd.DataFrame()
        
        #make the API call
        #channel=capterra : to get capterra clicks report.
        url = "https://public-api.capterra.com/v1/clicks?start_date="+str(startDate)+"&end_date="+str(endDate)+"&channel=capterra"
        
        headers = {"Authorization": api_key}
        r = requests.get(url= url, headers = headers)
 
        if r.status_code != 200:
            print("\n*** something went wrong *** ",r)
            r.raise_for_status()
        else:
            response_dict = json.loads(r.text)
            if "data" in response_dict and response_dict["data"]:
                for record in response_dict["data"]:
                    properties_keys = record.keys()
                    cp_data_df = cp_data_df.append(record,ignore_index = True)
 
                fields = ['email','cpl','channel','vendor_name','country','conversion_rate','avg_cpc','avg_position','date_of_report']
                cp_data_df.drop(fields,inplace=True, axis=1)
 
                grp_instances = ["product_name","category"]
                cp_data_df = cp_data_df.groupby(grp_instances).sum().reset_index()
 
                cp_data_df["start_date"] = startDate
                cp_data_df["end_date"] = endDate
                cp_data_df["week"] = week_number
                
            else:
                print("\n*** Data not Available ***")
 
        print("\nFunction (get_capterra_data) Finished successfully. ")
        return cp_data_df
    except:
        print("\n*** Function (get_capterra_data_api) Failed *** ",sys.exc_info())
        raise
 
if __name__ == '__main__':
    try:
        timestamp = datetime.strftime(datetime.now(),'%Y-%m-%d')
        print("DATE : ",timestamp,"\n")
        print("Capterra data extraction process started.")
        readfile(sys.argv[1:])
 
        api_key = "Paste the API key here."
        
        cp_master_data = get_capterra_data(api_key,start_date,end_date)
        print("\n Master Data :\n",cp_master_data)
 
        print("\nCapterra data modulation process Finished.")
    except:
        print("\n*** capterra data modulation processing Failed *** ", sys.exc_info())
 

NOTE: To use the full potential of the above code, please try to understand workflow and make sense of what logic does. If you know of a better and optimized way to do the same thing let me know in the comment section.

Save the file as “capterra_data.py” and use the command python ./python/capterra_data.py -s 2021-07-16 -e 2021-07-16” to run the file. Where -s: is for the start date and -e: is for the end date.

If there is no error you see a data frame table displayed in the output.

Congratulations! you now know python logic to retrieve the Capterra click report using the Capterra API key. Hope I was able to make the entire process of building python logic for Capterra API calls and data retrieval simpler.

Check out other API Set-Up Guide.

If you have any questions or comments feel free to reach me at.

Leave a Reply

Your email address will not be published. Required fields are marked *