Browse documentation

Java SDK

Use the official nRouter Java SDK with Maven Central dependencies, automated environment configuration, and full OpenAI API parity.

Last updated

The official nRouter Java SDK (ai.nrouter:nrouter-sdk) connects to https://api.nrouter.ai/v1 automatically, resolves your sk-nrouter-... key from the environment, and delivers full compatibility with standard OpenAI client libraries while applying your organization's server-side guardrails, smart routing, and real-time cost tracking.

Installation

Maven

Add to your pom.xml:

<dependency>
  <groupId>ai.nrouter</groupId>
  <artifactId>nrouter-sdk</artifactId>
  <version>2.2.1</version>
</dependency>

Gradle

Add to your build.gradle:

implementation 'ai.nrouter:nrouter-sdk:2.2.1'

Or build.gradle.kts:

implementation("ai.nrouter:nrouter-sdk:2.2.1")

Setup

Export your virtual API key in your environment:

export NROUTER_API_KEY="sk-nrouter-your-key-here"

Initialize the client with the official nRouter factory:

import ai.nrouter.sdk.NRouter;
import com.openai.client.OpenAIClient;

// Automatically reads NROUTER_API_KEY and targets https://api.nrouter.ai/v1
OpenAIClient client = NRouter.create();

You can also pass your API key explicitly:

OpenAIClient client = NRouter.builder()
    .apiKey("sk-nrouter-your-key-here")
    .build();

Chat Completion

import ai.nrouter.sdk.NRouter;
import com.openai.client.OpenAIClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import com.openai.models.ChatCompletionMessageParam;
import com.openai.models.ChatCompletionUserMessageParam;

public class NRouterExample {
    public static void main(String[] args) {
        OpenAIClient client = NRouter.create();

        ChatCompletion response = client.chat().completions().create(
            ChatCompletionCreateParams.builder()
                .model("gpt-5.4-mini")
                .addMessage(ChatCompletionMessageParam.ofUser(
                    ChatCompletionUserMessageParam.builder()
                        .content("Hello, nRouter!")
                        .build()
                ))
                .build()
        );

        System.out.println(response.choices().get(0).message().content());
    }
}

Per-Request Overrides

The Java SDK does not yet support extra_body fields natively. To pass nrouter_* fields per request (prompt templates, cache toggle), use java.net.http.HttpClient and include them in the raw JSON body:

{
  "model": "gpt-5.5",
  "messages": [{"role": "user", "content": "Summarize Q1 earnings..."}],
  "nrouter_prompt_template_id": "your-summarizer-id",
  "nrouter_prompt_variables": {"language": "Spanish"},
  "nrouter_cache": false
}

Guardrails are not part of this body. 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

try {
    client.chat().completions().create(/* ... */);
} catch (Exception e) {
    // "guardrail_blocked" — guardrail rejected the request
    // "insufficient_credits" — top up to continue
    System.out.println("Error: " + e.getMessage());
}

Response Headers

Every successful response carries:

  • x-nr-request-id — id for this call, and the join key for its spend row
  • x-nr-model — the model that actually served the request
  • x-nr-cost-statusexact when we priced the call, unpriced when we could not
  • x-nr-request-cost — USD spend for this call. Absent when x-nr-cost-status is unpriced: nRouter never reports a cost of 0 for a call it could not price
  • x-nr-input-tokens, x-nr-output-tokens, x-nr-total-tokens — token counts as reported by the provider

Next Steps

Was this page helpful?