0

Tried to create new Postgres database in google cloud SQL through C# console application ,but its throwing 401 unauthorized issue.

How to pass Api key or any authorization header for google cloud api's?

private static async void CreateDb()
{
    var myObject = new
    {
        name = "test-google-api",
    };

    var json = JsonConvert.SerializeObject(myObject);
    var data = new StringContent(json, Encoding.UTF8, "application/json");

    var url = "https://www.googleapis.com/sql/v1beta4/projects/{projectid}/instances/{instanceid}/databases";
    using var client = new HttpClient();

    var response = await client.PostAsync(url, data).ConfigureAwait(false);

    string result = response.Content.ReadAsStringAsync().Result;
    Console.WriteLine(result);
}
vijay
  • 701
  • 2
  • 12
  • 26
  • 1
    Also don't use `async void` unless its an event handler, also don't call `Result` on an *async method* (basically ever) or you will be back here with other problems before you know it – TheGeneral Feb 26 '21 at 04:18
  • Actually my question is , i am using below Api but i don't know how to pass Api key or any other authentication process for this https://cloud.google.com/sql/docs/postgres/create-manage-databases#rest-v1beta4 – vijay Feb 26 '21 at 04:40
  • 1
    https://cloud.google.com/docs/authentication API Keys are not used. You must use an OAuth Access Token from either user credentials or a service account.. The token is used in the HTTP `Authorization: Bearer ` header. While learning use the token generated by this command: https://cloud.google.com/sdk/gcloud/reference/auth/application-default/print-access-token – John Hanley Feb 26 '21 at 06:10
  • Stackoverflow answer on how to add the header to HttpClient: https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient – John Hanley Feb 26 '21 at 06:12

0 Answers0