Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Minor copy edits and formatting.

...

The goal for the Line Item Tool is to provide a codebase that Solutions Engineers can easily modify to let publishers with unique line item needs, easily code custom line item updates. This Line Item Tool update is a modified version of the open-source dfp-prebid-setup line item tool. Anyone who knows how to code in Python can extend/customize the tool's code to handle their custom requirements.

Quick start

This guide summarizes instructions from a variety of sources to help you get up-to-speed quickly accessing Google Ad Manager, meeting the Python code requirements, and using the Line Item Tool.

Info
titleDFP is now called, Google Ad Manager (GAM):

When you see DFP mentioned in this guide, remember that it is referring to GAM.

GAM access

The first task is to create Google credentials to programmatically access the publisher's GAM account, and then provide access to those credentials in the GAM account:

  1. If you haven't done so yet, sign up for a GAM account.
  2. Create Google developer credentials:
    • Go to the Google Developers Console Credentials page.
    • On the Credentials page, select Create credentials, then Service account key.
    • Select New service account, and select JSON key type. You can leave role blank.
    • Use Create to download a file containing the .json private key.
  3. Enable API access to GAM
    • Sign into your GAM accountyou must have admin rights.
    • In the Admin section, select Global Settings.
    • Ensure that API access is turned on.
    • Press the Add a service account user button, then:
      • Enter the service account email for the Google developer credentials you created above.
      • Set the role to Administrator.
      • Save your settings.

Set up the tool on your local machine using docker

  1. Clone the git repo
  2. Build and run a docker container:
    • Install Docker (if not already installed). 
    • Build the docker: docker build -t openwrap-dfp .
    • Run the container: docker run -tid openwrap-dfp (returns a container id that you will use in the next step)
    • Execute an interactive bash shell on the container where you can run the tool: docker exec -t -i <container_id> /bin/sh
  3. Set googleads.yaml
    • Make a copy of googleads.example.yaml, then rename it, googleads.yaml
    • In googleads.yaml, set these required fields:
      • application_name — the Google project you named while creating GAM credentials above. It should appear in the top-left of the credentials page.
      • network_code — your GAM network number; for example, in the url: https://admanager.google.com/12398712#delivery, the network code is 12398712.
      • path_to_private_key_file — the path to the JSON file downloaded while creating google credentials.
      • Here is the sample content for googleads.yaml:

        Code Block
        languageyml
        titleSample googleads.yaml
        # From: https://github.com/googleads/googleads-python-lib/blob/master/googleads.yaml
        ad_manager:
          #############################################################################
          # Required Fields                                                           #
          #############################################################################
          application_name: lineitem-tool
          network_code: 12398712
          path_to_private_key_file: ./key.json


  4. Verify your setup
    To test your set up, from the top-level directory, run:
    python -m dfp.get_orders
    If successful, it returns all the orders in your GAM account.
  5. Create line items for OpenWrap
    • Edit the settings.py for the line items, you want to create.
    • Read the instructions in the README for config values.
    • For the price buckets file, use the same file template used by the existing line item tool: LineItem.csv
    Note
    titleImportant…
    Ignore the Order Name and Advertiser columns are in the CSV file. Specify those settings in, settings.py
    • Execute the tool:
      python -m tasks.add_new_openwrap_partner

...

The output after running, tasks.add_new_openwrap_partner with the above settings.py will resemble the following:

New functionality

The new Line Item Tool supports the following functionality that the previous version does not:

  • Create line items in any currency.
  • An unlimited number of custom targeting parameters.

Contribute to the tool

Anyone proficient in Python programming can contribute to extending the capabilities of the Line Item Tool. If you would like to contribute, fork this repo, commit your changes, and open a pull request.

...

  1. Add update_line_items_rate.py to the tasks folder. It accepts/reads the line item ID, the new rate, and calls the function defined in dfp directory to update line items:

    Code Block
    languagepy
    titleSample update_line_items_rate.py
    linenumberstrue
    collapsetrue
    """This code example updates the rate of line item.
    """
    import dfp.update_line_item
     
     
    # Set id of the line item.
    LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
     
    #set rate of the line item
    RATE = 'INSERT_RATE_HERE'
     
     
    def main( line_item_id, rate):
       
      #convert rate to micro amount
      rate = num_to_micro_amount(float(rate))
     
      #calling DFP (GAM) method to update line item
      dfp.update_line_item.update_line_item_rate(line_item_id, rate)
     
    def num_to_micro_amount(num, precision=2):
      """
      Converts a number into micro-amounts (multiplied by 1M), rounded to
      specified precision. Useful for more easily working with currency,
      and also for communicating with DFP(GAM)API.
     
      Args:
        num (float or int)
        precision (int)
      Returns:
        an integer: int(num * 1,000,000), rounded to the nearest
          10^(6-`precision`)
      """
      rounding = -6 + precision
      return int(round(num * (10 ** 6), rounding))
     
    if __name__ == '__main__':
      main(LINE_ITEM_ID, RATE)


  2. Add update_line_items.py to the dfp folder. It gets the line item from the GAM account, forms the updated line item config, and calls the GAM line item service to update the line item.

    Code Block
    languagepy
    titleSample update_line_items.py
    linenumberstrue
    collapsetrue
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    import logging
     
    from googleads import ad_manager
     
    from dfp.client import get_client
     
     
    logger = logging.getLogger(__name__)
     
    def update_line_item_rate(line_item_id, rate):
     
      dfp_client = get_client()
      line_item_service = dfp_client.GetService('LineItemService', version='v201911')
     
      # Create statement object to get line item.
      statement = (ad_manager.StatementBuilder(version='v201911')
                   .Where(('id = :id '))
                   .WithBindVariable('id', int(line_item_id)))
     
      # Get line items by statement.
      response = line_item_service.getLineItemsByStatement(
          statement.ToStatement())
      print(response)
      if 'results' in response and len(response['results']):
        # Update each local line item by changing its delivery rate type.
        updated_line_items = []
        for line_item in response['results']:
          if not line_item['isArchived']:
            line_item['costPerUnit']['microAmount'] = rate
            updated_line_items.append(line_item)
     
        # Update line items remotely.
        line_items = line_item_service.updateLineItems(updated_line_items)
        if line_items:
          for line_item in line_items:
            print('Line item with id "%s", belonging to order id "%s", named '
                  '"%s", and rate "%s" was updated.'
                  % (line_item['id'], line_item['orderId'], line_item['name'],
                      line_item['costPerUnit']['microAmount']))
        else:
          print('No line items were updated.')
      else:
        print('No line items found to update.')
     
    def main():
        print("update line items")
     
    if __name__ == '__main__':
      main()

    For GAM-related code, see the sample code available in, https://github.com/googleads/googleads-python-lib/tree/master/examples/ad_manager/v202102. For line item update updates see, Update Line Item Example.

    Using the Line Item Tool's modular framework, you can support a wide range of custom requirements and also contribute to extending and improving this tool.