惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
T
ThreatConnect
SecWiki News
SecWiki News
F
Future of Privacy Forum
AWS News Blog
AWS News Blog
C
Cisco Blogs
A
Arctic Wolf
Vercel News
Vercel News
The GitHub Blog
The GitHub Blog
Scott Helme
Scott Helme
V
V2EX
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
K
Kaspersky official blog
G
Google Developers Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
P
Privacy International News Feed
C
Cyber Attacks, Cyber Crime and Cyber Security
N
News | PayPal Newsroom
Schneier on Security
Schneier on Security
NISL@THU
NISL@THU
Microsoft Azure Blog
Microsoft Azure Blog
量子位
The Hacker News
The Hacker News
Stack Overflow Blog
Stack Overflow Blog
Security Latest
Security Latest
M
Microsoft Research Blog - Microsoft Research
Google Online Security Blog
Google Online Security Blog
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
I
InfoQ
Google DeepMind News
Google DeepMind News
Y
Y Combinator Blog
The Cloudflare Blog
Microsoft Security Blog
Microsoft Security Blog
Martin Fowler
Martin Fowler
Cisco Talos Blog
Cisco Talos Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Troy Hunt's Blog
F
Fox-IT International blog
S
Security @ Cisco Blogs
博客园 - 司徒正美
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Comments on: Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
LINUX DO - 最新话题
GbyAI
GbyAI
Project Zero
Project Zero
腾讯CDC
T
Tailwind CSS Blog

DEV Community

RAG 시스템 실전 구축 (v38) Beyond Pip Install: Why Your AI Agent Needs a "Hermetic" Life-Support System to Survive Resume Building using HTML & CSS SpecFlow: Multi-Agent SDD in Cursor (4 phases, /approve, single code writer) Running ASR for smart homes in the NPU of Intel processors "Building a CI/CD Pipeline From Scratch: A Practical Guide for Developers (with GitHub Actions)" SpecFlow: SDD multi-agente en Cursor (4 fases, /approve, un solo escritor de código) Adobe Commerce Cloud now costs $40k/year. We migrated from Adobe Commerce to Magento Open Source — here's the honest breakdown .klickd v4.0.0 — Portable AI memory with constraints, strict schemas, and test vectors We Trust Third Party Code, It’s Time to Trust AI Generated Code LangGraph 워크플로우 템플릿 (v38) Sustainable AI Starts with Efficient AI Find Remove duplicated files in Google Drive How to Detect GPU Waste in a Kubernetes Cluster The Privacy Bug in My First Chrome Extension (And How to Avoid It) Serverless Mental Models: What They Don't Tell You Before You Build Preventing GPT hallucination in automated content pipelines: how I structure Make.com flows with data injection Hmm, where were we? AI Visibility Tools, Math Proofs, and Stripped Guardrails Shape Developer Landscape How AI and Electronics Are Changing Healthcare Devices: The Future of Smart Healthcare Author: Shivam Wakade | Founder, PrivSR Making Claude Sound Like Optimus Prime Understanding Reinforcement Learning with Human Feedback Part 5: Training the Reward Model with Loss Functions Learning Progress Pt.20 How Secure LoRa Communication Devices Work: Building the Future of Private and Long-Range Connectivity Author: Shivam Wakade | Founder, PrivSR How I Rebuilt an RPG Map Editor with Rust, React, and WASM Building a System That Automates YouTube Post-Production Building a 100% Serverless Digital Asset Packager in the Browser Game Recommended AI What is Human-In-The-Loop (HITL)? Deep Dive: React Server Components in TanStack Start Migrating off Google Analytics: Umami vs Plausible vs Fathom Building a Portfolio That Actually Demonstrates Software Engineering Async/Await in JavaScript: From Callbacks to Clean Code (2026) Benchmarking LLM Structured Outputs Angular 21 Multiselect Dropdown: A Migration-Friendly Component with Live Functional Tests ShareBox v5 — GPU transcoding, Netflix-style grid, and why I don't need Plex anymore TOML Schema is live Handling Duplicate Shopify Webhook Events (And Why You Must) Original Kubernetes Dashboard — retired upstream, upgraded to Angular 21. لماذا أسست ترينافو للتجار العرب الذين تتجاهلهم المنصات الغربية Construyendo un recomendador de películas en Python: de los datos al modelo When APIs Lie: A Lesson in Defensive Debugging Pope Leo XIV's AI Encyclical: What Builders Must Know (2026) Donna v0.3.0 HTB — MonitorsFour | Writeup The Free Tool You Trust Is the One You Should Fear the Most HTB — MonitorsFour | Writeup Fr 97. Embeddings and Vector Search: Semantic Search That Works Deep Dive: Building "Gravity Paint" - A Tactile Physics Instrument with React, Matter.js, and p5.js ABAP Unit Testing with Test Doubles and Mocking Frameworks: A Senior Architects Guide to Isolating Dependencies in SAP S/4HANA LeetCode Solution: 5. Longest Palindromic Substring kovax-react 0.8: Tailwind v4 preset, FormField adapters, ColorModeScript, and Storybook I built an AI résumé tool that refuses to lie about your experience The hat Azure Entra ID User & Role Management — Step-by-Step Practical Guide With A Simple Excercise The AI-Native Company: How a Single Founder Can Build Global Organizations Powered by AWS and an Ecosystem of Artificial Intelligences Building a Lightweight Remote MCP Knowledge Base on Cloudflare Workers Why I built Trinavo for the MENA merchants Western platforms ignore The N+1 Query That Killed Our Database, And How I Fixed It Docstrings vs Markdown Docs: What Should Developers Actually Write? Training Data Provenance: The Manifest Diff That Explains the Hash Add SVGIcons MCP to Claude Code and Find SVG Icons from Your Terminal 3 CLI Tools You Can Buy with Crypto — No KYC, No Subscriptions COSS Weekly: OpenClaw competitor NanoClaw Raises $12M, Dust Raises $40M, Sonar Acquires Gitar, and more How to know if you actually need mobile proxies (without buying any) Building Cursor for Community: A Buildathon Built on Time Pressure How we built a PII masking layer for LLM APIs — local detection, reversible tokens, one line to integrate Why MLFQ Was Way Ahead of Its Time Add Runtime Limits to Claude Agent Workflows I Built a Prompt Injection Detector with 98% Recall on Unseen Attacks. Here's Why Data Beat Architecture. 8 Vite Config Options Every Developer Should Know (Vite 8) Feature Flags That Forgot to Leave Why Trust Infrastructure Is Becoming the Hidden Layer of Donation Platforms XyPriss: Rethinking Core Performance and Zero-Trust Architecture in Modern Backends Designing Configuration for Scalable Treasure Hunts SSH Login Delays: The 10-Second Wait That Drives Us Crazy Building Production Multi-Agent Workflows in n8n: What 50 Deployments Taught Us A 3-layer memory system that gives Claude Code persistent context across sessions. Trishul SNMP Suite 2.0.1: Better MIBs, Traps, and SNMP Labs How I built a production AI SaaS as a solo developer Auto-labelling 1.2M robotics frames with VLMs: a failover story India’s Laws Were Not Built for AI — And Courts Are Filling the Gap skill-insp: A Skill That Scores Other Skills Clprolf Minimalist Messaging in the Age of AI What's actually in a good .cursorrules file? I built 10 of them — here's what I learned Building Strong Python Basics – Loops, Functions and Logic How to Choose the Right Tech Stack for Your Project I built a free multi-tab JSON editor — here's what I learned HTTP Headers Every Developer Should Know (2026) Building Cross-Platform Digital Products: Challenges and Best Practices Data Privacy in the Age of AI: How Product Teams Can Build Trust with Users What Would WordPress Look Like If It Were Designed Today? Why Backup Success Does Not Mean Database Recoverability Local AI Office Assistant That Never Sends Your Documents to the Cloud Building TaskForge: Translating Enterprise Chaos into an Open-Source Scheduler Tesla P40 in a Homelab: 24GB of Inference on a Budget Llama 4: Meta's Latest — Scout, Maverick, and the MoE Revolution George Hotz called AI code 'slop.' He's half right. Como Construir um Fluxo de Trabalho Baseado em Engenharia de Prompt e Automação
How to Extract Your Full Team Hierarchy from HubSpot (the API doesn't expose it)
Felipe Rosas · 2026-05-26 · via DEV Community

If you manage a HubSpot portal with more than a handful of teams — multi-country orgs, dealer networks, agency rollups — you've probably tried at some point to programmatically get the parent–child relationship between teams.

And you've probably hit this wall:

GET /settings/v1/teams

Enter fullscreen mode Exit fullscreen mode

returns a flat array. No parentTeamId. No childTeams. Just a list, as if hierarchy didn't exist.

Meanwhile the HubSpot UI displays a beautiful nested tree. Where is it getting that from?

Spoiler: an internal endpoint that isn't part of the public API. Here's how to use it for one-off audits and exports — with all the caveats that come with relying on unofficial routes.


The problem in one paragraph

Public Settings API → flat list. UI → virtualized tree (only ~20 rows in the DOM at a time, so DOM scraping breaks the moment you scroll). No export button anywhere. If you need to reconcile owners ↔ teams ↔ countries, or audit which teams are orphaned, or build a flat lookup table for your data warehouse, you're stuck doing it by hand. Unless…


Step 1 — Find the internal endpoint

  1. Log into HubSpot.
  2. Navigate to Settings → Users & Teams → Teams.
  3. Open DevTools → Network tab → filter Fetch/XHR.
  4. Reload the page.
  5. Look for a request to /api/app-users/v1/teams with includeHierarchy=true in the query string.
  6. Right-click → Copy → Copy as fetch.

You'll get a fetch call with three things you need:

  • portalId — your portal ID.
  • x-hubspot-csrf-hubspotapi — session CSRF token (rotates often).
  • x-hs-locale — your locale token.

⚠️ This is an undocumented internal endpoint. HubSpot can change or remove it without notice. Don't put this in production. It's perfect for manual audits, scheduled monthly refreshes, or generating a reference table you re-upload when needed.


Step 2 — Fetch the hierarchy

Paste this in the DevTools Console (on the Teams settings page). Replace the placeholders with values from your copied request.

(async () => {
  const PORTAL_ID    = "{YOUR_PORTAL_ID}";
  const CSRF_TOKEN   = "{YOUR_CSRF_TOKEN}";
  const LOCALE_TOKEN = "{YOUR_LOCALE_TOKEN}";

  const url = `https://app.hubspot.com/api/app-users/v1/teams`
    + `?portalId=${PORTAL_ID}`
    + `&includeHierarchy=true`;

  const res = await fetch(url, {
    headers: {
      "accept": "application/json, text/javascript, */*; q=0.01",
      "x-hs-locale": LOCALE_TOKEN,
      "x-hubspot-csrf-hubspotapi": CSRF_TOKEN
    },
    credentials: "include"
  });

  if (!res.ok) {
    console.error(`❌ HTTP ${res.status} — CSRF probably expired. Refresh the page and grab a new token.`);
    return;
  }

  const raw = await res.json();
  console.log(`✅ Pulled ${raw.length} root teams`);

  // Strip user IDs, keep only structural fields
  const clean = (node) => ({
    id: node.id,
    name: node.name,
    parentTeamId: node.parentTeamId,
    children: (node.childTeams || []).map(clean)
  });
  const tree = raw.map(clean);

  const count = (nodes) => nodes.reduce((acc, n) => acc + 1 + count(n.children), 0);
  console.log(`🌳 Total teams: ${count(tree)}`);

  window.__teamsTree = tree;
  return tree;
})();

Enter fullscreen mode Exit fullscreen mode

If you hit a 401, your CSRF token expired — refresh the HubSpot page, grab the new token from the Network tab, re-run.


Step 3 — Flatten to CSV

Now you have a clean nested tree at window.__teamsTree. Most of the time, what you actually need is a flat table with derived fields (depth, parent name, leaf flag) you can upload to BigQuery, Snowflake, Sheets, whatever.

(() => {
  if (!window.__teamsTree) {
    console.error("Run the fetch script first.");
    return;
  }

  // Adapt this regex to your root team naming convention
  const COUNTRY_ROOT_PATTERN = /^{YOUR_ROOT_PREFIX}\s*-\s*/;

  const flatten = (nodes, parentName = null, country = null, depth = 0) => {
    return nodes.flatMap(n => {
      const isCountryRoot = depth === 0 && COUNTRY_ROOT_PATTERN.test(n.name);
      const currentCountry = isCountryRoot
        ? n.name.replace(COUNTRY_ROOT_PATTERN, "").trim()
        : country;

      return [
        {
          team_id: n.id,
          team_name: n.name,
          parent_team_id: n.parentTeamId,
          parent_team_name: parentName,
          country: currentCountry,
          depth,
          is_country_root: isCountryRoot,
          is_leaf: n.children.length === 0
        },
        ...flatten(n.children, n.name, currentCountry, depth + 1)
      ];
    });
  };

  const flat = flatten(window.__teamsTree);

  const headers = Object.keys(flat[0]);
  const escape = (v) => {
    if (v == null) return "";
    const s = String(v);
    return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  };
  const csv = [
    headers.join(","),
    ...flat.map(row => headers.map(h => escape(row[h])).join(","))
  ].join("\n");

  // Direct download (avoids clipboard focus issues)
  const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
  const a = document.createElement("a");
  a.href = URL.createObjectURL(blob);
  a.download = `hubspot_team_hierarchy_${new Date().toISOString().slice(0,10)}.csv`;
  document.body.appendChild(a);
  a.click();
  a.remove();

  console.log(`✅ Downloaded ${flat.length} rows`);
  console.table(flat.slice(0, 5));
})();

Enter fullscreen mode Exit fullscreen mode

File lands in your Downloads folder, named with today's date.


What you get

Nested JSON:

[
  {
    "id": 1234,
    "name": "Region A",
    "parentTeamId": null,
    "children": [
      {
        "id": 5678,
        "name": "Country X",
        "parentTeamId": 1234,
        "children": [
          { "id": 9012, "name": "Dealer Y", "parentTeamId": 5678, "children": [] }
        ]
      }
    ]
  }
]

Enter fullscreen mode Exit fullscreen mode

Flat CSV:

team_id team_name parent_team_id parent_team_name country depth is_country_root is_leaf
1234 Region A Region A 0 true false
5678 Country X 1234 Region A Region A 1 false false
9012 Dealer Y 5678 Country X Region A 2 false true

Why this matters

Once the hierarchy lives in a queryable place, things that were painful become one-liners:

  • Owner → team → country lookups without hardcoding country strings.
  • Orphan audits — root teams that don't follow your naming convention often expose governance gaps.
  • BI rollup reporting — join contacts/deals against the flat table in BigQuery, Looker, Tableau.
  • Leaf vs. structural teams — easy filter for customer-facing units only.
  • Duplicate detection at a glance.

Caveats (read these)

  • Undocumented endpoint. Not officially supported. Could break without warning.
  • Manual workflow. CSRF tokens are session-bound — this is not for cron jobs.
  • Read-only. Don't try to write changes through this.
  • Permissions apply. You need access to view Teams settings in your portal.

For anything programmatic and recurring, build on the public API and accept the flat-list limitation, or maintain your hierarchy mapping in a separate source of truth (a Google Sheet, a database table, a YAML in a repo — anything you control).


Source code

Full repo with scripts, sample output, and MIT license:

👉 github.com/feliperosasgp/hubspot-teams-hierarchy

PRs welcome — if you've got a cleaner regex pattern, a Python port, or a headless browser version that handles auth automatically, send it through.


A note to HubSpot

If anyone from HubSpot is reading: exposing parentTeamId (or an includeHierarchy=true flag) on the public /settings/v1/teams endpoint would unlock a meaningful class of governance and reporting workflows. The data is already there. Just let us reach it without the gymnastics. 🙏


If this saved you an afternoon, drop a 🦄 and let me know what you ended up using it for.