How to call and test the OpenAI API

Before you write code against the OpenAI API, it helps to see the raw requests and responses: which fields come back, how errors look, how long a call takes and how many tokens it uses. An API client is the fastest way to do that, and the same requests become a regression test for your prompts later.

Step 1: Key and environment

Create a key in the OpenAI dashboard, ideally in a separate project for testing so its spending can be limited and its key revoked on its own.

VariableValue
baseUrlhttps://api.openai.com/v1
openaiKeyyour key, marked as secret
modela model your project can use, from OpenAI's model list

On the collection's Authorization tab, choose Bearer token with {{openaiKey}}.

Keeping the model in a variable means you can compare models by switching environments, and update it in one place when a new one comes out.

Step 2: Your first request

HTTP
POST {{baseUrl}}/chat/completions
Content-Type: application/json

{
  "model": "{{model}}",
  "messages": [
    {"role": "system", "content": "You answer in one short sentence."},
    {"role": "user", "content": "What does HTTP status 429 mean?"}
  ]
}

The reply is in choices[0].message.content, and usage tells you how many tokens the call used:

JSON
{
  "id": "chatcmpl-…",
  "model": "…",
  "choices": [
    {"index": 0, "message": {"role": "assistant", "content": "It means you sent too many requests too quickly."}, "finish_reason": "stop"}
  ],
  "usage": {"prompt_tokens": 27, "completion_tokens": 12, "total_tokens": 39}
}

Step 3: Test what's stable

The text changes on every call, so don't assert on exact wording. Test the shape, the finish reason and the things you can rely on:

JavaScript
const body = pm.response.json();
const choice = body.choices[0];

pm.test('returns a completed answer', () => {
  pm.response.to.have.status(200);
  pm.expect(choice.finish_reason).to.equal('stop');
  pm.expect(choice.message.content).to.be.a('string').and.not.empty;
});

pm.test('answer is short, as instructed', () => {
  pm.expect(choice.message.content.length).to.be.below(300);
});

pm.test('mentions the key idea', () => {
  pm.expect(choice.message.content.toLowerCase()).to.match(/too many|rate/);
});

A finish_reason of length means the answer was cut off by a token limit, which is worth catching.

Step 4: JSON output

When your code parses the reply, ask for JSON and test that it parses:

Request body
{
  "model": "{{model}}",
  "response_format": {"type": "json_object"},
  "messages": [
    {"role": "system", "content": "Reply with JSON: {\"status\": number, \"meaning\": string}."},
    {"role": "user", "content": "HTTP 404"}
  ]
}
JavaScript
pm.test('reply is valid JSON with the expected fields', () => {
  const reply = JSON.parse(pm.response.json().choices[0].message.content);
  pm.expect(reply.status).to.equal(404);
  pm.expect(reply.meaning).to.be.a('string');
});

Step 5: Cost and latency

JavaScript
const usage = pm.response.json().usage;

pm.test('stays within the token budget', () => {
  pm.expect(usage.total_tokens).to.be.below(500);
});

pm.test('responds within 10 seconds', () => {
  pm.expect(pm.response.responseTime).to.be.below(10000);
});

console.log(`tokens: ${usage.total_tokens}, time: ${pm.response.responseTime} ms`);

Run the collection with a data file of prompts and you have a small, repeatable evaluation of your prompts across models. See Data-driven API tests.

Errors to know

StatusUsual cause
401Wrong or revoked key
404A model name your project can't use
429Rate limit, or the project is out of credit; the error body says which
400A malformed body, or a parameter the model doesn't support

Keep the key safe

The key can spend money. Keep it as a secret variable, never in the request itself, and use --env-var in CI:

Terminal
requestarium run-collection "OpenAI" --env OpenAI --env-var openaiKey=OPENAI_API_KEY

When you share the collection or generate code from a request, secrets stay masked. See Keeping API keys out of your collections.