Skip to content

Code Examples

Complete working examples in Python and JavaScript. All code on this page is tested in CI to stay in sync with the API.

response = requests.post(
    f"{BASE_URL}/shorten",
    headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
    json={"redirect_url": "https://example.com/landing"},
)
print(response.status_code)
print(response.json())
const basicResponse = await fetch(`${BASE_URL}/shorten`, {
  method: "POST",
  headers: {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    redirect_url: "https://example.com/landing",
  }),
});
const basicResult = await basicResponse.json();
console.log(basicResult);
curl -X POST "$BASE_URL/shorten" \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "redirect_url": "https://example.com/landing"
  }'
response = requests.post(
    f"{BASE_URL}/shorten",
    headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
    json={
        "redirect_url": "https://example.com/product",
        "data": {"sku": "WIDGET-42", "campaign": "summer-2026"},
        "webhooks": ["https://your-server.com/webhook"],
    },
)
print(response.status_code)
print(response.json())
const dataResponse = await fetch(`${BASE_URL}/shorten`, {
  method: "POST",
  headers: {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    redirect_url: "https://example.com/product",
    data: { sku: "WIDGET-42", campaign: "summer-2026" },
    webhooks: ["https://your-server.com/webhook"],
  }),
});
const dataResult = await dataResponse.json();
console.log(dataResult);
curl -X POST "$BASE_URL/shorten" \
  -H "X-API-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "redirect_url": "https://example.com/product",
    "data": {"sku": "WIDGET-42", "campaign": "summer-2026"},
    "webhooks": ["https://your-server.com/webhook"]
  }'

Scanalytics

Full Analytics

response = requests.get(
    f"{BASE_URL}/links/{SHORT_ID}/analytics",
    headers={"X-API-Key": API_KEY},
)
data = response.json()
print(f"Total hits: {data['total_hits']}")
print(f"Last 7 days: {data['last_7_days']}")
print(f"Top referrer: {data['referrers'][0]['label']}" if data["referrers"] else "No referrers")
const fullRes = await fetch(`${BASE_URL}/links/${SHORT_ID}/analytics`, {
  headers: { "X-API-Key": API_KEY },
});
const data = await fullRes.json();
console.log(`Total hits: ${data.total_hits}`);
console.log(`Last 7 days: ${data.last_7_days}`);
if (data.referrers.length) console.log(`Top referrer: ${data.referrers[0].label}`);
curl -s https://usnp.me/links/$SHORT_ID/analytics \
  -H "X-API-Key: $API_KEY" | python3 -m json.tool

Analytics Summary

response = requests.get(
    f"{BASE_URL}/links/{SHORT_ID}/analytics/summary",
    headers={"X-API-Key": API_KEY},
)
summary = response.json()
print(f"{summary['short_id']}: {summary['total_hits']} total, {summary['last_7_days']} this week")
const summaryRes = await fetch(`${BASE_URL}/links/${SHORT_ID}/analytics/summary`, {
  headers: { "X-API-Key": API_KEY },
});
const summary = await summaryRes.json();
console.log(`${summary.short_id}: ${summary.total_hits} total, ${summary.last_7_days} this week`);
curl -s https://usnp.me/links/$SHORT_ID/analytics/summary \
  -H "X-API-Key: $API_KEY" | python3 -m json.tool

Webhook Receiver

Verify the X-Webhook-Signature header to ensure payloads come from yousnap.me.

def verify_webhook_signature(payload_bytes: bytes, signature_header: str, secret: str) -> bool:
    """Verify the X-Webhook-Signature header matches the payload."""
    expected = hmac.new(secret.encode(), payload_bytes, hashlib.sha256).hexdigest()
    received = signature_header.removeprefix("sha256=")
    return hmac.compare_digest(expected, received)

Full receiver:

from fastapi import FastAPI, Request, HTTPException

receiver_app = FastAPI()
WEBHOOK_SECRET = "your-webhook-secret"

@receiver_app.post("/webhook")
async def handle_webhook(request: Request):
    body = await request.body()
    signature = request.headers.get("X-Webhook-Signature", "")

    if not verify_webhook_signature(body, signature, WEBHOOK_SECRET):
        raise HTTPException(status_code=401, detail="Invalid signature")

    payload = json.loads(body)
    print(f"Link clicked: {payload['short_id']}")
    print(f"Custom data: {payload.get('data')}")
    return {"status": "ok"}
function verifyWebhookSignature(payloadBytes, signatureHeader, secret) {
  const expected = crypto
    .createHmac("sha256", secret)
    .update(payloadBytes)
    .digest("hex");
  const received = signatureHeader.replace("sha256=", "");
  return crypto.timingSafeEqual(
    Buffer.from(expected, "hex"),
    Buffer.from(received, "hex")
  );
}

Full receiver:

const app = express();
const WEBHOOK_SECRET = "your-webhook-secret";

app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const signature = req.headers["x-webhook-signature"] || "";

  if (!verifyWebhookSignature(req.body, signature, WEBHOOK_SECRET)) {
    return res.status(401).json({ error: "Invalid signature" });
  }

  const payload = JSON.parse(req.body);
  console.log(`Link clicked: ${payload.short_id}`);
  console.log(`Custom data: ${JSON.stringify(payload.data)}`);
  res.json({ status: "ok" });
});

app.listen(3000, () => console.log("Webhook receiver on :3000"));