Skip to content

Commit f62e84b

Browse files
Add basic fetch example extracted from wrapper repo
1 parent 9c1f09c commit f62e84b

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/**
2+
* Example: Using OpenRouter with raw fetch API
3+
*
4+
* This example demonstrates how to make direct HTTP requests to OpenRouter's API
5+
* using the native fetch API without any additional libraries.
6+
*
7+
* To run: bun examples/basic/example-basic-fetch.ts
8+
*/
9+
10+
// Make this a module
11+
export {};
12+
13+
// OpenRouter API endpoint
14+
const OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions";
15+
16+
// Type definitions for the API response
17+
interface ChatCompletionResponse {
18+
id: string;
19+
model: string;
20+
choices: Array<{
21+
index: number;
22+
message: {
23+
role: string;
24+
content: string;
25+
};
26+
finish_reason: string;
27+
}>;
28+
usage: {
29+
prompt_tokens: number;
30+
completion_tokens: number;
31+
total_tokens: number;
32+
};
33+
}
34+
35+
// Request payload following OpenAI-compatible chat completions format
36+
const requestBody = {
37+
model: "openai/gpt-4o-mini",
38+
messages: [
39+
{
40+
role: "user",
41+
content: "Write a haiku about TypeScript",
42+
},
43+
],
44+
};
45+
46+
console.log("=== OpenRouter Raw Fetch Example ===\n");
47+
console.log("Request:");
48+
console.log(`URL: ${OPENROUTER_API_URL}`);
49+
console.log("Model:", requestBody.model);
50+
console.log("Message:", requestBody.messages[0]?.content);
51+
console.log();
52+
53+
try {
54+
// Ensure API key is available
55+
if (!process.env.OPENROUTER_API_KEY) {
56+
throw new Error("OPENROUTER_API_KEY environment variable is not set");
57+
}
58+
59+
// Make the HTTP POST request to OpenRouter
60+
const response = await fetch(OPENROUTER_API_URL, {
61+
method: "POST",
62+
headers: {
63+
// Required: Authorization header with your API key
64+
"Authorization": `Bearer ${process.env.OPENROUTER_API_KEY}`,
65+
// Required: Content type for JSON payload
66+
"Content-Type": "application/json",
67+
// Optional but recommended: Identify your app
68+
"HTTP-Referer": "https://github.com/openrouter/examples",
69+
"X-Title": "OpenRouter Fetch Example",
70+
},
71+
body: JSON.stringify(requestBody),
72+
});
73+
74+
// Check if the request was successful
75+
if (!response.ok) {
76+
const errorText = await response.text();
77+
throw new Error(
78+
`HTTP error! status: ${response.status}, body: ${errorText}`
79+
);
80+
}
81+
82+
// Parse the JSON response
83+
const data = await response.json() as ChatCompletionResponse;
84+
85+
// Display the response
86+
console.log("Response:");
87+
console.log("Status:", response.status, response.statusText);
88+
console.log("Model used:", data.model);
89+
console.log("\nGenerated content:");
90+
console.log(data.choices[0]?.message?.content);
91+
console.log("\nUsage stats:");
92+
console.log("- Prompt tokens:", data.usage.prompt_tokens);
93+
console.log("- Completion tokens:", data.usage.completion_tokens);
94+
console.log("- Total tokens:", data.usage.total_tokens);
95+
96+
// Optional: Show raw response structure
97+
if (process.env.DEBUG) {
98+
console.log("\nFull response object:");
99+
console.log(JSON.stringify(data, null, 2));
100+
}
101+
} catch (error) {
102+
console.error("Error making request to OpenRouter:");
103+
104+
if (error instanceof Error) {
105+
console.error("Error message:", error.message);
106+
} else {
107+
console.error("Unknown error:", error);
108+
}
109+
110+
process.exit(1);
111+
}

0 commit comments

Comments
 (0)