APIs·6 min read

How to use the OpenAI API (Python and Node quickstart)

A practical introduction to the OpenAI API covering authentication, the chat completions endpoint, streaming, error handling, and cost management, with working code in Python and JavaScript.

Get your API key

Create an account at platform.openai.com. Navigate to API Keys and create a new secret key. Store it in an environment variable, never hardcode it in your source code. Set it with: `export OPENAI_API_KEY=sk-...` on macOS/Linux, or add it to your `.env` file with `dotenv`.

OpenAI bills per token. New accounts receive $5 in free credit. Set a monthly spending limit in your account settings to prevent unexpected charges during development.

Install and make your first call (Python)

Install the SDK: `pip install openai`. Then: `from openai import OpenAI; client = OpenAI()`. The client automatically reads `OPENAI_API_KEY` from your environment.

Make a chat completion: `response = client.chat.completions.create(model='gpt-4o-mini', messages=[{'role': 'user', 'content': 'What is the capital of France?'}])`. Access the response text with `response.choices[0].message.content`.

First call in Node.js / TypeScript

Install: `npm install openai`. Then: `import OpenAI from 'openai'; const client = new OpenAI();`. The constructor reads `OPENAI_API_KEY` from `process.env`.

Call: `const response = await client.chat.completions.create({ model: 'gpt-4o-mini', messages: [{ role: 'user', content: 'Hello!' }] }); console.log(response.choices[0].message.content);`

Streaming responses

Streaming shows tokens as they are generated, making applications feel much more responsive. In Python: `stream = client.chat.completions.create(model='gpt-4o-mini', messages=[...], stream=True)`. Then `for chunk in stream: print(chunk.choices[0].delta.content or '', end='', flush=True)`.

In Node.js: `const stream = await client.chat.completions.stream({...})`. Iterate with `for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || '') }`. Call `await stream.finalChatCompletion()` to get the complete response object including usage stats.

Handle errors and manage costs

Always wrap API calls in try-except (Python) or try-catch (JS). Handle `openai.RateLimitError` with exponential backoff, wait 1s, then 2s, then 4s between retries. Handle `openai.AuthenticationError` by checking your API key. Handle `openai.BadRequestError` for content policy violations.

Track token usage from `response.usage.total_tokens`. GPT-4o-mini costs $0.15 per million input tokens and $0.60 per million output tokens (as of mid-2025), cheap enough for most applications. Set `max_tokens` to limit output length and prevent runaway costs on edge cases.