Reputation: 11
I have tried to finde at code example in c#, on how to connect and extract data from the Google search console API. Does anyone know where I can find a code example or if one could add a simple one here in the answers. It will be much appreciated
Upvotes: 0
Views: 850
Reputation: 1276
The Google Search Console API is built on HTTP and JSON, so any standard HTTP client can send requests to it and parse the responses.
However, the Google APIs client libraries provide better language integration, improved security, and support for making calls that require user authorization. The client libraries are available in a number of programming languages; by using them you can avoid the need to manually set up HTTP requests and parse the responses.
You can use the following reference:
https://developers.google.com/api-client-library/dotnet/get_started
This is a C# sample code for using the API:
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Books.v1;
using Google.Apis.Books.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
namespace Books.ListMyLibrary
{
/// <summary>
/// Sample which demonstrates how to use the Books API.
/// https://developers.google.com/books/docs/v1/getting_started
/// <summary>
internal class Program
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Books API Sample: List MyLibrary");
Console.WriteLine("================================");
try
{
new Program().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("ERROR: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { BooksService.Scope.Books },
"user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
}
// Create the service.
var service = new BooksService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Books API Sample",
});
var bookshelves = await
service.Mylibrary.Bookshelves.List().ExecuteAsync();
}
}
}
In this sample code, a new UserCredential instance is created by calling the GoogleWebAuthorizationBroker.AuthorizeAsync method.
If you want to use the API for ASP.Net Core projects (which mostly we use it) you can check out the following page :
https://www.nuget.org/packages/Google.Apis.Auth.AspNetCore3/
Upvotes: 1