Trouble connecting to Azure OpenAI API (401 Error)

Mithun 30 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 Service
Azure OpenAI Service
An Azure service that provides access to OpenAI’s GPT-3 models with enterprise capabilities.
2,543 questions
Azure AI services
Azure AI services
A group of Azure services, SDKs, and APIs designed to make apps more intelligent, engaging, and discoverable.
2,583 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AshokPeddakotla-MSFT 30,066 Reputation points
    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.

    1 person found this answer helpful.