Skip to main contentSkip to navigation
[email protected]
Client AreaSupport
Hosting Mammoth
HostingMammothYour Data, Our Responsibility
Home
Solutions
Hosting Services
Store
Pricing
About
Blog
API
Contact

Stay Ahead of the Curve

Get the latest insights on cybersecurity, AI innovations, and enterprise data solutions delivered to your inbox.

Hosting Mammoth
HostingMammothEnterprise Solutions

Enterprise-grade data solutions. Hosting, recovery, cybersecurity, and AI-powered services for businesses worldwide.

[email protected]
Sun - Fri, 9:00am - 5:00pm

Services

  • Cloud Hosting
  • Data Recovery
  • Cybersecurity
  • Legal Support
  • MSP Services
  • Web Development
  • AI Services
  • Free Server Migration

Hosting

  • VPS Hosting (NVMe SSD)
  • VDS Hosting (NVMe)
  • Storage VPS (High SSD)
  • GPU Servers
  • Managed Services
  • Cloud Firewall
  • Load Balancer
  • One-Click Apps
  • n8n Hosting
  • Object Storage
  • FAQ

Company

  • Store
  • Pricing
  • About Us
  • Locations
  • Blog
  • Testimonials
  • Contact
  • Affiliate Program
  • White-Label
  • Terms of Service
  • Privacy Policy
  • Browser Cookies
  • SLA

Support

  • Client Area
  • Submit Ticket
  • Knowledge Base
  • Server Status
  • API Documentation

© 2026 Hosting Mammoth. All rights reserved.

Knowledge Base
Getting StartedAccount ManagementVPS HostingGPU ServersStorage VPSCloud FirewallLoad BalancerServer ManagementBilling & PaymentsSupport & TicketsAffiliate ProgramReseller ProgramMarketplace & Appsn8n HostingManaged ServicesServer MigrationAPI & DevelopersSecurityTroubleshootingGlossaryInstall Guides
  1. Home
  2. /
  3. Support
  4. /
  5. API & Developers
  6. /
  7. Api Code Examples Python
GUIDEAPI & Developers

API Code Examples — Python

3 min read

These Python examples demonstrate how to interact with the Data Mammoth API using the popular requests library. Each example is ready to use with minimal modification.

Setup

Install the requests library if you do not have it:

bash
pip install requests

Set up your API key as an environment variable:

bash
export DM_API_KEY="dm_key_abc123def456"

Base Configuration

python
import os
import requests

API_BASE = "https://api.datamammoth.com/v1" API_KEY = os.environ.get("DM_API_KEY")

headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" }

Server Management

List All Servers

python
response = requests.get(f"{API_BASE}/servers", headers=headers)
servers = response.json()["data"]

for server in servers: print(f"{server['name']} ({server['ip']}) - {server['status']}")

Get Server Details

python
server_id = "srv_abc123"
response = requests.get(f"{API_BASE}/servers/{server_id}", headers=headers)
server = response.json()["data"]

print(f"Name: {server['name']}") print(f"IP: {server['ip']}") print(f"Status: {server['status']}") print(f"Plan: {server['plan']}") print(f"OS: {server['os']}") print(f"CPU: {server['vcpus']} vCPUs") print(f"RAM: {server['ram_mb']} MB")

Create a Server

python
new_server = {
    "name": "web-production",
    "plan": "vps-standard",
    "region": "us-east",
    "os": "ubuntu-24.04",
    "hostname": "web01.example.com",
    "tags": ["production", "web"]
}

response = requests.post(f"{API_BASE}/servers", headers=headers, json=new_server)

if response.status_code == 201: server = response.json()["data"] print(f"Server created: {server['id']} ({server['ip']})") else: error = response.json()["error"] print(f"Error: {error['message']}")

Restart a Server

python
server_id = "srv_abc123"
action = {"action": "restart"}

response = requests.post( f"{API_BASE}/servers/{server_id}/actions", headers=headers, json=action )

if response.status_code == 200: print("Server restart initiated") else: print(f"Error: {response.json()['error']['message']}")

Billing

List Unpaid Invoices

python
response = requests.get(
    f"{API_BASE}/billing/invoices",
    headers=headers,
    params={"status": "unpaid"}
)
invoices = response.json()["data"]

for invoice in invoices: print(f"Invoice {invoice['number']}: ${invoice['total']:.2f} (due {invoice['due_date']})")

Check Account Balance

python
response = requests.get(f"{API_BASE}/billing/balance", headers=headers)
balance = response.json()["data"]
print(f"Account balance: ${balance['balance']:.2f} {balance['currency']}")

Support Tickets

Create a Support Ticket

python
ticket = {
    "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. "
               "Running htop shows MySQL as the top consumer."
}

response = requests.post(f"{API_BASE}/support/tickets", headers=headers, json=ticket)

if response.status_code == 201: ticket_data = response.json()["data"] print(f"Ticket created: {ticket_data['id']}") else: print(f"Error: {response.json()['error']['message']}")

Utility Functions

Paginated Fetching

python
def fetch_all(endpoint, params=None):
    """Fetch all pages of a paginated endpoint."""
    all_items = []
    page = 1
    params = params or {}

while True: params["page"] = page params["per_page"] = 50 response = requests.get( f"{API_BASE}/{endpoint}", headers=headers, params=params ) data = response.json() all_items.extend(data["data"])

if not data["meta"]["has_next"]: break page += 1

return all_items

Usage

all_servers = fetch_all("servers", {"status": "running"}) print(f"Total running servers: {len(all_servers)}")

Error Handling with Retry

python
import time

def api_request(method, endpoint, max_retries=3, **kwargs): """Make an API request with retry logic.""" url = f"{API_BASE}/{endpoint}"

for attempt in range(max_retries): response = requests.request(method, url, headers=headers, **kwargs)

if response.status_code == 429: retry_after = int(response.headers.get("Retry-After", 2 ** attempt)) print(f"Rate limited. Retrying in {retry_after}s...") time.sleep(retry_after) continue

if response.status_code >= 500: wait = 2 ** attempt print(f"Server error {response.status_code}. Retrying in {wait}s...") time.sleep(wait) continue

return response

raise Exception(f"Max retries exceeded for {endpoint}")

Usage

response = api_request("GET", "servers") servers = response.json()["data"]

Webhook Handler (Flask)

python
from flask import Flask, request, jsonify
import hmac
import hashlib

app = Flask(__name__) WEBHOOK_SECRET = "your_webhook_secret"

@app.route("/webhooks/datamammoth", methods=["POST"]) def handle_webhook(): signature = request.headers.get("X-Webhook-Signature", "") payload = request.get_data(as_text=True)

expected = hmac.new( WEBHOOK_SECRET.encode(), payload.encode(), hashlib.sha256 ).hexdigest()

if not hmac.compare_digest(f"sha256={expected}", signature): return jsonify({"error": "Invalid signature"}), 401

event = request.json print(f"Received event: {event['event']}")

if event["event"] == "server.status_changed": server = event["data"] print(f"Server {server['name']} changed to {server['new_status']}")

return jsonify({"status": "ok"}), 200

What to Do Next

  • API Code Examples — JavaScript/Node.js — JavaScript examples.
  • API Overview — Full API documentation.
  • API Error Codes & Handling — Error reference.
  • API Rate Limits & Best Practices — Optimize your usage.

Was this article helpful?

← Back to API & DevelopersBrowse all categories →

Still have questions?

Contact Support →Submit a Ticket