JavaScript Guide¶
Examples use the native fetch API (Node.js 18+, browsers). For older Node.js versions, use node-fetch or axios.
Basic Request¶
const API_KEY = "YOUR_KEY";
const response = await fetch("https://dns.toolkitapi.io/v1/lookup?domain=toolkitapi.io&type=A", {
headers: {
"X-API-Key": API_KEY,
},
});
const data = await response.json();
console.log(data);
Reusable Helper¶
class ToolkitAPI {
constructor(apiKey, baseUrl) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
}
async request(method, path, { params, body } = {}) {
const url = new URL(`${this.baseUrl}${path}`);
if (params) {
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== null) {
url.searchParams.set(key, String(value));
}
}
}
const headers = { "X-API-Key": this.apiKey };
const options = { method, headers };
if (body !== undefined) {
headers["Content-Type"] = "application/json";
options.body = JSON.stringify(body);
}
const response = await fetch(url.toString(), options);
if (!response.ok) {
const error = await response.json();
throw new Error(`API error ${response.status}: ${error.detail}`);
}
return response.json();
}
get(path, params) {
return this.request("GET", path, { params });
}
post(path, body) {
return this.request("POST", path, { body });
}
}
// Usage
const dns = new ToolkitAPI("YOUR_KEY", "https://dns.toolkitapi.io/v1");
const result = await dns.get("/lookup", { domain: "toolkitapi.io", type: "A" });
Error Handling¶
try {
const response = await fetch("https://dns.toolkitapi.io/v1/lookup?domain=toolkitapi.io&type=A", {
headers: {
"X-API-Key": "YOUR_KEY",
},
});
if (!response.ok) {
const error = await response.json();
console.error(`Error ${response.status}: ${error.detail}`);
return;
}
const data = await response.json();
console.log(data);
} catch (err) {
console.error("Network error:", err.message);
}
File Uploads¶
const formData = new FormData();
formData.append("file", fileBlob, "photo.png");
formData.append("format", "webp");
const response = await fetch("https://image.toolkitapi.io/v1/image/convert", {
method: "POST",
headers: { "X-API-Key": "YOUR_KEY" },
body: formData,
});
const blob = await response.blob();