Developers can use the DFP API to build applications that manage inventory, create orders, pull reports, and more.
The DFP API uses SOAP; to help you get started, we offer client libraries in Java, .NET, Python, PHP, and Ruby. To make your first API request, follow the steps below.
1. Sign up
If you don't already have one, sign up for a DFP account.
2. Prepare for Authentication
Complete the following steps to prepare for authentication using OAuth2:
- Make a note of your network code. You'll find this in the URL when you are logged into your network. For example, in the URL
https://www.google.com/dfp/2032576#delivery, 2032576 is your network code. - Create your OAuth2 credentials by following the steps in our Authentication guide.
3. Enabling API Access
You need to enable API access to at least one network to use the API. If you wish to use the API on your production account, you must enable access on the production account at a minimum. You can also create a test network if you want to test the API in a separate environment.
Enable API access as follows:
- Enable access to a test network:
- You must create a new Google account that you will use only for testing.
- Create a test network by either:
- making a call to
NetworkService.makeTestNetwork(). AMakeTestNetworkexample is included in all the client libraries. - visiting the playground
- making a call to
- Sign in to your new network here: https://www.google.com/dfp/signin. Any Google account already associated with a DFP test network will receive an
AuthenticationError.GOOGLE_ACCOUNT_ALREADY_ASSOCIATED_WITH_NETWORKerror. - Use the network code created in step 2 for all future requests to the API. As usual
NetworkService.getAllNetworks()can be used to fetch all networks with which the current login is associated.
- Enable access to the production API:
- Sign into your DFP account in the DFP user interface, you must have admin rights.
- Select the Admin tab.
- On the Network Settings tab, click the icon to the right of API Access.
- API terms and conditions are displayed, click the Accept button.
- Click Save to activate your API access.
4. Set up your client
Download one of the the DFP client libraries. The libraries offer wrapper functions and features that make it easier and faster to develop applications.
The tabs below provide quickstarts for coding in each of the languages for which there is a client library.
Java
Here is a basic example that shows how to use the Java client library.
- Create an Eclipse project
Open Eclipse and follow these instructions to set up Eclipse with Maven.
- Set up your credentials
All calls to the API require authentication.
// Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.DFP) .fromFile() .build() .generateCredential();You can then create your
DfpSessionusing the Builder pattern:// Construct a DfpSession. DfpSession session = new DfpSession.Builder() .fromFile() .withOAuth2Credential(oAuth2Credential) .build();Credentials and properties in
fromFile()are pulled from the "ads.properties" file. See the README for more info. - Construct a client for the InventoryService
You will need a SOAP Client Stub to make calls to the API. The
DfpServicesclass handles this logic. This object is expensive to construct - instantiate it once and reuse as much as possible within a thread.// Construct a DFP service factory, which can only be used once per thread, // but should be reused as much as possible. DfpServices dfpServices = new DfpServices();You can then obtain a reference to the service class like so:InventoryServiceInterface inventoryService = dfpServices.get(session, InventoryServiceInterface.class); - Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all ad units present within the account into an
AdUnitPageobject.// Create a statement to select all ad units. StatementBuilder statementBuilder = new StatementBuilder() .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Default for total result set size. int totalResultSetSize = 0; do { // Get ad units by statement. AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (AdUnit adUnit : page.getResults()) { System.out.printf( "%d) Ad unit with ID '%s' and name '%s' was found.%n", i++, adUnit.getId(), adUnit.getName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize);
For more detailed information about using the Java Client Library, refer to the README file in the client library distribution.
Python
Here is a basic example that shows how to use the Python client library.
The Python Client Library supports Python v2.7 or Python v3.0+ via the 2to3 converter.
Before you can run this example, you must follow the steps in the README file that is distributed with the Python Client Library. If you need help authenticating against our client library, you must also set up your OAuth2 credentials as outlined in our OAuth2 wiki.
- Set up your credentials
To initialize the Client object, call
DfpClient.LoadFromStorage()after populating the templated fields in thegoogleads.yamlfile.from googleads import dfp # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage()
- Construct a client for the InventoryService
Each service can be retrieved through its appropriate
getService()method. ThegetService()method returns a SOAP client to that service.# Initialize appropriate service. ad_unit_service = client.GetService('InventoryService', version='v201608') - Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns and prints all of the ad units present within a network.
statement = dfp.FilterStatement() # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. while True: response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement()) if 'results' in response: for ad_unit in response['results']: # Print out some information for each ad unit. print('Ad unit with ID "%s" and name "%s" was found.\n' % (ad_unit['id'], ad_unit['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize']
PHP
Here is a basic example that shows how to use the PHP client library.
Before you can run this example, you must follow the steps in the README file that is distributed with the PHP Client Library.
The PHP client library requires PHP 5.2.x and uses the native SoapClient.
It requires the following PHP extensions:
You can get started using the PHP client library as follows:
- Set up your credentials
First, create a new
DfpUser. This loads the credentials from thesrc/Google/Api/Ads/Dfp/auth.inifile. Refer to the README file for alternate ways to load credentials.// Get DfpUser from credentials in "../auth.ini" // relative to the DfpUser.php file's directory. $user = new DfpUser();
- Construct a client for the InventoryService
Each service can be retrieved through its appropriate
getService()method. ThegetService()method returns a SOAP client to that service and loads all classes for that service.// Get the InventoryService. $inventoryService = $user->GetService('InventoryService', 'v201608'); - Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all ad units present within the account into a
pageobject, 500 at a time.// Create a statement to select all ad units. $statementBuilder = new StatementBuilder(); $statementBuilder->OrderBy('id ASC') ->Limit(StatementBuilder::SUGGESTED_PAGE_LIMIT); // Default for total result set size. $totalResultSetSize = 0; do { // Get ad units by statement. $page = $inventoryService->getAdUnitsByStatement( $statementBuilder->ToStatement()); // Display results. if (isset($page->results)) { $totalResultSetSize = $page->totalResultSetSize; $i = $page->startIndex; foreach ($page->results as $adUnit) { printf("%d) Ad unit with ID %s, name '%s', and status %s was found.\n", $i++, $adUnit->id, $adUnit->name, $adUnit->status); } } $statementBuilder->IncreaseOffsetBy(StatementBuilder::SUGGESTED_PAGE_LIMIT); } while ($statementBuilder->GetOffset() < $totalResultSetSize); printf("Number of results found: %d\n", $totalResultSetSize);
If you want to develop in PHP without the client library, please refer to the NoClientLibrary wiki article.
.NET
Here is a basic example that shows how to use the .NET client library
- Create a new project
Open Visual Studio and create a new project (i.e. Console Application).
- Add required library references to your project
If you're using NuGet, simply add a dependency for Google.Dfp, or Google.Dfp.Examples.CSharp if you want to run code examples.
Otherwise, download the binary distribution from GitHub and copy all dlls from the \lib folder into your project. Add references to these dlls and to System.Web.Services in your project.
- Setup your App.config
Copy src\App.config to your project directory and add it to your project. If your application has its own App.config, then you can copy the following nodes into your App.config:
- configuration/DfpApi
- configuration/system.web
- configuration/configSections/section[name="DfpApi"]
- configuration/system.net
- Setup credentials
Open App.config and edit the following keys:
<add key="ApplicationName" value="INSERT_YOUR_APPLICATION_NAME_HERE" /><add key="NetworkCode" value="INSERT_YOUR_NETWORK_CODE_HERE" /><add key="OAuth2ClientId" value="INSERT_OAUTH2_CLIENT_ID_HERE" /><add key="OAuth2ClientSecret" value="INSERT_OAUTH2_CLIENT_SECRET_HERE" /><add key="OAuth2RefreshToken" value="INSERT_OAUTH2_REFRESH_TOKEN_HERE" />
- Make a call to the library
You can call the library as shown in the following C# code snippet
DfpUser user = new DfpUser(); InventoryService inventoryService = (InventoryService) user.GetService(DfpService.v201608.InventoryService); // Create a statement to select ad units. StatementBuilder statementBuilder = new StatementBuilder() .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Retrieve a small amount of ad units at a time, paging through // until all ad units have been retrieved. AdUnitPage page = new AdUnitPage(); try { do { page = inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement()); if (page.results != null) { // Print out some information for each ad unit. int i = page.startIndex; foreach (AdUnit adUnit in page.results) { Console.WriteLine("{0}) Ad unit with ID \"{1}\" and name \"{2}\" was found.", i++, adUnit.id, adUnit.name); } } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); Console.WriteLine("Number of results found: {0}", page.totalResultSetSize); } catch (Exception e) { Console.WriteLine("Failed to get ad units. Exception says \"{0}\"", e.Message); }
If you don't want to set your credentials in your App.config, then refer to this wiki article for alternate ways of using the DfpUser class. For more detailed information about using the .NET Client Library, refer to the README . If you want to develop in .NET without the client library, please refer to the NoClientLibrary wiki article.
Ruby
Here is a basic example that shows how to use the Ruby client library.
The Ruby Client Library requires Ruby 2.1 or 2.2 as well as the Google Ads Savon SOAP toolkit of version 1.0.0 or later.
Before you can run the example, you must follow the steps in the README file that is distributed with the Ruby Client Library. You will need to edit dfp_api.yml to include your authentication credentials.
- Set up your credentials
First, create a new
DfpApiinstance. This loads the credentials from the~/dfp_api.ymlfile. Refer to the README file for alternate ways to specify credentials.# Get DfpApi instance and load configuration from ~/dfp_api.yml. dfp = DfpApi::Api.new
- Construct an InventoryService instance
Each service can be retrieved through the
service()method. This method returns a service stub object that can be used to call its methods. Specify the service name as the first parameter and required API version as the second parameter.# Get the InventoryService. inventory_service = dfp.service(:InventoryService, API_VERSION)
- Perform an operation
After you've instantiated a client to connect to the API, you can perform an operation. The following code returns all ad units present within the account into a
pageobject, 500 at a time.# Create a statement to get all ad units statement = DfpApi::FilterStatement.new('ORDER BY id ASC') begin # Get ad units by statement. page = inventory_service.get_ad_units_by_statement(statement.toStatement()) if page[:results] # Print details about each ad unit in results. page[:results].each_with_index do |ad_unit, index| puts "%d) Ad unit ID: %d, name: %s, status: %s." % [index + statement.offset, ad_unit[:id], ad_unit[:name], ad_unit[:status]] end end statement.offset += DfpApi::SUGGESTED_PAGE_LIMIT end while statement.offset < page[:total_result_set_size] # Print a footer. if page.include?(:total_result_set_size) puts "Total number of ad units: %d" % page[:total_result_set_size] end
If you want to develop in Ruby without the client library, please refer to the wiki article.
5. Next Steps
When you have got a client library up and running, go ahead and play with the examples provided to extend them for your needs.
Visit the reference documentation for the version you are working with to learn more about the API
If you need help, read the advanced topics listed under the Guides section or visit the Forum.


