How to Build a Real Estate Submarket Trend Analyzer with n8n and GPT-4

New to n8n? Start with our step-by-step setup guide, then come back to build this workflow.

Most real estate investors miss the best deals not because they lack capital. It’s because they can’t process market signals fast enough. By the time MLS data, public records, demographic shifts, and macroeconomic indicators are manually compiled into a report, the window has already closed. This n8n workflow solves that: every morning at 6 AM, it pulls all four data sources simultaneously, feeds them to a GPT-4o AI agent, scores each submarket on a 0 to 100 investment scale, and fires off alerts to your acquisition team via Gmail and Slack, automatically, without anyone lifting a finger.

Prefer to skip the setup? Grab the ready-made template → and be running in under 10 minutes.

What You’ll Build

  1. A scheduled n8n workflow that runs every morning at 6:00 AM and fetches live data from your MLS API, public property records database, a demographic data provider, and a macroeconomic indicator source, all four in parallel.
  2. An AI agent powered by GPT-4o that ingests all the aggregated data, calculates investment scores for each submarket, identifies the top opportunity, and predicts value growth over the next 12 months.
  3. An automated alert system that sends a rich HTML email to your acquisition team and posts a formatted Slack message to your investor channel whenever a submarket scores above your defined threshold (default: 75 out of 100).
  4. A fully configurable setup where you define the target market (e.g., “Austin, TX”), the investment threshold, and the recipients, no code changes needed.

How It Works: The Big Picture

The workflow is a single linear pipeline with one parallel fan-out. It starts on a daily schedule, fans out to four simultaneous HTTP requests, merges the results, runs them through a GPT-4o AI agent equipped with a financial calculator and a market research tool, checks the top score against your threshold, and routes high-quality opportunities to both Gmail and Slack.

┌────────────────────────────────────────────────────────────────────────────┐
│  AI REAL ESTATE SUBMARKET TREND ANALYZER                                   │
│                                                                            │
│  [Schedule: 6 AM] ──► [Config Node]                                        │
│                              │                                             │
│          ┌───────────────────┼───────────────┬───────────────┐             │
│          ▼                   ▼               ▼               ▼             │
│   [Fetch MLS]   [Fetch Public Records] [Fetch Demo-] [Fetch Macro-]        │
│                                         graphics]    economics]            │
│          └───────────────────┴───────────────┴───────────────┘             │
│                              │                                             │
│                  [Aggregate All Market Data]                               │
│                              │                                             │
│   [GPT-4o LLM] ──►  [Investment Opportunity Analyzer Agent]               │
│   [Calculator] ──►          │ ◄── [Structured Output Parser]              │
│   [Mkt Tool]   ──►          │                                             │
│                              ▼                                             │
│                 [Check Score ≥ Threshold (75)]                             │
│                         ▼ YES                                              │
│              ┌──────────┴──────────┐                                       │
│              ▼                     ▼                                       │
│    [Email Acquisition Team]  [Notify on Slack]                             │
└────────────────────────────────────────────────────────────────────────────┘

What You’ll Need

  • n8n: self-hosted or n8n Cloud (any recent version)
  • OpenAI API key: for GPT-4o access (paid plan required)
  • MLS data API: any provider with a REST endpoint (e.g., ATTOM, PropStream)
  • Public records API: ATTOM Property API or CoreLogic
  • Demographic data API: Census Bureau API (free) or Esri ArcGIS
  • Macroeconomic data API: FRED API from the St. Louis Fed (free)
  • Gmail account: connected via OAuth 2.0 in n8n
  • Slack workspace: with a bot added to your investor channel

Estimated build time: 45 to 90 minutes from scratch, or under 10 minutes with the template.

Step-by-Step Build Guide

1 Daily Analysis Schedule (Schedule Trigger)

This is the entry point of your workflow. It fires every morning at 6:00 AM so your team has fresh data before the trading day begins. Add a Schedule Trigger node, set the interval to “Every Day”, and configure the hour to 6.

💡

Tip: You can trigger the workflow manually during setup by clicking “Execute Workflow” in n8n. Once you’re happy with the output, enable the schedule.

2 Workflow Configuration (Set Node)

This Set node acts as a single control panel. All customizable parameters live here. It’s the only node you’ll need to update when switching markets or adjusting strategy.

Field Name Type Example Value Description
mlsApiUrl String https://api.attomdata.com/v1/assessment/snapshot Your MLS or property data API endpoint
publicRecordsApiUrl String https://api.attomdata.com/v1/sale/snapshot Public sale records endpoint
demographicApiUrl String https://api.census.gov/data/2022/acs/acs5 Demographic data source (Census API is free)
macroeconomicApiUrl String https://api.stlouisfed.org/fred/series/observations FRED API for interest rates, GDP, etc.
targetMarket String Austin, TX The market region to analyze
investmentThreshold Number 75 Minimum score (0 to 100) to trigger an alert
acquisitionTeamEmail String acquisitions@yourfirm.com Where the email alert is sent
slackChannel String C08XXXXXXXXX Slack channel ID for notifications
📌

The targetMarket value is passed as a query parameter to all four data APIs. Make sure your providers accept a market name in their format, some require a ZIP code or FIPS code instead of a city name.

3 Parallel Data Fetching (4 × HTTP Request Nodes)

Four HTTP Request nodes run in parallel, each pulling a different dataset. Connect the Config node’s output to all four simultaneously (n8n supports multiple connections from one output port).

{
  "url": "={{ $('Workflow Configuration').first().json.mlsApiUrl }}",
  "queryParameters": {
    "market": "={{ $('Workflow Configuration').first().json.targetMarket }}"
  }
}

Duplicate this pattern for all four nodes, swapping the URL. The four sources: MLS Listings (active listings, median prices, days on market), Public Property Records (sale prices, ownership history), Demographic Profiles (population growth, median income), and Macroeconomic Indicators (mortgage rates, GDP, unemployment).

💡

Tip: For APIs requiring authentication, add Authorization: Bearer YOUR_API_KEY in the Headers section of each HTTP Request node.

4 Aggregate All Market Data (Aggregate Node)

The four parallel streams merge into a single item using the Aggregate node set to “Aggregate All Item Data.” This collapses all four API responses into one JSON object the AI agent can work with.

{
  "data": [
    { "source": "mls", "listings": 1247, "medianPrice": 485000, "daysOnMarket": 22 },
    { "source": "publicRecords", "salesVolume": 312, "yoyPriceChange": 0.08 },
    { "source": "demographics", "population": 978908, "populationGrowthRate": 0.032, "medianIncome": 76400 },
    { "source": "macroeconomics", "mortgageRate30yr": 6.82, "unemploymentRate": 0.038 }
  ]
}

5 Investment Opportunity Analyzer (AI Agent)

The brain of the workflow is an AI Agent node powered by GPT-4o with access to a financial calculator and a market research HTTP tool. The agent’s system prompt instructs it to: analyze price trends and demographic shifts, identify emerging investment opportunities, calculate a 0 to 100 investment score per submarket, predict 12-month value growth, and return a structured JSON with all findings.

Connect the OpenAI GPT-4o LLM node, Financial Calculator Tool, Market Research HTTP Tool, and Structured Investment Output parser to the agent’s sub-connections.

💡

Tip: You can swap gpt-4o-mini into the LLM node to reduce API costs for lower-stakes markets and reserve GPT-4o for your primary targets.

6 Structured Investment Output (Output Parser)

The Structured Output Parser forces GPT-4o to return a predictable JSON schema, no free-form text that breaks downstream nodes. A sample output:

{
  "opportunities": [
    {
      "location": "East Austin, TX",
      "propertyType": "Multifamily",
      "investmentScore": 88,
      "currentMedianPrice": 520000,
      "predictedValueGrowth": 12.4,
      "keyDrivers": ["Tech employer expansion", "Limited new supply", "Strong rental demand"],
      "risks": ["Interest rate sensitivity", "Gentrification pushback"],
      "recommendedAction": "Acquire 4-8 unit multifamily within 90 days",
      "timeframe": "6-18 months hold"
    }
  ],
  "marketSummary": "Austin remains a high-growth market. East Austin shows the strongest risk-adjusted opportunity.",
  "topOpportunity": {
    "location": "East Austin, TX",
    "reason": "Score of 88 driven by strong rental demand, limited inventory, and 12.4% predicted growth."
  }
}

7 Check Investment Score Threshold (IF Node)

An IF node gates the alert system. It compares the top opportunity’s investment score against your investmentThreshold (default: 75). Score ≥ 75 fires both alerts. Below threshold, the workflow ends silently, with no alert spam on quiet days.

8 Email Acquisition Team (Gmail Node)

A Gmail node sends a formatted HTML email to your acquisition team with the top opportunity details, market summary, and a table of all high-scoring submarkets. Subject line is dynamically generated: “Investment Opportunity Detected: East Austin, TX”

💡

Tip: To send to multiple team members, use a comma-separated list in the “To” field: james.carter@yourfirm.com, emily.rodriguez@yourfirm.com.

9 Notify Investors on Slack (Slack Node)

Simultaneously, a Slack node posts a formatted message to your investor channel. The channelId field uses the channel’s Slack ID (starts with C). Find it by right-clicking the channel in Slack → “View channel details.”

The Data Structure

This workflow is stateless by default: real-time analysis and alerting only. To track scores over time, add a Google Sheets or Airtable node after the IF check.

Field Type Example Description
location String East Austin, TX Specific neighborhood or submarket identified
propertyType String Multifamily Best property type for this opportunity
investmentScore Number 88 GPT-4o’s 0 to 100 rating of investment potential
currentMedianPrice Number 520000 Current median sale price in USD
predictedValueGrowth Number 12.4 Predicted % price growth over 12 months
keyDrivers Array [“Tech expansion”, “Low supply”] Top reasons this submarket is attractive
risks Array [“Rate sensitivity”] Risk factors to monitor
recommendedAction String Acquire 4-8 unit within 90 days Specific, actionable recommendation
timeframe String 6-18 months hold Recommended investment horizon
📌

The investmentScore is what the IF node evaluates. Default threshold 75 = strong buy signal. Scores 60 to 74 = watch list. Below 60 = low priority.

Full System Flow

┌─────────────────────────────────────────────────────────────────────────┐
│  COMPLETE PIPELINE — Daily Run at 6:00 AM                               │
│                                                                         │
│  [Schedule: 6 AM daily]                                                 │
│         │                                                               │
│  [Set: Target Market, Threshold, Recipients, API URLs]                  │
│         │                                                               │
│  DATA COLLECTION (parallel)                                             │
│  ┌──────┴──────┬────────────────┬────────────────┐                     │
│  [MLS API] [Public Records] [Demographics] [Macroeconomics]             │
│  └──────┬──────┴────────────────┴────────────────┘                     │
│         │                                                               │
│  [Aggregate All Market Data → single JSON object]                       │
│         │                                                               │
│  [GPT-4o Agent] + [Calculator Tool] + [Market Research Tool]            │
│  [Structured Output Parser enforces JSON schema]                        │
│         │                                                               │
│  [IF: investmentScore >= 75?]                                           │
│         │ YES                                                           │
│  ┌──────┴──────────────┐                                                │
│  [Gmail: Alert Email]  [Slack: Investor Notification]                   │
└─────────────────────────────────────────────────────────────────────────┘

Testing Your Workflow

  1. Click Execute Workflow manually in n8n (skip the schedule for now).
  2. Verify all four HTTP Request nodes return data from your APIs. Authentication errors (401) mean a missing or wrong API key in the headers.
  3. Confirm the Aggregate node outputs a single item containing all four data sources.
  4. Check that the AI Agent returns a valid JSON object with an opportunities array and investmentScore values.
  5. Temporarily set investmentThreshold to 0 in the Config node to force the IF condition to pass, then verify both Gmail and Slack receive alerts.
  6. Restore your threshold and toggle the workflow Active.
Problem Likely Cause Fix
HTTP node returns 401 Missing or expired API key Add Authorization: Bearer YOUR_KEY in the Headers section
Aggregate node empty One HTTP request failed silently Enable “Continue on Fail” on each HTTP node
AI Agent returns unstructured text Output parser not connected Ensure Structured Output Parser is on the ai_outputParser sub-port
IF node never passes Score field path is wrong Path: $('Investment Opportunity Analyzer').item.json.output.opportunities[0].investmentScore
Slack message not delivered Wrong channel ID format Use channel ID starting with C, not the channel name. Invite the bot first.
Gmail auth error OAuth token expired Reconnect credential in n8n Settings → Credentials

Frequently Asked Questions

Can I analyze multiple markets at once instead of just one?

Yes, wrap the workflow in a loop using a Split in Batches or Code node that generates an array of market names. Each iteration runs the full pipeline for that market. Be mindful of OpenAI API rate limits if processing many markets simultaneously.

What MLS data provider should I use?

Popular options include ATTOM Data Solutions, PropStream (investor-focused), and RentCast (strong for rental market data). Any provider returning JSON over HTTP works, just point the URL fields at your provider’s endpoint. Many MLS boards also offer direct API access via RETS or RESO Web API.

How much does the OpenAI API cost per run?

With GPT-4o, expect roughly $0.03 to $0.12 per daily run depending on data volume. A typical run with compact API responses costs under $0.05. Analyzing a dozen markets per day keeps monthly cost well under $20, a fraction of one analyst hour.

Can I add more data sources beyond the four included?

Yes, the Market Research HTTP Tool lets GPT-4o fetch additional data on demand during its analysis. You can also add a fifth parallel HTTP Request node for any fixed data source you always want included.

What happens if one API is down when the workflow runs?

By default, a failed HTTP Request stops the workflow. Enable “Continue on Fail” on each HTTP node to handle this gracefully. The Aggregate node collects whichever responses arrived, and GPT-4o analyzes what’s available, noting any missing sources in its summary.

Can I store results historically to track score trends?

Yes, add a Google Sheets node after the AI Agent (before the IF check) to append each run’s results. Over time you’ll build a time-series dataset showing how each submarket’s score evolves, invaluable for spotting momentum shifts early.

Get the Real Estate Submarket Analyzer Template

Skip the 90-minute build. Get the complete, ready-to-import n8n workflow JSON, a step-by-step setup guide, and a credentials walkthrough, everything you need to have your AI market analyst running by tomorrow morning.

Get the Template →

Instant download · Works on n8n Cloud and self-hosted · 14-day money-back guarantee

💡

Already building? Grab the template to skip the credential setup docs and JSON structure headaches. It’s pre-wired and tested.

What’s Next?

  • Historical trend logging: Add a Google Sheets append step to track investment scores over time and visualize momentum for each submarket.
  • Comparable sales report: Extend the AI agent’s prompt to generate a full comps report for the top opportunity and attach it to the email.
  • Multi-market leaderboard: Loop through 5 to 10 markets and generate a daily ranked leaderboard of the best opportunities across your entire portfolio universe.
  • Deal pipeline integration: When score exceeds threshold, auto-create a deal in HubSpot, Salesforce, or Airtable pre-populated with the GPT-4o analysis.
  • Risk dashboard: Feed the risks array into a Google Sheets risk register for a live view of what to watch in each market.
n8n
Real Estate
GPT-4
OpenAI
Gmail
Slack
Investment Analysis
AI Automation

How to Automate Market Demand Research with n8n, GPT-4o and XPOZ MCP

New to n8n? Start with our step-by-step setup guide, then come back to build this workflow.

Manual market research is a time sink most founders and marketers can’t afford. You open Reddit, Twitter, Product Hunt, and Google, spend two hours reading threads, and come away with a vague sense that “people seem frustrated with X.” That’s not intelligence. That’s noise. This workflow changes that by running a fully automated market demand analysis every week, scanning public discussions across Google Search, Twitter/X, and Instagram, extracting real buying signals with GPT-4o, and delivering a polished report straight to your Notion workspace and email inbox, with no human effort required.

Don’t want to build it from scratch? Grab the ready-made template → and be live in under 15 minutes.

What You’ll Build

  1. A weekly schedule trigger that fires the workflow automatically, no manual runs needed.
  2. A research context node where you define your niche, keywords, and analyst focus in plain text.
  3. An AI research agent (GPT-4o + XPOZ MCP) that scans Google Search, Twitter/X, and Instagram for real demand signals and pain points.
  4. A second AI formatter agent that converts raw insights into a clean Notion summary and a professional stakeholder email.
  5. Parallel delivery to Notion (for long-term research tracking) and Gmail (for immediate stakeholder awareness), plus an error-alert branch that emails you if anything breaks.

How It Works: The Big Picture

┌────────────────────────────────────────────────────────────────────────────┐
│  AI MARKET DEMAND ANALYZER                                                 │
│                                                                            │
│  [Schedule Trigger]                                                        │
│       │                                                                    │
│       ▼                                                                    │
│  [Inject Research Context]   ← niche / query / analyst notes              │
│       │                                                                    │
│       ▼                                                                    │
│  [AI Research Agent] ← GPT-4o + XPOZ MCP (Google/Twitter/Instagram)       │
│       │                                                                    │
│       ▼                                                                    │
│  [Format Insights Agent] ← GPT-4o (Notion summary + email body)           │
│       │                                                                    │
│       ▼                                                                    │
│  [Parse & Validate JSON Output]                                            │
│       │                  │                                                 │
│       ▼                  ▼                                                 │
│  [Save to Notion]   [Send Gmail]                                           │
│                                                                            │
│  ── Error Branch ──                                                        │
│  [Error Trigger] → [Send Error Alert Email]                                │
└────────────────────────────────────────────────────────────────────────────┘

What You’ll Need

  • n8n: self-hosted or n8n Cloud (any recent version)
  • OpenAI API key: GPT-4o access required (GPT-4o mini also works with slightly lower depth)
  • XPOZ API token: get yours at xpoz.ai; powers social intelligence search across Google, Twitter/X, and Instagram
  • Notion integration token + database: your research database with at least a Title property
  • Gmail OAuth2 connection in n8n, for sending insight emails and error alerts

Time to build from scratch: ~45 minutes. Time with the template: ~15 minutes (credential setup only).


Building the Workflow: Step by Step

1 Scheduled Market Research Trigger (Schedule Trigger)

This is the heartbeat of the workflow. Every time it fires, the full research pipeline runs end to end. By default the template is configured to run every Monday at 8:00 AM, but you can change this to daily, bi-weekly, or any custom cron schedule.

In n8n, open the node and set:

  • Trigger interval: Weeks
  • Weeks between triggers: 1
  • Trigger on weekday: Monday
  • At hour: 8 (8:00 AM)
💡

Tip: If you’re tracking fast-moving niches (crypto, AI tools, trending SaaS), switch to a daily trigger. For stable B2B markets, weekly is usually sufficient and keeps your API costs low.

2 Inject Research Context (Set)

This is your configuration panel. Instead of hardcoding research parameters inside the AI prompt, they live here, which means you can change your niche or focus topic without touching any agent prompt logic.

Three fields to configure:

Field What it does Example value
body.niche The market or industry you’re researching SaaS project management tools
body.query Specific keywords or research question Asana alternatives for remote teams
body.notes Analyst guidance for the AI Focus on pricing complaints and feature gaps. Ignore generic how-to content.

After this node runs, the output looks like:

{
  "body": {
    "niche": "SaaS project management tools",
    "query": "Asana alternatives for remote teams",
    "notes": "Focus on pricing complaints and feature gaps."
  }
}

3 AI Research Agent: GPT-4o + XPOZ MCP

This is where the heavy lifting happens. An n8n AI Agent node powered by GPT-4o receives your research context and uses the XPOZ MCP connector as a tool to search across Google Search, Twitter/X, and Instagram in real time.

The agent’s system prompt instructs it to act as a growth intelligence analyst, extracting only high-signal findings: real frustrations, competitor weaknesses, switching intent, unmet feature requests, and pricing dissatisfaction. Generic content (tutorials, press releases, promotional posts) is explicitly filtered out.

XPOZ MCP node configuration:

  • Endpoint URL: https://mcp.xpoz.ai/mcp
  • Authentication: Bearer Auth, paste your XPOZ API token
💡

Tip: The agent is set to maxIterations: 30, giving it enough room to make multiple search calls and cross-reference findings. Don’t reduce this below 10 or you’ll get shallow results.

4 Format Insights into Notion Summary and Email (AI Agent)

A second GPT-4o agent takes the raw insight text and transforms it into two clean deliverables as a single JSON object.

{
  "notion_summary": "Remote teams cite per-seat pricing as barrier. Common complaints: no built-in time tracking, clunky Slack integration. Competitors gaining ground: Linear, ClickUp. Buying intent detected in 12 threads asking for free Asana alternatives.",
  "email": {
    "subject": "Weekly Market Intelligence: Asana Alternatives (April 2026)",
    "body": "Hi James,\n\nThis week's scan surfaced strong demand signals for lightweight project management tools targeting remote-first teams..."
  }
}
📌

Note: The system prompt explicitly bans markdown, emojis, and hallucinated data. The AI only uses content from the research agent’s output. This matters, you don’t want fabricated market insights landing in your Notion database.

5 Parse and Validate AI Output (Code)

This JavaScript node handles both clean JSON and JSON wrapped in markdown code fences. It also validates that both required fields (notion_summary and email) are present before allowing data to continue downstream, throwing meaningful errors if anything is missing.

6 Save to Notion + Send Gmail (Parallel)

After validation, the workflow splits into two parallel branches. The Notion node saves the summary as a new database page for long-term research archiving. The Gmail node sends the formatted email to your configured stakeholder address. Both run simultaneously, no sequential bottleneck.

💡

Tip: Want to send to multiple stakeholders? Add multiple recipients in the Gmail node’s To field separated by commas, or use the CC/BCC options in the node’s Options panel.

The Notion Database Schema

Create a Notion database for your market research archive. At minimum you need one property:

Property name Type Example value Notes
summery Title Remote teams cite Asana’s pricing as a barrier… Must match the key in the Notion node’s propertiesUi config. Rename in Notion if preferred, just update the node’s key field to match.
Date (optional) Date April 14, 2026 Use a Created time property in Notion for automatic timestamping.
Niche (optional) Text SaaS project management Extend the workflow to add this field automatically if needed.
📌

Important: The template’s Notion node references property key summery|title. If you create a fresh database, name your title property summery, or update the key in the node to match your own property name.

Error Handling Branch

The workflow includes a dedicated error handling branch. Any node that fails mid-execution triggers the Error Trigger node, which immediately sends an alert email including the failed node name, error message, and timestamp. You’ll know within seconds if the XPOZ API returns an error, GPT-4o rate-limits your request, or the Notion API rejects the page, with no manual log monitoring needed.

Testing Your Workflow

  1. Click Test Workflow in n8n (runs the Schedule Trigger manually).
  2. Watch the AI Research Agent execute, it makes several XPOZ tool calls. Typically takes 30 to 90 seconds.
  3. Inspect the Parse and Validate AI Output node, confirm a valid JSON object with both keys.
  4. Check your Notion database for a new entry and your Gmail inbox for the insight email.
  5. If all looks good, activate the workflow via the Active toggle.
Problem Likely cause Fix
XPOZ node returns 401 Invalid or expired Bearer token Regenerate XPOZ API key and update the n8n credential
Parse node throws JSON error GPT-4o returned non-JSON text Check the formatter agent’s output and adjust the system prompt slightly
Notion page created with empty title Property key mismatch Match the key in the Notion node to your database’s title property name exactly
Gmail not sending OAuth scope issue Re-authorize the Gmail credential in n8n
Agent times out Too many XPOZ search iterations Provide a more specific body.query to reduce search surface

Frequently Asked Questions

Does this workflow search the web in real time or use cached data?

It uses real-time data via the XPOZ MCP connector, which queries Google Search, Twitter/X, and Instagram live at execution time. Every run reflects the current state of public discussions, not cached snapshots. Results will vary between runs, which is exactly what you want for tracking how market sentiment shifts over time.

Can I research multiple niches in a single run?

The default template handles one niche per run to keep analysis focused and costs predictable. To research multiple niches, either run the workflow multiple times with different Set node configurations, or extend it by adding a loop before the AI agent that iterates over an array of niche/query pairs stored in a Google Sheet or Airtable.

How much does this cost to run per week?

A typical analysis run consumes roughly 8,000 to 15,000 GPT-4o tokens across both agents, putting the OpenAI cost at around $0.10 to $0.25 per run. Add XPOZ API costs based on your plan tier. For a weekly run, total API cost is generally under $1/month.

Can I use a different AI model instead of GPT-4o?

Yes. Swap the two OpenAI LLM nodes for any model supported by n8n’s LangChain nodes: Claude, Gemini, Mistral, or a locally hosted Ollama model. If you switch models, you may need to adjust the formatting prompt to ensure clean JSON output.

Can I save results somewhere other than Notion?

Absolutely. Replace the Notion node with a Google Sheets, Airtable, or Slack node. The parsed JSON output is clean and structured, so it plugs into any destination node with minimal reconfiguration.

What happens if XPOZ finds no relevant discussions?

The AI research agent is instructed to state clearly when demand signals are weak or non-existent rather than fabricating insights. The Notion summary will reflect “low demand signal detected”, which is itself a useful data point. Refine your query in the Set node to search with different keywords.


🚀 Get the AI Market Demand Analyzer Template

You now know exactly how this workflow is built. The ready-made template includes the complete n8n workflow JSON (import in one click), a step-by-step Setup Guide PDF, and a Credentials Guide showing exactly where to get each API key.

Download the Template, $14.99 →

Instant download · Works on n8n Cloud and self-hosted · One-time purchase

What’s Next

  • Competitor monitoring: Replace the niche query with specific competitor product names to track sentiment around their offerings over time.
  • Keyword trend scoring: Add a Code node after parsing to count signal frequency across runs and flag niches with accelerating demand.
  • Slack digest: Add a Slack node alongside the Gmail output to post a weekly #market-intel summary to your team channel.
  • Multi-niche portfolio: Pair with a Google Sheets trigger to iterate over a list of niches, running a full analysis sweep across your entire product portfolio in one go.

How to Auto-Generate SWOT Analysis PDF Reports with n8n and AI

New to n8n? Start with our step-by-step setup guide, then come back to build this workflow.

Writing a SWOT analysis takes hours — researching the market, consulting stakeholders, structuring the findings, and then wrestling with formatting in Word or Google Docs. If you’re a consultant, analyst, or business owner who produces these reports regularly, that time adds up fast. This n8n workflow replaces that process with four specialized AI agents that analyze Strengths, Weaknesses, Opportunities, and Threats in parallel, then stitch the results into a professionally formatted PDF and deliver it straight to your inbox.

Prefer to skip the setup? Grab the ready-made template → and be up and running in under 10 minutes.

What You’ll Build

  1. You add a company’s profile (name, industry, size, market region) to a Google Sheet — one row per company you want analyzed.
  2. You trigger the workflow with one click. Four AI agents instantly spin up in parallel and each writes a deep analysis of one SWOT quadrant.
  3. A fifth agent writes the introduction, a sixth writes the conclusion, and a seventh assembles the table of contents and title page.
  4. All sections are saved back to your Google Sheet as a structured record, then merged and sent to APITemplate.io to render a polished PDF.
  5. The finished PDF lands in your Gmail inbox, ready to share with a client or stakeholder — no manual formatting required.

How It Works — The Big Picture

The workflow reads a single row of company data from Google Sheets, fans out to four parallel analysis agents, formats each section, then reconverges to generate the PDF and send it by email. The entire flow runs sequentially where needed and in parallel where possible, keeping generation time to a minimum.

+-------------------------------------------------------------------------+
|  SWOT ANALYSIS PDF REPORT GENERATOR                                     |
|                                                                         |
|  [Manual Trigger]                                                       |
|       |                                                                 |
|  [Google Sheets -- Read Company Row]                                    |
|       |                                                                 |
|  [AI Agent -- SWOT Coordinator]  <-- OpenAI GPT-4                      |
|       |                                                                 |
|  +----+--------------------------------------+                          |
|  v          v           v           v                                   |
| [Strengths] [Weaknesses] [Opportunities] [Threats]  <- parallel agents |
|  v          v           v           v                                   |
| [Format S] [Format W]  [Format O]  [Format T]                          |
|  +----+--------------------------------------+                          |
|       v                                                                 |
|  [Merge All Sections]                                                   |
|       |                                                                 |
|  [Write Introduction]  [Write Conclusion]  [Title Page + ToC]          |
|       +----------------------------------+------------------+           |
|                             [Pull from Sheets]                          |
|                                  |                                      |
|                        [Combine All Content]                            |
|                                  |                                      |
|                    [Generate PDF via APITemplate.io]                    |
|                                  |                                      |
|                        [Download PDF File]                              |
|                                  |                                      |
|                      [Send Report via Gmail]                            |
+-------------------------------------------------------------------------+
  

What You’ll Need

  • n8n instance — self-hosted or n8n Cloud (v1.60+ recommended)
  • OpenAI API key — GPT-4 or GPT-4o access required
  • DeepSeek API key — used for the reasoning-heavy analysis phase (optional but improves depth)
  • Google Sheets — with OAuth2 connected to n8n; one sheet for input data, one for storing generated sections
  • APITemplate.io account — free plan works for testing; paid plan for production volume
  • Gmail account — connected to n8n via OAuth2 for report delivery

Estimated build time: 45-90 minutes from scratch, or under 10 minutes with the template.

Part 1 — Reading Company Data

1 Manual Trigger (Trigger)

This workflow starts manually — you click “Test workflow” (or call the workflow via another automation). The trigger passes no data; it simply kicks off the flow so the next node can read from your Google Sheet.

💡

Tip: You can easily swap this for a Schedule Trigger to run the analysis automatically every Monday morning, or a Webhook Trigger so an external system (like a CRM) can fire it on demand.

2 Google Sheets — Read Company Row

This node reads your input spreadsheet and pulls the company profile for analysis. Configure it to read a single row at a time — either the first row, or use a filter to target a specific company name.

{
  "Company Name": "Apex Logistics Inc.",
  "Industry": "Third-Party Logistics (3PL)",
  "Business Size": "Mid-market (250-500 employees)",
  "Market Region": "Southeast United States"
}
📌

Important: The column names in your sheet must exactly match what the AI agent nodes reference in their prompts. If you rename a column, update the corresponding agent prompt too.

Part 2 — Parallel SWOT Analysis

3 AI Agent — SWOT Coordinator

This central agent receives the full company profile and fans out to the four specialized analysis agents. It uses OpenAI GPT-4 and a Structured Output Parser to ensure the data passed downstream is consistently formatted.

{
  "companyName": "Apex Logistics Inc.",
  "industry": "Third-Party Logistics (3PL)",
  "businessSize": "Mid-market (250-500 employees)",
  "marketRegion": "Southeast United States",
  "analysisContext": "Focus on competitive landscape, operational efficiency, and regional market dynamics."
}

4 Strengths Analysis Agent

One of four parallel agents. This one is prompted to identify the company’s internal competitive advantages — things like proprietary technology, strong customer relationships, operational efficiencies, or brand recognition. It draws on the industry and business size context to make the analysis specific rather than generic.

{
  "section": "strengths",
  "points": [
    "Established network of 12 regional distribution centers across the Southeast",
    "Proprietary real-time shipment tracking system with 99.4% accuracy",
    "Long-term contracts with 3 of the top 10 US e-commerce retailers",
    "Low driver turnover rate (8%) compared to industry average (35%)"
  ],
  "summary": "Apex Logistics benefits from deep regional infrastructure and technology investments that create significant switching costs for key clients."
}
💡

Tip: All four analysis agents share the same OpenAI Chat Model node — n8n lets multiple agents reference one credential/model without duplicating the node. This keeps your workflow clean and makes it easy to swap models globally.

5 Weaknesses Analysis Agent

Prompts the model to think critically about internal limitations — gaps in technology, talent, financial resources, or operational coverage. The output mirrors the same JSON structure as the Strengths agent for easy merging downstream.

6 Opportunities Analysis Agent

Shifts focus externally: what market trends, regulatory changes, customer segments, or partnership opportunities could this company exploit? This agent benefits most from the “Market Region” field — it allows the AI to tailor its recommendations to specific geographic dynamics.

7 Threats Analysis Agent

Identifies external risks: new competitors, regulatory headwinds, supply chain vulnerabilities, macroeconomic factors. This agent uses the DeepSeek Reasoner model by default (you can configure it to use GPT-4) because threat analysis benefits from deeper causal reasoning.

Part 3 — Formatting and Assembly

8 Section Formatting Agents (x4)

After analysis, four formatting agents take each raw JSON section and convert it into polished prose — proper paragraphs, transitions, and a professional tone suitable for an executive report. Each formatting agent saves its output back to a dedicated Google Sheet tab, creating a persistent record of every analysis run.

{
  "section": "strengths",
  "formattedText": "Apex Logistics has built a formidable operational foundation across the Southeast United States. The company's network of 12 regional distribution centers ensures next-day delivery coverage for over 85% of the regional population -- a geographic footprint that would take years and significant capital for a new entrant to replicate.\n\nThe proprietary tracking system, developed in-house over six years, delivers 99.4% shipment accuracy and has become a key differentiator in contract renewals..."
}

9 Merge All SWOT Sections

The n8n Merge node waits for all four formatting branches to complete, then combines their outputs into a single item that flows forward. This is the synchronization point — nothing moves to the introduction or conclusion until all four SWOT sections are ready.

10 Write Introduction & Conclusion Agents

Two additional AI agents generate the bookends of the report. The introduction agent receives a summary of all four sections and writes a context-setting executive overview. The conclusion agent synthesizes the findings into strategic recommendations. Both use GPT-4o for speed.

11 Combine All Content (Code Node)

A JavaScript code node pulls all sections from Google Sheets (via several “Pull from Sheets” nodes), assembles them in the correct order — Title Page, ToC, Introduction, Strengths, Weaknesses, Opportunities, Threats, Conclusion — and formats the combined content into the JSON structure APITemplate.io expects.

// Combine all report sections in order
const sections = {
  titlePage: $('Extract Company Name').item.json.companyName,
  tableOfContents: $('Save Table of Contents to Sheets').item.json.tocContent,
  introduction: $('Upload Introduction').item.json.formattedText,
  strengths: $('Upload Strengths').item.json.formattedText,
  weaknesses: $('Upload Weaknesses').item.json.formattedText,
  opportunities: $('Upload Opportunities').item.json.formattedText,
  threats: $('Upload Threats').item.json.formattedText,
  conclusion: $('Upload Conclusion').item.json.formattedText
};

return [{ json: { reportData: sections, generatedAt: new Date().toISOString() } }];

Part 4 — PDF Generation and Delivery

12 Generate PDF via APITemplate.io

This HTTP Request node sends the assembled report data to APITemplate.io’s PDF generation API. APITemplate renders the content using a pre-built professional template (think letterhead, consistent typography, section dividers) and returns a download URL for the finished PDF.

💡

Tip: APITemplate.io lets you design your own PDF templates using a drag-and-drop editor. You can match the report to your brand colors, add a logo, and create custom section styles — all without touching CSS or LaTeX.

13 Download PDF & Send via Gmail

The Download PDF node fetches the binary file from APITemplate’s URL, and the Gmail node attaches it to an email addressed to the analyst or stakeholder. The subject line and body are dynamically populated with the company name and generation timestamp.

The Data Structure

Your Google Sheet needs two tabs: an Input tab (one row per company to analyze) and an Output tab (where generated sections are stored). The input schema is simple:

Column Type Example Description
Company Name Text Apex Logistics Inc. The full company name — used in the report title and throughout the analysis
Industry Text Third-Party Logistics (3PL) The industry sector — helps AI agents contextualize competitive dynamics
Business Size Text Mid-market (250-500 employees) Company size — affects which strengths/weaknesses are relevant
Market Region Text Southeast United States Geographic focus — used for market-specific opportunity and threat analysis
Status Text Pending / Completed Optional status field — useful if you process a queue of companies
📌

Column names must match exactly (including capitalization and spaces) — the AI agent prompts reference them by name using n8n expressions like {{ $json["Company Name"] }}.

Full System Flow

  Google Sheet (Input Tab)
         |
         v
  +------------------+
  |  Read Company    |  -> Company Name, Industry, Size, Region
  |  Profile         |
  +------------------+
         |
         v
  +----------------------------------------------------------+
  |              SWOT Coordinator Agent (GPT-4)              |
  +----------------------------------------------------------+
    |           |              |              |
    v           v              v              v
 [Strengths] [Weaknesses] [Opportunities] [Threats]
  (GPT-4)    (GPT-4)        (GPT-4)      (DeepSeek)
    |           |              |              |
    v           v              v              v
 [Format S] [Format W]   [Format O]    [Format T]
    |           |              |              |
    +-----------+-------+------+--------------+
                        v
                [Merge All Sections]
                        |
           +------------+------------+
           v            v            v
     [Introduction] [Conclusion] [Title + ToC]
           |            |            |
           +------------+----+-------+
                            v
              Google Sheets (Output Tab -- persist all sections)
                            |
                            v
                 [Combine All Content]
                            |
                            v
              [APITemplate.io -- Generate PDF]
                            |
                            v
                    [Download PDF]
                            |
                            v
              [Gmail -- Send Report to Inbox]
  

Testing Your Workflow

  1. Add one row to your Google Sheet with a real company you know well (e.g., a local business or well-known brand in your industry).
  2. Open the workflow in n8n and click Test workflow.
  3. Watch the execution — each agent node should light up green within 30-60 seconds as the AI generates content.
  4. Check your Google Sheets Output tab — you should see the formatted sections appear as the agents complete.
  5. After all nodes complete successfully, check your Gmail inbox for the PDF report.
Problem Likely Cause Fix
AI Agent node fails with 400 error OpenAI credential not configured or invalid API key Go to n8n Credentials → OpenAI → re-enter your API key and test connection
Google Sheets node returns empty data Spreadsheet ID or sheet name not updated after import Open the Google Sheets node, click the Spreadsheet URL field, and reselect your sheet
APITemplate.io returns 401 Unauthorized APITemplate API key missing or expired Log in to APITemplate.io → Account → API Keys → copy the key into n8n’s HTTP Request node header
Gmail node fails to send OAuth scope doesn’t include “Send email” Reconnect the Gmail credential in n8n and ensure “Compose and send” scope is granted
PDF is blank or missing sections One of the SWOT agents timed out or returned empty output Re-run the workflow; if it persists, add error handling (IF node) after each agent to catch empty responses

Frequently Asked Questions

Can I analyze multiple companies in one run?

The current template processes one company at a time to stay within OpenAI rate limits and keep execution predictable. To process a batch, add a Loop node before the Google Sheets read step and iterate through each row with a status of “Pending”. Update the status to “Completed” after the PDF is sent.

How much does this workflow cost to run per report?

Using GPT-4o for the four SWOT agents, introduction, conclusion, and table of contents, a single full report typically uses 8,000-14,000 tokens across all calls — roughly $0.08-$0.14 at current GPT-4o pricing. APITemplate.io’s free plan includes 50 PDF renders per month. So for moderate use, the ongoing cost is very low.

Can I use a different AI model instead of GPT-4?

Yes. Each AI Agent node lets you swap the connected language model independently. You can use GPT-4o mini for faster, cheaper runs, Claude via OpenRouter for a different analytical style, or Gemini if you prefer Google’s ecosystem. The Structured Output Parser will still enforce the expected JSON shape regardless of which model you use.

Does the workflow work on n8n Cloud, or only self-hosted?

It works on both n8n Cloud and self-hosted instances running n8n v1.60 or later. The only requirement is that your n8n instance can reach the OpenAI API, Google APIs, and APITemplate.io over HTTPS — which any standard deployment supports.

Can I customize the PDF template design?

Absolutely. Log in to APITemplate.io and open your template in the editor. You can change fonts, colors, add your company logo, modify section layouts, and add a cover page image. Once you save the template, the workflow will automatically use the updated design the next time it runs.

What if I don’t want to use APITemplate.io?

You have two alternatives: use the n8n HTML node to render the content as an HTML file and convert it with a headless Chrome service like Browserless, or export the sections to a Google Doc and use the Google Drive API to export it as PDF. The APITemplate.io approach is recommended because it requires no additional infrastructure and produces the most polished output.

🚀 Get the SWOT Analysis PDF Report Template

Skip the build — get the fully configured workflow JSON, a pre-built Google Sheets input template, and step-by-step setup and credentials guides so you’re generating professional SWOT reports in minutes.

Get the Template →

Instant download · Works on n8n Cloud and self-hosted · $14.99

What’s Next?

  • Competitor comparison mode: Analyze 3-5 competitors in one run and add a comparison table to the PDF showing how your company stacks up across each SWOT quadrant.
  • CRM integration: Trigger the workflow from HubSpot or Salesforce when a new prospect is added, and automatically attach the SWOT PDF to their contact record.
  • Slack/Teams delivery: Add a Slack or Teams node after the Gmail step to post a summary of the key findings to a team channel as soon as the report is ready.
  • Scheduled competitive intelligence: Run the workflow monthly on your key accounts to track how their SWOT profile evolves over time, building a longitudinal record in Google Sheets.
n8n
OpenAI
Google Sheets
APITemplate.io
SWOT Analysis
PDF Report
AI Agents
Business Automation

How to Build an AI Contract Risk Analyzer with n8n (Two-Pass Analysis)

New to n8n? Start with our step-by-step setup guide, then come back to build this workflow.

Learn how to build a two-pass AI contract analyzer with n8n that classifies documents, scores risk, and alerts your team via Slack and email.

Overview

This comprehensive guide shows you how to create an AI-powered contract analysis workflow using n8n, OpenAI, Supabase, Slack, and Gmail. The workflow performs a two-pass analysis to classify contracts and identify risks efficiently.

Key Features

  • Two-pass AI analysis for accurate risk scoring
  • Contract classification and metadata extraction
  • Automatic Slack and email alerts for high-risk contracts
  • Supabase integration for data persistence
  • Deduplication to avoid re-analyzing the same contracts
  • Error handling and admin notifications

How It Works

The workflow ingests contract PDFs, performs a quick classification pass to extract metadata, then conducts a deep risk analysis. Results are stored in Supabase and alerts are sent via Slack and email based on risk scores.

Get Started

Download the Complete Workflow

Includes setup guide, credentials guide, and the ready-to-import n8n JSON workflow.