Lompat ke konten

Pelajaran 2 ยท Getting Started

API Keys, Projects and Setup

Create an OpenAI API key, store it safely in an environment variable, install the official SDK, and organize projects, limits and key rotation.

Before your code can call the API, it has to prove who it is. It does that with an API key, a long secret string. Whoever holds the key can make requests that are billed to your account and that can reach the data its project can reach. Setting up the key well takes a few minutes and prevents the most common and most expensive beginner accidents.

In this lesson you create a key in the dashboard, store it outside your code, install the SDK, and learn how projects and limits keep mistakes small.

Create a key and keep it out of your code

You create keys in the OpenAI API dashboard. Copy a new key right away and store it in a safe place, such as a password manager or your hosting provider's secret store.

The official SDKs read the key automatically from an environment variable named OPENAI_API_KEY. That means your source code never needs to contain it.

Terminal
# macOS or Linux, for the current terminal session
export OPENAI_API_KEY="paste-your-key-here"
POWERSHELL
# Windows PowerShell: saves the variable for new terminal windows
setx OPENAI_API_KEY "paste-your-key-here"

After setx, open a new terminal, because the current one does not see the change. Many projects load variables from a .env file during development. If you do that, add .env to .gitignore before your first commit.

TEXT
# .gitignore
.env
.env.*

If a key ever lands in a commit, a screenshot, a chat message or a log file, treat it as stolen. Revoke it in the dashboard and create a new one. Deleting the file is not enough, because version history keeps the old copy.

Check for the key without printing it

A program should fail early, with a clear message, when the key is missing. It should also never print the full key. This runnable helper shows both ideas. It uses a pretend environment, so no real key is involved.

Python Check configuration and mask the secret

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real program you would pass os.environ instead of fake_env. Passing the environment in as an argument also makes the function easy to test.

Install an SDK

OpenAI publishes official SDKs. For Python and for JavaScript or TypeScript, the package is called openai.

Terminal
# Python, preferably inside a virtual environment
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install openai

# Node.js
npm install openai

If virtual environments are new to you, read Python virtual environments. Record the SDK version in your dependency file, such as requirements.txt or package-lock.json. SDKs add features quickly, and a pinned version makes your builds repeatable.

Create the client

A client object holds your settings. With the environment variable in place, you need no arguments.

Python
# Read-only: run on your own computer
from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY
JavaScript
// Read-only: Node.js
import OpenAI from "openai";

const client = new OpenAI(); // reads OPENAI_API_KEY

Create one client and reuse it. Passing a key as a literal string, for example OpenAI(api_key="...") with the real value typed in, is how secrets end up in repositories. Passing a value that you read from a secret manager is fine.

You can also call the API with plain HTTPS. The key goes in the Authorization header as a bearer token. The SDKs add retries, timeouts and typed objects, so they are usually the easier choice.

Browsers and mobile apps

Code that runs on a user's device cannot keep a secret. The usual design is simple: the app talks to your server, your server checks who the user is and applies limits, and only then calls OpenAI.

flowchart LR
  A["Browser or mobile app"] --> B["Your server (holds the key)"]
  B --> C["OpenAI API"]

Your server is the only part that knows the key.

Realtime voice has a special feature for this: your server can create a short-lived client secret for the browser. You will meet it in speech and realtime.

Projects, service accounts and limits

API accounts are organized into an organization with projects inside it. OpenAI's production guidance recommends habits like these:

  • Use separate projects for development or staging and for production.
  • Give each application its own service account key, so it does not depend on one person's key.
  • Set an expiry date on keys and rotate them: create the new key, deploy it, confirm it works, then revoke the old one.
  • Set rate limits and spend limits for each project.

There are two kinds of spending controls to know about. A spend alert warns you when usage passes an amount you choose. A hard spend limit stops the affected API traffic when tracked spend reaches it. A hard limit protects your wallet, but it can also take your product offline, so choose the number carefully and read the current documentation first.

A short setup checklist

Step Done when
Key created in the right project The name says which app uses it
Key stored safely No key in any source file
.env ignored by version control git status does not list it
SDK installed and pinned Version is in your dependency file
Spend alert or limit set You would hear about a runaway loop

When setup fails

Most first errors are simple. An authentication error usually means the variable is missing, has extra spaces or quotes, or holds a revoked key. If you just used setx, open a new terminal. If an editor or a web server started before you set the variable, restart it. A ModuleNotFoundError usually means you installed the package into a different Python environment from the one running your script, so check which interpreter is active. Print whether the variable exists, never its value.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which environment variable do the official SDKs read by default?

    With OPENAI_API_KEY set, you can create the client without passing a key.
  2. 2. You accidentally committed a key to a repository. What should you do?

    The old value remains in history and may already have been copied. Only revoking it makes it useless.
  3. 3. Why use separate projects for staging and production?

    Separation means a test loop cannot use up the production limits, and access can be controlled for each.
  4. 4. What is the risk of a hard spend limit?

    It is a real stop, which protects your budget but affects your users.

Summary

  • An API key is a secret that spends your money; keep it out of code, logs and client apps.
  • The SDKs read OPENAI_API_KEY; install the openai package and pin its version.
  • Create one client and reuse it.
  • Use projects, service account keys, expiry dates and spend controls.
  • Revoke any key that may have leaked.

Next: Your First Request with the Responses API

Progres Anda disimpan di browser ini. Tidak perlu akun.