Browse documentation

Java SDK

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

The official nRouter Java SDK delivers enterprise-grade, thread-safe bindings for the unified AI gateway with full OpenAI API parity.

Connect to https://api.nrouter.ai/v1 using your virtual NROUTER_API_KEY:

  • Maven Central distribution: Depend on ai.nrouter:nrouter-sdk:3.1.2 for Maven or Gradle.
  • Drop-in OpenAI client: Static NRouter.create() returns configured OpenAIClient instances.

Installation

Add the dependency to your pom.xml:

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

Gradle: implementation 'ai.nrouter:nrouter-sdk:3.1.2'.

Setup & Chat Completion

Set your virtual API key in your environment:

export NROUTER_API_KEY="sk-nrouter-xxxxxxxxxxxx"

Initialize the client with automatic environment resolution:

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 Main {
    public static void main(String[] args) {
        // Reads NROUTER_API_KEY and targets https://api.nrouter.ai/v1
        OpenAIClient client = NRouter.create();

        ChatCompletion response = client.chat().completions().create(
            ChatCompletionCreateParams.builder()
                .model("gpt-5.4-mini")
                .addMessage(ChatCompletionMessageParam.ofUser(
                    ChatCompletionUserMessageParam.builder().content("Explain JVM garbage collection.").build()
                ))
                .build()
        );

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

Streaming Responses

Stream tokens in real-time via Server-Sent Events (SSE):

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

public class StreamMain {
    public static void main(String[] args) {
        OpenAIClient client = NRouter.create();
        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
            .model("claude-haiku-4-5-20251001")
            .addMessage(ChatCompletionMessageParam.ofUser(
                ChatCompletionUserMessageParam.builder().content("Write a haiku.").build()
            ))
            .build();

        client.chat().completions().createStreaming(params).stream().forEach(chunk -> {
            chunk.choices().get(0).delta().content().ifPresent(System.out::print);
        });
        System.out.println();
    }
}

Error Handling

Errors map to standard HTTP status codes documented in Errors & Rate Limits and surface as OpenAI Java exceptions:

import com.openai.errors.OpenAIException;
import com.openai.errors.BadRequestException;
import com.openai.errors.AuthenticationException;
import com.openai.errors.RateLimitException;

try {
    ChatCompletion response = client.chat().completions().create(params);
} catch (BadRequestException e) {
    System.err.println("Bad request / guardrail violation: " + e.getMessage());
} catch (AuthenticationException e) {
    System.err.println("Authentication failed: Verify NROUTER_API_KEY.");
} catch (RateLimitException e) {
    System.err.println("Rate limit reached. Apply exponential backoff.");
} catch (OpenAIException e) {
    System.err.println("Gateway error: " + e.getMessage());
}

Next Steps

Was this page helpful?