Trouble connecting to Azure OpenAI API (401 Error)

Mithun 40 Reputation points
2024-06-15T22:03:31.34+00:00

I'm encountering a 401 error and unable to connect to the Azure OpenAI deployed API using the code below. Please help in resolving this issue.

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://sample-endpoint.openai.azure.com/openai/deployments/gpt-4o/completions?api-version=2023-03-15-preview");
request.Headers.Add("api-key", "Bearer sample-api-key");
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());

Thanks

Azure OpenAI in Foundry Models
Foundry Tools
Foundry Tools

Formerly known as Azure AI Services or Azure Cognitive Services is a unified collection of prebuilt AI capabilities within the Microsoft Foundry platform


1 answer

Sort by: Most helpful
  1. AshokPeddakotla-MSFT 36,021 Reputation points Moderator
    2024-06-18T07:54:42.0766667+00:00

    Mithun Greetings!

    Could you share the complete error logs?

    This 401 error message indicates that your authentication credentials are invalid. This could happen for several reasons, such as:

    • Using a revoked API key.
    • Using a different API key than one under the requesting organization.
    • Using an API key that does not have the required permissions for the endpoint you are calling.

    To resolve the issue, make sure that you are using the correct endpoint and authentication process to connect to the API.

    Also, see Authenticate the client and Build an Azure AI chat app with .NET for more information.

    Do let me know if that helps.

    Was this answer helpful?

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.