9

from a c# program i want to call my vertex ai endpoint for prediction with an api key (via "Google Cloud"/Credentials/API Keys" )). I gave the api key access to Vertex AI and as a test everything else too.

calling it with curl or c# i get the error that the service expects an "OAuth 2 access token " or something else.

CURL: curl -X POST -H "apikey=..mykey..." -H "Content-Type: application/json" https://.....googleapis.com/v1/projects/[PROJECT_ID]/locations/europe-west4/endpoints/[ENDPOINT_ID]:predict -d @image.json

ERROR: "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. ... }

MY QUESTION: Is there a way to use the Apikey for authentication to vertex ai?

1
  • This is the reason why Google is losing the market in AI. The competition provides a simple API with a simple key authentication. It is sad...
    – k3a
    Commented Sep 23, 2023 at 13:19

3 Answers 3

1

I see this is a bit old but I was having the same issue and after a week was able to solve it.

Here are the steps

Using this code in c#

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

class Program
{
    static async Task Main(string[] args)
    {
        // Define the endpoint URL
        var endpointUrl = $"https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint_id}:predict";

        // Read the image file as bytes
        var imageData = File.ReadAllBytes(filename);

        // Convert the image data to base64
        var imageBase64 = Convert.ToBase64String(imageData);

        // Define the request body
        var requestBody = new
        {
            instances = new[]
            {
                new {
                    content = imageBase64
                }
            }
        };

        // Serialize the request body to JSON
        var requestBodyJson = JsonConvert.SerializeObject(requestBody);

        // Create an HTTP client and request message
        using var client = new HttpClient();
        using var request = new HttpRequestMessage(HttpMethod.Post, endpointUrl);
        request.Content = new StringContent(requestBodyJson, System.Text.Encoding.UTF8, "application/json");

        // Set the authentication header
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_ACCESS_TOKEN");

        // Send the request and get the response
        using var response = await client.SendAsync(request);
        var responseBodyJson = await response.Content.ReadAsStringAsync();

        // Deserialize the response body from JSON
        dynamic responseBody = JsonConvert.DeserializeObject(responseBodyJson);

        // Process the response
        // ...
    }
}

for me the mail issue was the YOUR_ACCESS_TOKEN which is not the API key.

o obtain an access token for calling a Vertex AI endpoint, you need to authenticate using Google Cloud credentials that have the necessary permissions to call the endpoint.

Here's how you can obtain an access token using the Google Cloud SDK:

Install the Google Cloud SDK by following the instructions here: https://cloud.google.com/sdk/install.

Open a terminal or command prompt and run the following command to authenticate using your Google Cloud credentials:

gcloud auth application-default login

Follow the prompts to log in to your Google Cloud account and grant permissions to the Google Cloud SDK.

Once you're authenticated, you can obtain an access token by running the following command:

gcloud auth application-default print-access-token

This will output an access token that you can use to authenticate your requests to the Vertex AI endpoint.

In the example code snippets I provided earlier, replace YOUR_ACCESS_TOKEN with the access token you obtained using the above steps.

That should solve it

1
  • 2
    This is a nice answer. Next steps is to be able to generate this access token using code and on-demand. It is a short-lived token and you can only use the gcloud command while testing (since the token will expire shortly thereafter). Commented Oct 18, 2023 at 8:55
1

You could not use the API key for credentials. You must get the Bearer token via Google authentication or Google Service account

This error will show if you are using API Key

Request is missing required authentication credential.
 
Expected OAuth 2 access token, login cookie or other valid authentication credential. 

See https://developers.google.com/identity/sign-in/web/devconsole-project.

Here I will show how to generate Bearer Token: https://stackoverflow.com/a/75963509/11096674

-1

It is a closed Beta, but if you have access, now you can use google makersuite to generate a simple api key. See step-by-step to generate API key for vertexAI in makersuite, but currently is on a closed beta. then just call the vertex AI api with &key=thatKey

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.