Git Product home page Git Product logo

google-ads-node's Introduction

Google Ads Node

Unofficial Google Ads API gRPC client library for Node

Built by Opteo

Features

Note: This library is a minimal, low-level implementation for calling the Google Ads API with gRPC Protocol Buffers. For a more feature-complete and easier-to-use library, try our Javascript client library.

Installation

$ yarn add google-ads-node

Example

import {
  GoogleAdsClient,
  SearchGoogleAdsRequest,
  SearchGoogleAdsResponse,
  Campaign,
  Metrics
} from "google-ads-node"

// 1. Create a new client with valid authentication
const client = new GoogleAdsClient({
  access_token: "<ACCESS_TOKEN>",
  developer_token: "<DEVELOPER_TOKEN>",
  login_customer_id: "<LOGIN_CUSTOMER_ID>",
});
const customerId = "1234567890";

async function example() {
  // 2. Load a Google Ads service
  const service = client.getService("GoogleAdsService");

  // 3. Create a request
  const request = new SearchGoogleAdsRequest();
  request.setQuery(`
    SELECT
      campaign.id,
      campaign.name,
      campaign.status,
      segments.device,
      metrics.impressions,
      metrics.clicks,
      metrics.ctr,
      metrics.average_cpc,
      metrics.cost_micros
    FROM campaign
  `);
  request.setCustomerId(customerId);
  request.setPageSize(12);

  // 4. Get the results
  const result: SearchGoogleAdsResponse = await service.search(request)
    .catch((err: Error) => {
      console.log("--- Error in search ---");
      console.log(err);
    });

  // 5. Inspect the data!
  for (const row of res.getResultsList()) {
    const campaign: Campaign = row.getCampaign() as Campaign;
    const metrics: Metrics = row.getMetrics() as Metrics;

    if ((metrics.getClicks() as any) > 0) {
      console.log(`Campaign "${campaign.getName()}" has ${metrics.getClicks()} clicks.`);
    } else {
      console.log(`Campaign "${campaign.getName()}" has no clicks.`);
    }
  }
}

example();

Usage

Authentication

1. No internal authentication

A valid Google Ads access_token must be provided. This usage depends on the access_token being refreshed and generated outside of the client. If the token isn't valid, an UNAUTHENTICATED error will be thrown. It's recommended to follow the instructions here for generating tokens.

const client = new GoogleAdsClient({
  developer_token: "<DEVELOPER_TOKEN>",
  access_token: "<ACCESS_TOKEN>",
});

2. Token generation and refresh handling

This approach, which is recommended, internally handles access token generation and refreshing. A valid client_id, client_secret and refresh_token must be provided.

const client = new GoogleAdsClient({
  client_id: "<CLIENT_ID>",
  client_secret: "<CLIENT_SECRET>",
  refresh_token: "<REFRESH_TOKEN>",
  developer_token: "<DEVELOPER_TOKEN>",
});

Services

To load a Google Ads service, simply use the getService method. It supports a single string, being the name of the service. For a full list of avaiable services, check out the Google Ads service reference.

const service = client.getService("AdGroupAdService");

From here, you can then use all the available methods for the service e.g. getAdGroupAd() and mutateAdGroupAds(). The parameters and return value match the format specified in the Google Ads documentation.

import { GetAdGroupRequest } from "google-ads-node";

const request = new GetAdGroupAdRequest();
const ad = await service.getAdGroupAd(request);

Note: Service methods use camelCase in this library, whereas the Google Ads documentation uses TitleCase, so if a service method was called GetCampaign(), in this library it would be getCampaign()

Results

By default, since this library is implemented with gRPC, any calls via a service return an object in the protocol buffer format. This is a binary format object, which is difficult to understand, especially if you're not using the Typescript definitions.

Because of this, retrieving the results you want can be quite verbose. An example of this is below, where we show two methods for acquiring the id of a campaign.

const results = await service.search(request);

// Method 1
const { resultsList } = results.toObject();
const id = resultsList[0].campaign.id.value;

// Method 2
const row = results.getResultsList();
const campaign = row.getCampaign();
const id = campaign.getId().value;

If you don't wish to work directly with protocol buffers, are unfamiliar with gRPC, or just want an easier way to retrieve the data, we recommend using the parseResults client option. Setting this option to true will internally handle parsing the results in a more javascript friendly way, and return the desired entities/metrics/segments as objects (with all types correctly handled, e.g. name as a string, id as a number, etc.).

const client = new GoogleAdsClient({
  client_id: "<CLIENT_ID>",
  client_secret: "<CLIENT_SECRET>",
  refresh_token: "<REFRESH_TOKEN>",
  developer_token: "<DEVELOPER_TOKEN>",
  parseResults: true,
});

// ...

const { resultsList } = await service.search(request);
console.log(resultsList[0].campaign.id); // 123

Changelog

Contributing

Protocol Buffers

To update the Google Ads API version, the latest proto files (in the googleapis submodule) must be compiled.

Requirements:

  • Protoc compiler installed on your machine and added to your $PATH
  • Latest dependencies installed โ€“ make sure to use yarn install since some dependencies require a C++ compilation step

Steps:

  1. Navigate into the googleapis/ submodule and update with git pull.

  2. Run make protos to compile the *.proto files

  3. The new compiled proto files should now be in src/protos/, under the google/ads/googleads/v0/ path.

google-ads-node's People

Contributors

chloeroseanne avatar kritzware avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.