> ## Documentation Index
> Fetch the complete documentation index at: https://docs.peopledatalabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate a Lead List

> This recipe shows you how to generate a lead list through the use of both the Company Search API and the Person Search API

<RequestExample>
  ```python Python3 lines expandable theme={null}
  from time import sleep
  import requests, json, csv

  API_KEY = "YOUR API KEY"

  PDL_COMPANY_SEARCH_URL = "https://api.peopledatalabs.com/v5/company/search"
  PDL_PERSON_SEARCH_URL = "https://api.peopledatalabs.com/v5/person/search"

  all_records = []

  HEADERS = {
      'Content-Type': "application/json",
      'X-api-key': API_KEY
  }

  ES_QUERY = {
      "query": {
          "bool": {
              "must": [
                  {"term": {"industry": "computer software"}},
                  {"range": {"employee_count": { "gt": 1000 }}}
              ]
          }
      }
  }

  PARAMS = {
      'query': json.dumps(ES_QUERY),
      'size': 10
  }

  response = requests.get(
      PDL_COMPANY_SEARCH_URL,
      headers = HEADERS,
      params = PARAMS
  ).json()

  if response["status"] == 200:
      data = response['data']
      for record in data:
          ES_QUERY = {
              "query": {
                  "bool": {
                      "must": [
                          {"term": {"job_company_id": record['id']}},
                          {"term": {"job_title_levels": "director"}},
                          {"term": {"job_title_role": "engineering"}},
                      ]
                  }
              }
          }
          PARAMS = {
              'query': json.dumps(ES_QUERY),
              'size': 10
          }
          response = requests.get(
              PDL_PERSON_SEARCH_URL,
              headers = HEADERS,
              params = PARAMS
          ).json()
          
          if response["status"] == 200:
              data = response['data']
              all_records.extend(data)
          else:
              print("Person Search Error:", response)
  else:
      print("Company Search Error:", response)

  # Save profiles to csv (utility function)
  def save_profiles_to_csv(profiles, filename, fields = [], delim = ','):
      # Define header fields
      if fields == [] and len(profiles) > 0:
          fields = profiles[0].keys()
      # Write csv file
      with open(filename, 'w') as csvfile:
          writer = csv.writer(csvfile, delimiter=delim)
          # Write Header:
          writer.writerow(fields)
          # Write Body:
          count = 0
          for profile in profiles:
              writer.writerow([ profile[field] for field in fields ])
              count += 1
          print(f"Wrote {count} lines to: '{filename}'")

  # Use utility function to save profiles to csv    
  csv_header_fields = ['full_name', 'job_title', 'job_company_name', 'job_company_website', 'work_email', 'mobile_phone', "linkedin_url"]
  csv_filename = "lead_list.csv"
  save_profiles_to_csv(all_records, csv_filename, csv_header_fields)
  ```

  ```python Python3 SDK lines expandable theme={null}
  from time import sleep
  import requests, json, csv

  # See https://github.com/peopledatalabs/peopledatalabs-python
  from peopledatalabs import PDLPY

  # Create a client, specifying an API key
  CLIENT = PDLPY(
      api_key="YOUR API KEY",
  )

  all_records = []

  ES_QUERY = {
      "query": {
          "bool": {
              "must": [
                  {"term": {"industry": "computer software"}},
                  {"range": {"employee_count": { "gt": 1000 }}}
              ]
          }
      }
  }

  PARAMS = {
      'query': ES_QUERY,
      'size': 10
  }

  response = CLIENT.company.search(**PARAMS).json()

  if response["status"] == 200:
      data = response['data']
      for record in data:
          ES_QUERY = {
              "query": {
                  "bool": {
                      "must": [
                          {"term": {"job_company_id": record['id']}},
                          {"term": {"job_title_levels": "director"}},
                          {"term": {"job_title_role": "engineering"}},
                      ]
                  }
              }
          }
          PARAMS = {
              'query': ES_QUERY,
              'size': 10
          }
          response = CLIENT.person.search(**PARAMS).json()
          
          if response["status"] == 200:
              data = response['data']
              all_records.extend(data)
          else:
              print("Person Search Error:", response)
  else:
      print("Company Search Error:", response)

  # Save profiles to csv (utility function)
  def save_profiles_to_csv(profiles, filename, fields = [], delim = ','):
      # Define header fields
      if fields == [] and len(profiles) > 0:
          fields = profiles[0].keys()
      # Write csv file
      with open(filename, 'w') as csvfile:
          writer = csv.writer(csvfile, delimiter=delim)
          # Write Header:
          writer.writerow(fields)
          # Write Body:
          count = 0
          for profile in profiles:
              writer.writerow([ profile[field] for field in fields ])
              count += 1
          print(f"Wrote {count} lines to: '{filename}'")

  # Use utility function to save profiles to csv    
  csv_header_fields = ['full_name', 'job_title', 'job_company_name', 'job_company_website', 'work_email', 'mobile_phone', "linkedin_url"]
  csv_filename = "lead_list.csv"
  save_profiles_to_csv(all_records, csv_filename, csv_header_fields)
  ```
</RequestExample>

<ResponseExample>
  ```json Response Example theme={null}
  Wrote 100 lines to: 'lead_list.csv'
  ```
</ResponseExample>

<Steps>
  <Step title="Description">
    <Warning>
      **Credit Usage**

      Up to **10 Company Search API Credits** and **100 Person Search API Credits** will be used to execute this recipe
    </Warning>

    This recipes guides you through how to export a list of 100 leads with a current engineering role and a director level position from computer software companies with an employee size greater than 1,000.
  </Step>

  <Step title="Initial Setup">
    If using the Python SDK, import the SDK library and initiate the client object. Otherwise, specify the Company Search and Person Search API endpoints.

    Locate and copy your API Key from the <a href="https://dashboard.peopledatalabs.com/api-keys" target="_blank">API Dashboard</a>
  </Step>

  <Step title="Set API Key">
    If using the Python SDK, we place our API key for authentication in the client class constructor.

    Otherwise, we place our API key for authentication in the header fields of our request. Alternatively, we could have added the API Key into the input parameters.
  </Step>

  <Step title="Set Company Search Elastic Query">
    We set the query so that it will pull computer software companies with more than 1,000 employees.
  </Step>

  <Step title="Set Company Search Input Parameters">
    We set input parameters by assigning the query that we built in the previous step and by limiting the response to 10 records.
  </Step>

  <Step title="Send Company Search Request">
    We execute our company search query and assign its result to a response object.
  </Step>

  <Step title="Check If Company Search Query Was Successful">
    We check the status code of the response. If we receive a successful response (200), we then perform our person search query.
  </Step>

  <Step title="Iterate Through Each Company">
    We iterate through the list of companies we collected to find employees within each of them.
  </Step>

  <Step title="Set Person Search Query">
    We set the query so that it will pull directors with an engineering role from the company that we're currently iterating through.
  </Step>

  <Step title="Limit the Number of Responses">
    We limit the response to 10 records per company by setting the `size` parameter to 10
  </Step>

  <Step title="Send Person Search Request">
    We execute our person search query and assign its result to a response object.
  </Step>

  <Step title="Save Person Data">
    If the response is successful, we append the results of our query to an array of them.
  </Step>

  <Step title="Check for Errors in the Person Search Query">
    If the person search query was not successful, we output why it was not.
  </Step>

  <Step title="Check for Errors in the Company Search Query">
    If the company search query was not successful, we output why it was not.
  </Step>

  <Step title="Output Results to a CSV File">
    Define a function that outputs the list of leads to a CSV file.
  </Step>

  <Step title="Set variables to pass to the function">
    Define the headers, file name to pass to the `save_profiles_to_csv()` function
  </Step>

  <Step title="Execute the function">
    Call the `save_profiles_to_csv()` function and pass the variables you set in the previous step.
  </Step>

  <Step title="Congratulations!">
    <Check>
      **Success!**

      You successfully generated a CSV containing engineers with a director level in companies in the computer software industry with an employee size greater than 1,000 employees!
    </Check>
  </Step>
</Steps>


## Related topics

- [Zapier Integration](/docs/zapier.md)
- [Salesforce Installation & Configuration](/docs/salesforce-integration-setup-installation-configuration.md)
- [Verify Enrichment Workflows](/docs/salesforce-integration-setup-verify-enrichment-workflows.md)
- [PDLScores™ for Person Data](/docs/pdlscores-for-person-data.md)
- [January 2023 Release Notes](/changelog/january-2023-release-notes-v21.md)
