These JavaScript examples demonstrate how to use the Data Mammoth API with Node.js using the built-in fetch API (Node.js 18+) and the axios library. Each example is ready to adapt for your projects.
Setup
Using Built-in Fetch (Node.js 18+)
No additional installation required.
Using Axios
npm install axiosConfiguration
const API_BASE = "https://api.datamammoth.com/v1"; const API_KEY = process.env.DM_API_KEY;
const headers = { "Authorization":Bearer ${API_KEY}, "Content-Type": "application/json" };
Server Management
List All Servers (Fetch)
async function listServers() { const response = await fetch(${API_BASE}/servers, { headers }); const { data } = await response.json();data.forEach(server => { console.log(
${server.name} (${server.ip}) - ${server.status}); });return data; }
listServers();
List All Servers (Axios)
const axios = require("axios");const client = axios.create({ baseURL: API_BASE, headers: { "Authorization":
Bearer ${API_KEY}, "Content-Type": "application/json" } });async function listServers() { const { data } = await client.get("/servers"); data.data.forEach(server => { console.log(
${server.name} (${server.ip}) - ${server.status}); }); }
listServers();
Create a Server
async function createServer() { const response = await fetch(${API_BASE}/servers, { method: "POST", headers, body: JSON.stringify({ name: "web-production", plan: "vps-standard", region: "us-east", os: "ubuntu-24.04", hostname: "web01.example.com", tags: ["production", "web"] }) });
if (response.status === 201) { const { data } = await response.json(); console.log(Server created: ${data.id} (${data.ip})); } else { const { error } = await response.json(); console.error(Error: ${error.message}); } }
Perform Server Action
async function restartServer(serverId) { const response = await fetch(${API_BASE}/servers/${serverId}/actions, { method: "POST", headers, body: JSON.stringify({ action: "restart" }) });if (response.ok) { console.log("Server restart initiated"); } else { const { error } = await response.json(); console.error(
Error: ${error.message}); } }
restartServer("srv_abc123");
Billing
List Unpaid Invoices
async function getUnpaidInvoices() { const response = await fetch(${API_BASE}/billing/invoices?status=unpaid, { headers } ); const { data } = await response.json();data.forEach(invoice => { console.log(
Invoice ${invoice.number}: $${invoice.total.toFixed(2)} (due ${invoice.due_date})); });
return data; }
Support Tickets
Create a Ticket
async function createTicket() { const response = await fetch(${API_BASE}/support/tickets, { method: "POST", headers, body: JSON.stringify({ subject: "High CPU usage on web server", department: "technical", priority: "high", server_id: "srv_abc123", message: "CPU usage has been above 90% for the past 3 hours." }) });
if (response.status === 201) { const { data } = await response.json(); console.log(Ticket created: ${data.id}); } }
Utility Functions
Paginated Fetching
async function fetchAll(endpoint, params = {}) { const allItems = []; let page = 1; let hasNext = true;while (hasNext) { const queryParams = new URLSearchParams({ ...params, page: page.toString(), per_page: "50" });
const response = await fetch(
${API_BASE}/${endpoint}?${queryParams}, { headers }); const result = await response.json();allItems.push(...result.data); hasNext = result.meta.has_next; page++; }
return allItems; }
// Usage const allServers = await fetchAll("servers", { status: "running" }); console.log(Total running servers: ${allServers.length});
Error Handling with Retry
async function apiRequest(method, endpoint, body = null, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { const options = { method, headers }; if (body) options.body = JSON.stringify(body);const response = await fetch(
${API_BASE}/${endpoint}, options);if (response.status === 429) { const retryAfter = parseInt(response.headers.get("Retry-After") || Math.pow(2, attempt)); console.log(
Rate limited. Retrying in ${retryAfter}s...); await new Promise(resolve => setTimeout(resolve, retryAfter * 1000)); continue; }if (response.status >= 500) { const wait = Math.pow(2, attempt); console.log(
Server error. Retrying in ${wait}s...); await new Promise(resolve => setTimeout(resolve, wait * 1000)); continue; }return response; }
throw new Error(Max retries exceeded for ${endpoint}); }
Webhook Handler (Express.js)
const express = require("express"); const crypto = require("crypto");const app = express(); const WEBHOOK_SECRET = "your_webhook_secret";
app.post("/webhooks/datamammoth", express.json(), (req, res) => { const signature = req.headers["x-webhook-signature"]; const payload = JSON.stringify(req.body);
const expected = crypto .createHmac("sha256", WEBHOOK_SECRET) .update(payload) .digest("hex");
if (signature !==
sha256=${expected}) { return res.status(401).json({ error: "Invalid signature" }); }const event = req.body; console.log(
Received event: ${event.event});if (event.event === "server.status_changed") { const { name, new_status } = event.data; console.log(
Server ${name} changed to ${new_status}); }res.json({ status: "ok" }); });
app.listen(3000, () => console.log("Webhook server running on port 3000"));
What to Do Next
- API Code Examples — Python — Python examples.
- API Code Examples — PHP — PHP examples.
- API Overview — Full API documentation.
- Webhooks — Event notification setup.