SDKsPHP SDK
PHP SDK
Connect PHP applications to nRouter using openai-php/client. Configure custom base URLs, manage API authentication, and access hundreds of top AI models.
Last updated
nRouter works with openai-php/client. Set the base URI to https://api.nrouter.ai/v1 and pass your sk-nrouter-... key — guardrails, caching, and rate-limits auto-apply from your org config.
Installation
composer require openai-php/clientSetup
<?php
require 'vendor/autoload.php';
$client = OpenAI::factory()
->withApiKey(getenv('NROUTER_API_KEY'))
->withBaseUri('https://api.nrouter.ai/v1')
->make();Chat Completion
<?php
$response = $client->chat()->create([
'model' => 'gpt-5.4-mini',
'messages' => [
['role' => 'user', 'content' => 'Hello!'],
],
]);
echo $response->choices[0]->message->content . "\n";Per-Request Overrides
openai-php/client forwards unknown keys, so nrouter_* fields work inline:
<?php
// Run a prompt template with variables
$response = $client->chat()->create([
'model' => 'gpt-5.5',
'messages' => [['role' => 'user', 'content' => 'Q1 revenue was $4.2M...']],
'nrouter_prompt_template_id' => 'your-summarizer-id',
'nrouter_prompt_variables' => ['language' => 'Spanish', 'max_length' => '100'],
]);
// Bypass cache for a single call
$response = $client->chat()->create([
'model' => 'gpt-5.5',
'messages' => [['role' => 'user', 'content' => 'What is the latest news?']],
'nrouter_cache' => false,
]);Guardrails are not among these keys. You assign them in the dashboard at key, team, or organization scope — the narrowest scope that mentions a guardrail wins — and they run automatically on every request that scope covers.
Error Handling
<?php
try {
$client->chat()->create([
'model' => 'gpt-5.5',
'messages' => [['role' => 'user', 'content' => 'My SSN is 123-45-6789']],
]);
} catch (\Exception $e) {
// "guardrail_blocked" — guardrail rejected the request
// "insufficient_credits" — top up to continue
echo "Error: {$e->getMessage()}\n";
}Response Headers
Every successful response carries:
x-nr-request-id— id for this call, and the join key for its spend rowx-nr-model— the model that actually served the requestx-nr-cost-status—exactwhen we priced the call,unpricedwhen we could notx-nr-request-cost— USD spend for this call. Absent whenx-nr-cost-statusisunpriced: nRouter never reports a cost of0for a call it could not pricex-nr-input-tokens,x-nr-output-tokens,x-nr-total-tokens— token counts as reported by the provider
Next Steps
- Python SDK — full deep-dive of all features
- cURL Examples — Inspect raw request/response shape
- Chat Completions API — Full API reference
Was this page helpful?