Google Ads API: Build A Keyword Research Tool With C# For Free!

google ads api with c#

Table of Contents

Spread the love

How to Develop a Free Keyword Research Tool with Google Ads API & C#?

We'll use Google Ads API, and make a tool in which you can give a keyword, and returns back hundreds of keyword suggestions and ideas with metrics like search volume data, CPC and Competition

For example, if you go to keywordtool.io, you can search for a keyword, and it gives you keyword suggestions.

It is considered one of the best free keyword tools. (But it’s not totally Free)

Let’s say you write a word here like “learn programming” Click on search.

You can see it will give you keyword ideas with search volume, CPC, competition, etc. 

And here comes the part where I said it was not completely Free. if you want to get these hidden values you need to go with a pro “paid version.” 

Another example is H-supertools. I Built it and is totally Free to use.

If you search here for “learn programming”, hit search.

You can see now suggestions like monthly search volume, paid competition, and CPC. 

Today I’ll reveal the complete process of how to build similar tools.

When you know how to build tools like this, You can build a SaaS service-based business or maybe your own tools website. And as an added bonus you will be enhancing your own coding abilities and knowledge. 

How does our Keyword Tool work?

It's a simple console application. When you run it, you'll have two options to authenticate with Google Ads API and to perform keyword research. as shown in the image below

google ads api with c#

Let's perform a Keyword Research and search for “C#“. 

google ads api  keyword tool

Our tool gets back ~500 keyword ideas with search volume data, competition, and CPC values. It also draws this table for you. 

Of course, In my case, it's a simple console application (just for simplicity reasons.) But we can use and implement the same code in any type of application. Let’s say a mobile application, web application, or even a desktop app.

Now that we have gotten a general understanding of the Project. Let’s start!

Develop a Keyword Research Tool with Google Ads API & C#

Before starting Coding, I recommend you watch this Video, as everything is explained visually if you are that loves videos more than reading 🙂

Step1: Setup Your Google Cloud Console Account.

So, our first step is to go to the Google cloud console and sign up using your Gmail account.

google api console

Simply go here and create a new project if you don't have one.

google console create project

google ads api keyword tool

 

When you create a project. Go to Enable APIs & Services.

google ads api tutorial

And click on “Enable APIs

google ads api tutorial

After that, search for “Google ads API” and you' ll see the Google ads API.

google ads api tutorial
google ads api tutorial

Click on it and, click “Enable.”

google ads api tutorial

In my case, it's already enabled.

Step 2: Create Credentials.

Click on “Credentials” and then hit “Create credentials.” 

Make sure to select “OAuth client id

google ads api

Follow along with the setup wizard and get client IDs.

google ads api tutorial

Now click on this arrow here.

google ads api tutorial

And you will get the Client ID and the Client Secret.

google ads api tutorial

We will use this to authenticate our application.

I don’t cover “running and creating credentials” in this Tutorial. It is out of the scope. Plus it is easy and we have a ton of tutorials about this on the internet. You can simply Google it!

Let’s move on. 

Now we have the client ID and the client secret.

Google Ads API Authentication Code With C#

Now we need to authenticate.

For this, open the application project in visual studio and open KeywordIdeasGoogleAPI.cs class that I created.

google ads api c#

You will see we have two methods.

One is called Authenticate and the other is called search. Open the authentication method.

google ads api c#

While doing my research I found the authentication code on Github. It does Authentication with Google Ads API. 

I just tested & tweaked it and Made it simpler for you to understand and use ????

This is the function, that will return the authentication keys that you will use to authenticate.

google ads api c#

Let's test this.

Run the application.

google ads api c#

It will tell you to authenticate press 1, and hit ”enter.”

google ads api c#

And now it will ask you for the client ID.

google ads api c#

Copy the client ID.

Paste here.

google ads api c#

Copy and Paste the client's secret here.

google ads api authenticate c#

And now it will authenticate. 

I will select my account. 

 It's not verified, it's okay to hit continue. As we are using it in our own environment.

Continue and Now we are done.

Now it will prompt you to copy these keys.

google ads api authentication c#

I‘ve copied them (as highlighted in white above) and pasted them into the app.config file. So just copy it and close the application.

Now go to Project in Visual Studio.

google ads api c#

Create the App.config file and you will see, that I already added these keys.

google ads api c#

And just a reminder. All the code is in the source Code Section of this Blog Post. So feel free to check it out and copy it if you like!

When you have done the above procedure.

Get The Developer Token

Now the next step is to get the developer token. As You can see, we need to set the developer token in the app.config file.

google ads api developer token

For this, you will need to create a Google ads Manager Account.

Here is a link here for the Google API documentation.

Use this link to create a manager account on google ads.

google ads api manager account

It's like any Google ads account. Click on tools and then click on API center and you'll see the developer token there.

google ads  get developer token

Just copy it.

google ads get developer token

And paste in your app.config file, in this section here. 

google ads  get developer token

Perform a Keyword Research Test

Now we have developer tokens, we have authentication keys. Everything is ready to authenticate and perform some keyword research operations.

In the Google API, we have the keyword ideas service.

keyword ideas service

If you scroll down we will see all samples in C#, PHP, and Python. In our case, we are using C#. We have this function here in this code. You can copy it.

But it will not work directly.

So after doing some research and testing. I created this method here.

The search method.

The Source Code for this method is provided in the Code section of this Blog Post.

google ads api keyword tool

Then, Pass the google client object, and the customer id (which you can get also from the google ad account ), the location id, the language id, and the keywords you want to search for.

You just enter and pass them here and you will generate the keyword results table and return back to the user.

google ads api keyword tool

So, How to get the customer id?

For this, you need to go back here and you need to create a test account.

google ads test account

Click on this link here and create a test account.

google ads create test account

You can see this is my test account. It will show you this red message here just click and copy this ID here.

google ads create test account

Then go back to your code, and paste it.

Let's open our main program script.

You can see here, that it will tell you to enter a keyword. We read the keyword then we will pass the customer id.

Make sure to remove the dashes and keep only the numbers.

Now we need to enter IDs for locations.

It will give you an example here like New York is 21167. 

You can click on this link here. to get a list of location IDs.

google ads api create keyword tool

google geo IDs

You can download this CSV file to get the ids of any location on this planet.

google location IDs csv

So you can get these IDs and use them inside your code here.

Then you need to pass the language id. For English, it's 1000. 

You can get it from this link.

And you will get the language IDs for any language.

If you go down we have English 1000 french is 1002 and so on.

So you get the language code and paste it here.

google ads API set language ID

Then in the main function of the console app, you create a new google ads client and call the search function.

google ads API keyword tool

And you pass the client as a parameter. Automatically this client will read authentication keys from the app.config file. And that's it!

Let's run again.

So after you authenticate and add the keys in the app.config file, you can do keyword research.

google ads api keyword tool

Let's say, “subscribe to my channel.” ????

Press enter.

You can see now, we have a full table with keyword data, search volume, competitions, and CPC bids.

google ads api keyword tool

By the way.

When you get the API data, the low cpc and high cpc bids will be in micro, so you need to divide by 1 million to get the actual CPC value.

Note: CPC Bids means that advertisers are paying these numbers to advertise on Google.

Keyword Research Tool with C# (Source Code)

Here is the Full Project on Github. And below is the code mentioned in this Post.

1. Authentication

//start

public void Authenticate()
        {
            const string GOOGLE_ADS_API_SCOPE = "https://www.googleapis.com/auth/adwords";

            Console.WriteLine("This code example creates an OAuth2 refresh token for the " +
                            "Google Ads API .NET Client library. This example works with both web and " +
                            "desktop app OAuth client ID types. To use this application\n" +
                              "1) Follow the instructions on " +
                              "https://developers.google.com/google-ads/api/docs/oauth/cloud-project " +
                              "to generate a new client ID and secret.\n" +
                              "2) Run this application.\n" +
                              "3) Enter the client ID and client secret when prompted and follow the instructions.\n" +
                              "4) Once the output is generated, copy its contents into your App.config " +
                              "file. See https://developers.google.com/google-ads/api/docs/client-libs/dotnet/configuration " +
                              "for other configuration options.\n\n");

            Console.WriteLine("IMPORTANT: For web app clients types, you must add " +
                "'http://127.0.0.1/authorize' to the 'Authorized redirect URIs' list in your " +
                "Google Cloud Console project before running this example to avoid getting a " +
                "redirect_uri_mismatch error. Desktop app client types do not require the " +
                "local redirect to be explicitly configured in the console.\n\n");

            // Accept the client ID from user.
            Console.Write("Enter the client ID: ");
            var clientId = Console.ReadLine();

            // Accept the client ID from user.
            Console.Write("Enter the client secret: ");
            var clientSecret = Console.ReadLine();

            // Load the JSON secrets.
            var secrets = new ClientSecrets()
            {
                ClientId = clientId,
                ClientSecret = clientSecret
            };

            try
            {
                // Authorize the user using desktop flow. GoogleWebAuthorizationBroker creates a
                // web server that listens to a random port at 127.0.0.1 and the /authorize url
                // as loopback url. See https://github.com/googleapis/google-api-dotnet-client/blob/main/Src/Support/Google.Apis.Auth/OAuth2/LocalServerCodeReceiver.cs
                // for details.
                Task<UserCredential> task = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    secrets,
                    new[] { GOOGLE_ADS_API_SCOPE },
                    string.Empty,
                    CancellationToken.None,
                    new NullDataStore()
                );
                var credential = task.Result;

                Console.WriteLine("\nCopy the following content into your App.config file.\n\n" +
                    $"<add key = 'OAuth2Mode' value = 'APPLICATION' />\n" +
                    $"<add key = 'OAuth2ClientId' value = '{clientId}' />\n" +
                    $"<add key = 'OAuth2ClientSecret' value = '{clientSecret}' />\n" +
                    $"<add key = 'OAuth2RefreshToken' value = " +
                    $"'{credential.Token.RefreshToken}' />\n");

                Console.WriteLine("/n" +
                    "<!-- Required for manager accounts only: Specify the login customer -->\n" +
                    "<!-- ID used to authenticate API calls. This will be the customer ID -->\n" +
                    "<!-- of the authenticated manager account. It should be set without -->\n" +
                    "<!-- dashes, for example: 1234567890 instead of 123-456-7890. You can -->\n" +
                    "<!-- also specify this later in code if your application uses -->\n" +
                    "<!-- multiple manager account OAuth pairs. -->\n" +
                    "<add key = 'LoginCustomerId' value = INSERT_LOGIN_CUSTOMER_ID_HERE />/n/n");


                Console.WriteLine("See https://developers.google.com/google-ads/api/docs/client-libs/dotnet/configuration " +
                    "for alternate configuration options.");
                Console.WriteLine("Press <Enter> to continue...");
                Console.ReadLine();
                

            }
            catch (AggregateException)
            {
                Console.WriteLine("An error occurred while authorizing the user.");
            }
        }

//end
//start

 public void Search(GoogleAdsClient client, long customerId, long[] locationIds,
                                long languageId, string[] keywordTexts)
        {
            var keywordPlanIdeaService =
                client.GetService(Services.V10.KeywordPlanIdeaService);

            //Check if keyword is not empty
            if (keywordTexts.Length == 0)
            {
                throw new ArgumentException("At least one keyword is required!");
            }


            var request = new GenerateKeywordIdeasRequest
            {
                CustomerId = customerId.ToString(),
                KeywordSeed = new KeywordSeed()
            };


            request.KeywordSeed.Keywords.AddRange(keywordTexts);


            //Set Locations
            foreach (long locationId in locationIds)
            {
                request.GeoTargetConstants.Add(ResourceNames.GeoTargetConstant(locationId));
            }
            //Set Language
            request.Language = ResourceNames.LanguageConstant(languageId);
            //Set Network
            //Google or GoogleWithPartners
            request.KeywordPlanNetwork = KeywordPlanNetworkEnum.Types.KeywordPlanNetwork.GoogleSearch;

            try
            {
                // Generate keyword ideas based on the specified parameters.
                var response =
                    keywordPlanIdeaService.GenerateKeywordIdeas(request);

                //Create a Console Table
                var table = new ConsoleTable("Keyword", "Search Volume", "Competition","Low CPC Bid", "High CPC Bid");

                // Iterate over the results and add to the table
                foreach (var result in response)
                {
                    var metrics = result.KeywordIdeaMetrics;

                    if (metrics != null)
                    {
                       
                        var lowBid = Convert.ToDecimal(metrics.LowTopOfPageBidMicros) / 1000000;
                        var highBid = Convert.ToDecimal(metrics.LowTopOfPageBidMicros) / 1000000;

                        table.AddRow(result.Text, metrics.AvgMonthlySearches, metrics.CompetitionIndex, "$ " + lowBid, "$ " + highBid);
                    }
                    else
                    {
                        table.AddRow(result.Text, "", "","","");
                    }

                }

                table.Write();
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure!");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }


//end

Conclusion

In this tutorial, I showed you How to use Google Ads API and C# To Develop a Free Keyword Research Tool.

If you did it. Congratulations ????

The Google Ads API is free but has some limitations if you wanna scale your app, but did you know you can use the Free Google Suggestions API To Develop a Keyword Research Tool with no limits! Yes! If you wanna learn how. Check this post.

Don't FORGET To join me on YouTube:

Subscribe To My Channel To Get All Updates

Thanks!

Take care, and Happy Coding! If you have questions or want to discuss anything related to this project, I will be happy to chat with you on our forum.

Make sure to check out our other Tutorials, & Take Care!


Spread the love