How to get Azure OpenAI endpoint and key
Quick answer
To get your Azure OpenAI endpoint and API key, sign in to the Azure Portal, create or select an Azure OpenAI resource, then find the endpoint URL on the resource overview page and the API keys under the Keys and Endpoint section. Use these values to configure your client with AzureOpenAI SDK or REST API calls.
PREREQUISITES
Python 3.8+Azure subscriptionAzure OpenAI resource created in Azure Portalpip install openai>=1.0AzureOpenAI API key and endpoint from Azure Portal
Setup Azure OpenAI resource
First, sign in to the Azure Portal. Navigate to Create a resource and search for Azure OpenAI. Follow the prompts to create a new Azure OpenAI resource in your desired subscription and region. After deployment, open the resource page.
Find endpoint and API key
On your Azure OpenAI resource page, locate the Overview tab to find the Endpoint URL. Then, go to the Keys and Endpoint section to view your API keys. Copy the Endpoint and one of the Keys to use in your application.
| Location | What to find |
|---|---|
| Overview tab | Endpoint URL (e.g., https://your-resource-name.openai.azure.com/) |
| Keys and Endpoint tab | API keys (Key1 and Key2) |
Use endpoint and key in Python
Set environment variables for your AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_API_KEY. Then use the AzureOpenAI client from the openai package to authenticate and call the API.
import os
from openai import AzureOpenAI
client = AzureOpenAI(
api_key=os.environ["AZURE_OPENAI_API_KEY"],
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
api_version="2024-02-01"
)
response = client.chat.completions.create(
model=os.environ["AZURE_OPENAI_DEPLOYMENT"],
messages=[{"role": "user", "content": "Hello from Azure OpenAI!"}]
)
print(response.choices[0].message.content) output
Hello from Azure OpenAI!
Common variations
- Use managed identity authentication instead of API key by passing
azure_ad_token_providertoAzureOpenAI. - Change
api_versionif Azure updates the API. - Use different deployment names for
modelparameter as configured in Azure.
Troubleshooting
- If you get authentication errors, verify your
API keyandendpointare correct and not expired. - Ensure your Azure OpenAI resource is in a supported region.
- Check that your deployment name matches the
modelparameter in code.
Key Takeaways
- Get your Azure OpenAI endpoint URL and API key from the Azure Portal resource page.
- Use environment variables to securely store and access your Azure OpenAI credentials in Python.
- Use the AzureOpenAI client from the openai package with correct api_version and deployment name.
- Verify your resource region and deployment names to avoid authentication and usage errors.