Pull Component Data from the Figma API
Programmatically access your Figma components, styles, and variables. Build audits, reports, and automations on real data.
What you will need
Professional plan or above for full API access. The variables endpoint requires Professional or Organization.
Generated from your Figma settings. Used in the X-Figma-Token header on every request.
Required to run the fetch scripts in this workflow.
Found in the URL: figma.com/design/[FILE_KEY]/your-file-name. You will need it for every API call.
Time to generate the token, write the script, and verify your first audit output.
Why This Matters for Your Design System
“How many components do we actually have?” I asked this question in a meeting last year. Three people gave three different answers. One counted pages in Figma. One counted entries in Notion. One guessed.
The Figma REST API answers that question in 200 milliseconds. One request returns every component, every style, every variable in your file, with metadata attached. This workflow shows you how to go from “I think we have about 80 components” to an exact, automated inventory you can run any time you want.
Step 1: Generate a Figma Personal Access Token
The API requires authentication. You need a Personal Access Token (PAT) to prove you have permission to read the file.
- Open Figma and click your profile avatar in the top left
- Go to Settings
- Scroll down to “Personal access tokens”
- Click “Generate new token”
- Give it a descriptive label, like
api-component-audit - Copy the token immediately. Figma only shows it once.
Store the token in an environment variable on your machine so you do not have to paste it into scripts directly:
export FIGMA_TOKEN="figd_your-token-here"
Add this line to your ~/.zshrc or ~/.bashrc file so it persists across terminal sessions.
Why this step matters: The token is your API key. Without it, every request returns a 403 error. Storing it as an environment variable (instead of hardcoding it in a script) keeps it out of your Git history, which is a basic security practice.
Step 2: Find Your File Key
Every Figma file has a unique key embedded in its URL. When you open a file, the URL looks like:
https://www.figma.com/design/ABC123xyz/My-Design-System
The file key is the part after /design/ and before the next /. In this example, it is ABC123xyz.
Save this key. You will use it in every API request.
Why this step matters: The file key identifies which Figma file the API should read. If you have multiple files (a component library, a documentation file, a playground), each has its own key. Most teams start with their main component library file.
Step 3: Fetch Component Data
Create a script to pull all components from your file. Save this as fetch-components.js:
const FILE_KEY = 'YOUR_FILE_KEY';
const TOKEN = process.env.FIGMA_TOKEN;
async function fetchComponents() {
const response = await fetch(
`https://api.figma.com/v1/files/${FILE_KEY}/components`,
{
headers: {
'X-Figma-Token': TOKEN,
},
}
);
const data = await response.json();
if (data.error) {
console.error('API Error:', data.message);
return;
}
const components = data.meta.components;
console.log(`Found ${components.length} components\n`);
// Summary statistics
const withDescription = components.filter(c => c.description).length;
const withoutDescription = components.length - withDescription;
console.log(`With description: ${withDescription}`);
console.log(`Without description: ${withoutDescription}`);
console.log(`Documentation coverage: ${Math.round(
(withDescription / components.length) * 100
)}%\n`);
// List all components
components.forEach(component => {
const status = component.description ? '✓' : '✗';
console.log(` ${status} ${component.name}`);
});
}
fetchComponents();
Run it:
node fetch-components.js
You will see output like:
Found 127 components
With description: 89
Without description: 38
Documentation coverage: 70%
✓ Button/Primary
✓ Button/Secondary
✗ Button/Ghost
✓ Card/Default
✗ Card/Compact
...
Why this step matters: This is your component inventory, generated in seconds instead of hours. The documentation coverage percentage alone is valuable. It tells you exactly how much of your system is documented and gives you a prioritized list of what needs attention.
Step 4: Fetch Styles and Variables
Components are just one piece of the picture. Your design system also defines styles (colors, text, effects) and variables. Fetch those too.
Add these functions to your script:
async function fetchStyles() {
const response = await fetch(
`https://api.figma.com/v1/files/${FILE_KEY}/styles`,
{
headers: { 'X-Figma-Token': TOKEN },
}
);
const data = await response.json();
const styles = data.meta.styles;
console.log(`\n--- Styles ---`);
console.log(`Total: ${styles.length}`);
// Group by type
const grouped = {};
styles.forEach(style => {
const type = style.style_type;
if (!grouped[type]) grouped[type] = [];
grouped[type].push(style);
});
Object.entries(grouped).forEach(([type, items]) => {
console.log(` ${type}: ${items.length}`);
});
}
async function fetchVariables() {
const response = await fetch(
`https://api.figma.com/v1/files/${FILE_KEY}/variables/local`,
{
headers: { 'X-Figma-Token': TOKEN },
}
);
const data = await response.json();
const variables = Object.values(data.meta.variables);
const collections = Object.values(data.meta.variableCollections);
console.log(`\n--- Variables ---`);
console.log(`Collections: ${collections.length}`);
console.log(`Total variables: ${variables.length}`);
collections.forEach(collection => {
const collVars = variables.filter(
v => v.variableCollectionId === collection.id
);
console.log(` ${collection.name}: ${collVars.length} variables`);
});
}
Run the expanded script and you get a complete picture:
Found 127 components
Documentation coverage: 70%
--- Styles ---
Total: 45
FILL: 22
TEXT: 18
EFFECT: 5
--- Variables ---
Collections: 3
Primitives: 48 variables
Semantic: 32 variables
Component: 15 variables
Why this step matters: Knowing that you have 48 primitive variables and 32 semantic variables tells you a lot about your token architecture. Are those ratios healthy? Are you missing semantic mappings for some primitives? This data drives strategic decisions about where to invest your design system effort.
Step 5: Build Recurring Reports
A one-time audit is useful. A recurring report is powerful. Turn your script into something that runs regularly and outputs structured data.
Save results as JSON for further processing:
async function generateReport() {
const [components, styles, variables] = await Promise.all([
fetchComponentsData(),
fetchStylesData(),
fetchVariablesData(),
]);
const report = {
generatedAt: new Date().toISOString(),
fileKey: FILE_KEY,
summary: {
totalComponents: components.length,
documentedComponents: components.filter(c => c.description).length,
totalStyles: styles.length,
totalVariables: variables.length,
},
components: components.map(c => ({
name: c.name,
description: c.description || null,
containingFrame: c.containing_frame?.name || null,
})),
};
const fs = await import('fs');
fs.writeFileSync(
`audit-report-${new Date().toISOString().split('T')[0]}.json`,
JSON.stringify(report, null, 2)
);
console.log('Report saved.');
}
generateReport();
You can schedule this script to run weekly so the report stays fresh.
Why this step matters: Design systems are living products. Their health changes over time. A weekly report showing component count, documentation coverage, and variable usage trends gives you the data to advocate for resources, prioritize work, and demonstrate progress to stakeholders.
What You Get
- A complete inventory of every component, style, and variable in your Figma file.
- Documentation coverage metrics that show exactly what needs attention.
- Structured data you can feed into dashboards, spreadsheets, or other tools.
- Repeatable audits that take seconds instead of hours.
- A foundation for automation. Once you can read your design system data, you can build alerts, dashboards, and quality checks on top of it.
Common Pitfalls
- Rate limiting. The Figma API has rate limits. If you are making many requests in a short time, add a small delay between calls. For most audit scripts, this is not an issue.
- Large files timing out. If your Figma file is very large (1,000+ components), the file endpoint might time out. Use the component-specific endpoint (
/v1/files/:key/components) instead of fetching the entire file structure. - Token expiration. Figma PATs do not expire by default, but you can set them to. If your script suddenly stops working, check whether the token is still valid.
- Variables API access. The variables endpoint requires a Figma Professional plan or above. If you are on a free or Starter plan, you can still fetch components and styles but not variables.
Generate a real inventory of your Figma library
-
Generate the token, run the first fetch, count the gaps
Generate a Figma Personal Access Token from your Figma settings. Export it as
FIGMA_TOKENin your shell. Grab your file key from the library URL. Save thefetch-components.jsscript from Step 3, swap in your file key, and run:node fetch-components.js- The script prints an exact component count, not a rounded guess
- Every component appears with either a check or a cross for description
- You know the documentation coverage percentage for your library
- At least three undocumented components are named and easy to point at
-
Save the JSON report and share it with one stakeholder
Extend the script with the
generateReportfunction from Step 5 so it writesaudit-report-YYYY-MM-DD.jsonto disk. Commit the JSON to your repo. Send the file to your design system lead, your PM, or whoever asks “how is the library doing”.- A timestamped JSON report exists in your repo
- The report has a
summaryobject with total components, documented components, total styles, total variables - One real stakeholder received the file and now has a concrete number to work with
- You can rerun the script any time without touching the code
Finished this lesson?
Mark it complete to track your progress through "Agentic Design Systems".
The guides alone saved me a full day of work every sprint.
- All guides, prompts, and templates
- Starter kits and templates
- New content every week
- Priority support