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