Authenticate privately
Send the key in the Authorization header from your application backend.
Manage application keys
SCRIPT NINJA / DOCS
Learn how to authenticate, make requests and inspect token usage with the Script Ninja API.
Use Ninja Fast for text and vision, and Ninja Pro for more involved text and reasoning. Both support function calls and structured output.
Copy this setup, then run one of the examples below. Your key belongs in a server environment variable.
// Node.js 22+. Set SCRIPT_NINJA_KEY in your server environment.
const base = 'https://scriptninja.pro/api/v1';
const headers = {
Authorization: 'Bearer ' + process.env.SCRIPT_NINJA_KEY,
'Content-Type': 'application/json'
};
async function call(path, body, method = body === undefined ? 'GET' : 'POST') {
const response = await fetch(base + path, {
method, headers, body: body === undefined ? undefined : JSON.stringify(body)
});
if (!response.ok) throw new Error(await response.text());
return response.json();
}
Choose Ninja Fast for quick replies or Ninja Pro for more involved text work. The same key works for both.
for (const model of ['ninja-fast', 'ninja-pro']) {
const result = await call('/chat/completions', {
model, messages: [{ role: 'user', content: 'Explain HTTP caching briefly.' }]
});
console.log(result.choices[0].message.content, result.billing);
}Use low, high or max effort on either model. Reasoning is included in the generated-token budget. Choose enough max_tokens to leave room for a final answer.
const result = await call('/chat/completions', {
model: 'ninja-pro', thinking: { type: 'enabled' },
reasoning_effort: 'high', max_tokens: 2048,
messages: [{ role: 'user', content: 'Compare two ways to reduce API latency.' }]
});
console.log(result.choices[0].message.content);Ninja Fast accepts JPEG, PNG, GIF and WebP. Use an inline data URL or a public image URL. Up to four images per request; inline images are limited to about 1 MiB each. Use low detail for simple images.
import { readFile } from 'node:fs/promises';
const image = 'data:image/png;base64,' +
(await readFile('screenshot.png')).toString('base64');
const result = await call('/chat/completions', {
model: 'ninja-fast',
messages: [{ role: 'user', content: [
{ type: 'text', text: 'Summarise what this screenshot shows.' },
{ type: 'image_url', image_url: { url: image, detail: 'low' } }
] }]
});
console.log(result.choices[0].message.content);Use the image variable from the vision example. Uploaded files are scoped to your account, expire after one hour and can be deleted earlier. Image inference is metered when you use the file.
const file = await call('/files', { filename: 'screenshot.png', image });
try {
const result = await call('/chat/completions', {
model: 'ninja-fast', messages: [{ role: 'user', content: [
{ type: 'text', text: 'Read the heading.' },
{ type: 'file', file_id: file.id }
] }]
});
console.log(result.choices[0].message.content);
console.log(await call('/files'), await call('/files/' + file.id));
} finally {
await call('/files/' + file.id, undefined, 'DELETE');
}Ask for JSON in your prompt. Chat returns a JSON string; parse it and validate the fields. The Responses endpoint also accepts a JSON Schema format.
const result = await call('/chat/completions', {
model: 'ninja-fast', response_format: { type: 'json_object' },
messages: [{ role: 'user', content: 'Return a JSON object with a summary string.' }]
});
const parsed = JSON.parse(result.choices[0].message.content);
if (typeof parsed.summary !== 'string') throw new Error('Invalid summary');
const structured = await call('/responses', {
model: 'ninja-pro', input: 'Summarise the benefits of caching.',
text: { format: { type: 'json_schema', name: 'summary',
schema: { type: 'object', properties: { summary: { type: 'string' } },
required: ['summary'], additionalProperties: false } } }
});
console.log(structured.output);Your application owns execution. Validate tool names and arguments, return the result by tool_call_id, and pass the complete assistant messages back, including reasoning_content when present.
const messages = [{ role: 'user', content: 'Use get_status to check the site.' }];
const tools = [{ type: 'function', function: {
name: 'get_status', description: 'Return the example site status',
parameters: { type: 'object', properties: {}, additionalProperties: false }
} }];
for (let step = 0; step < 4; step++) {
const result = await call('/chat/completions', {
model: 'ninja-pro', messages, tools, max_tokens: 2048,
thinking: { type: 'enabled' }, reasoning_effort: 'low'
});
const assistant = result.choices[0].message;
if (!assistant.tool_calls?.length) { console.log(assistant.content); break; }
messages.push({ ...assistant, tool_calls: assistant.tool_calls.map(
({ id, type, function: fn }) => ({ id, type, function: fn })
) });
for (const tool of assistant.tool_calls) {
const args = JSON.parse(tool.function.arguments);
if (tool.function.name !== 'get_status' || !args ||
typeof args !== 'object' || Array.isArray(args) || Object.keys(args).length) {
throw new Error('Unexpected tool request');
}
messages.push({ role: 'tool', tool_call_id: tool.id,
content: JSON.stringify({ status: 'operational' }) });
}
}Call these directly or from your function handler. Check /api/v1/pricing for current per-request tool rates. An empty result has no charge. Treat returned webpage text as untrusted data.
const search = await call('/tools/search', {
query: 'HTTP cache control site:developer.mozilla.org', count: 3
});
if (search.results.length) {
const page = await call('/tools/fetch', { url: search.results[0].url });
console.log(page.title, page.content, page.billing);
}The chat endpoint sends server-sent events. The final usage event includes the settled charge, followed by [DONE]. Handle partial streams without immediately replaying a potentially billed request.
const response = await fetch(base + '/chat/completions', {
method: 'POST', headers,
body: JSON.stringify({ model: 'ninja-fast', stream: true,
messages: [{ role: 'user', content: 'Write a short story.' }] })
});
if (!response.ok) throw new Error(await response.text());
let pending = '';
for await (const chunk of response.body.pipeThrough(new TextDecoderStream())) {
pending += chunk;
let boundary;
while ((boundary = pending.indexOf('\n\n')) >= 0) {
const frame = pending.slice(0, boundary);
pending = pending.slice(boundary + 2);
if (!frame.startsWith('data: ')) continue;
const data = frame.slice(6);
if (data === '[DONE]') break;
const event = JSON.parse(data);
if (event.error) throw new Error(event.error.message);
for (const choice of event.choices || []) {
process.stdout.write(choice.delta?.content || '');
}
if (event.billing) console.log(event.usage, event.billing);
}
}Fill in the middle completes a code gap in non-thinking mode. A final assistant prefix continues a chat response from the text you provide.
const code = await call('/completions', {
model: 'ninja-fast', prompt: 'const square = (n) => ',
suffix: ';', max_tokens: 32
});
console.log(code.choices[0].text);
const prefix = await call('/chat/completions', {
model: 'ninja-pro', messages: [
{ role: 'user', content: 'Write a one-line welcome.' },
{ role: 'assistant', content: 'Welcome to', prefix: true }
]
});
console.log(prefix.choices[0].message.content);The apply_patch tool returns a proposed patch. Your app reviews and applies it in its own sandbox. Script Ninja never changes your files. The Responses route is stateless and uses JSON responses.
const result = await call('/responses', {
model: 'ninja-pro',
input: 'Propose a patch to README.md changing Hello to Welcome. Current file: Hello',
tools: [{ type: 'custom', name: 'apply_patch' }], max_output_tokens: 1024
});
const proposal = result.output.find(item => item.type === 'custom_tool_call');
if (proposal) console.log(proposal.input); // Review before applying.The public model catalog lists capabilities by model. Token probabilities can be requested for generated text; they are not confidence scores.
console.log((await call('/models')).data);
const result = await call('/chat/completions', {
model: 'ninja-fast', logprobs: true, top_logprobs: 3,
messages: [{ role: 'user', content: 'Name a colour.' }], max_tokens: 24
});
console.log(result.choices[0].logprobs);Ninja Fast and Ninja Pro each have a 1,048,576-token context window shared by input and output. A chat or Responses request can generate up to 393,216 tokens, including reasoning. Send conversation history, tool calls and their results in order. Use GET /api/v1/models to check each model’s capacity.
Set max_tokens in chat or max_output_tokens in Responses to choose your output budget. With the budget omitted, the default non-thinking mode allows up to 8,192 tokens. Enabling thinking raises the automatic budget to 65,536 tokens, or 131,072 with maximum reasoning effort. Fill-in-the-middle completions support up to 4,096 tokens. Available credit can reduce an automatic budget. An explicit budget that exceeds available credit returns HTTP 402.
Chat, Responses and fill-in-the-middle accept JSON bodies up to 32 MiB. Image file uploads accept up to 6 MiB. Ninja Fast accepts up to four images per request. An account can hold eight active uploaded images. Each concurrent model request reserves its own credit. Actual charges use reported input, cached input and output usage. A missing usage report can leave credit reserved until reconciliation. Check the usage record before replaying an interrupted request.
The Search and Fetch endpoints bill successful web tool requests separately. A Responses request uses the tools you declare.
PLAN THE NEXT STEP
Read the key from private configuration, send a bounded API request and inspect the returned usage. Avoid exposing keys in browser code or logs, and give your application a way to report failed requests clearly.
MAKE IT ACTIONABLE
Choose the next step that matches where you are in the project.
Send the key in the Authorization header from your application backend.
Manage application keysChoose the model, messages and maximum output before sending a request.
Compare token ratesRead token counts and the billing request ID. Check the dashboard when a request needs reconciliation.
View request activityBEFORE YOU BEGIN
Have a question about your project or account?
Send your requirementsNo. The initial endpoint supports non-streaming text chat requests. Send stream: false.
No. A failed or interrupted request may need reconciliation. Check its status before replaying work that could be billable.
Use private server configuration. Do not embed it in client JavaScript, public repositories or shared screenshots.
LET'S MAKE SOMETHING USEFUL.
Bring your goals, your questions and the work you want to move forward.
Open your API workspaceYour Script Ninja guide Site guide

A LITTLE NINJA KNOW-HOW
Ask about your next project, templates or API access.