Categories
Search
Connecting to the Google Search Console API
Part 2: Code Example
For this example we will create a new C# Console App using Visual Studio. Copy the Service Account JSON Credentials you downloaded from Part 1 into the Solution Explorer. Right Click on the file and open the file’s properties. Make sure that “Copy to Output Directory” is set to “Copy always”. Right click on your project and select “Manage NuGet Packages”. From the tab that opens, browse for “Google.Apis.SearchConsole.v1” and install it. You may also need to install the “Google Apis Core” package.
A Working Example
If you followed the steps from Part 1, you should now be able to connect to Google’s API using the following code snippet.
// CREATE API CREDENTIAL GoogleCredential credential; using (var stream = new FileStream("path-to-your-service-account-json-file.json", FileMode.Open, FileAccess.Read)) { credential = GoogleCredential.FromStream(stream).CreateScoped(SearchConsoleService.Scope.Webmasters); } // CREATE API SEARCH SERVICE var service = new SearchConsoleService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Your Application Name", }); // CREATE THE REQUEST SearchAnalyticsQueryRequest request = new SearchAnalyticsQueryRequest() { StartDate = "2024-01-01", EndDate = "2024-01-31", Dimensions = ["query"] }; // GENERATE THE REPORT var reports = await service.Searchanalytics.Query(request, "...https://www.the-website-you-have-access-to...").ExecuteAsync(); // ... |
Using the code snippet above you should now be able to connect to Google’s APIs and programmatically generate your reports.