Introduction to OpenAI

Pre Requisites

What Are API Keys and How to Protect Them

APIs rely on secure authentication to ensure only authorized clients can access your services. In this guide, you’ll learn what API keys are, how they work, and best practices for generating and safeguarding them.

Understanding API Keys

An API key is a unique token that identifies and authorizes a client application when calling your API endpoints. By issuing API keys, you can:

BenefitDescription
Access ControlRestrict who can invoke your API and tailor permissions per key.
Usage TrackingMonitor request volume and set rate limits to prevent abuse.
Scoped PermissionsAssign different access levels (read, write, admin) for each key.

How API Keys Work

  1. A client includes the API key in the request header or query string.
  2. Your server validates the key against its database.
  3. If valid, the request is processed; otherwise, it’s rejected with an HTTP 401 or 403.

Example: Calling the OpenAI API in Python

Here’s a simple Python snippet using the official OpenAI client library:

from openai import OpenAI
import os

# Load your API key from an environment variable
api_key = os.getenv("OPENAI_API_KEY")

client = OpenAI(api_key=api_key)
response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Write a haiku about AI"}]
)

print(response.choices[0].message.content)

Note

Never hard-code your API key in source files. Use environment variables or secret management tools instead.

For full reference, see the OpenAI API Documentation.

Generating and Protecting Your OpenAI API Key

Follow these steps to create and secure a new secret key on the OpenAI platform:

  1. Sign in and click the Settings (cogwheel) icon in the lower-left corner.
  2. Choose API keys from the sidebar menu.
  3. Click Create new secret key, provide a descriptive name (e.g., My Test API), and set the required scopes.
  4. Copy your newly generated key immediately—this is the only time it will be visible—and store it in a secure vault.

The image shows a webpage from the OpenAI platform displaying API keys, with a pop-up window prompting the user to save a newly generated secret key. The interface includes options to copy the key and view permissions.

Warning

Never expose your secret key in client-side code, public repositories, or logs. If compromised, revoke it immediately to prevent unauthorized charges.

Key Management Best Practices

PracticeRecommendation
Unique KeysGenerate separate keys for development, staging, and production.
Principle of Least PrivilegeGrant only the permissions necessary for each key.
Regular RotationRotate keys periodically to minimize security risks.
Usage MonitoringSet up alerts on unusual request patterns.

If you suspect a key has been leaked or abused, delete it right away and issue a replacement.

Watch Video

Watch video content

Previous
Getting Started With OpenAI Platform