OpenAI API key setup for Python and Node
Published 2026-10-04 · Updated 2026-10-24
Current OpenAI keys start with sk-proj-, the older bare sk- format still works on old accounts but everything new is project-scoped. Here’s the two-minute setup.
Export the key
export OPENAI_API_KEY="sk-proj-..."
Add that line to ~/.zshrc or ~/.bashrc to keep it between sessions. In a project, use a .env file and a loader like python-dotenv, and make sure .env is in your .gitignore.
Python
pip install openai
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY automatically
resp = client.chat.completions.create(
model="gpt-6.1-mini",
messages=[{"role": "user", "content": "Say hello"}],
)
print(resp.choices[0].message.content)
If you’d rather pass the key explicitly: OpenAI(api_key=os.environ["OPENAI_API_KEY"]).
Node
npm install openai
import OpenAI from "openai";
const client = new OpenAI(); // reads process.env.OPENAI_API_KEY
const resp = await client.chat.completions.create({
model: "gpt-6.1-mini",
messages: [{ role: "user", content: "Say hello" }],
});
console.log(resp.choices[0].message.content);
Quick sanity check with curl
curl https://api.openai.com/v1/models \
-H "Authorization: Bearer $OPENAI_API_KEY"
A JSON list of models means the key is live. 401 means it’s wrong or revoked; 429 means you’re over quota.
Mistakes that bite everyone
- Quotes or whitespace. Pasting
sk-proj-... "with a stray space or smart quote gives you a 401 that looks like a dead key. Echo the variable and check its length. - Old-format code. Samples written before project keys sometimes split the key on
T3BlbkFJor assume a fixed length. Don’t parse the key, it’s opaque. - Wrong project. Project keys only see the models and limits of the project they were created in. A key that lists models but 403s on a specific model is a project permissions issue, not a bad key.
- Hardcoding. Even in a private repo, a committed key gets scraped eventually. Keep it in the environment.
Once the models call returns 200, the rest is ordinary API work, swap the model id, stream if you need it, and watch the usage dashboard if you care about spend.