DEV Community

Mike
Mike

Posted on AI-assisted

Export Zillow Listings to Google Sheets with n8n

Build a property research spreadsheet from a ZIP code, then add detailed information for the homes you want to investigate. This walkthrough connects Zillow Search and Zillow Property Details through n8n, with Google Sheets as the destination.

You choose how many listings to request and how many to enrich. The workflow reads the Apify datasets page by page, adds available facts and history to the shortlist, and writes the results to Google Sheets in batches. Actual results depend on available inventory, run time and budgets.

Copy the workflow JSON · Google Sheets headers

I maintain both Actors, which run on Apify. The accompanying template uses standard n8n nodes to start runs through the Apify API, retrieve their results and export them to Google Sheets. You do not need to install a community node or write code to configure it.

What you will build

The supplied workflow demonstrates a ZIP-code search for homes for sale and follows this sequence:

  1. Search one or more US ZIP codes for homes for sale.
  2. Select properties using an asking-price ceiling and a minimum bedroom count.
  3. Request details for the number of qualifying properties you choose.
  4. Combine the search and detail records by Zillow property ID, or ZPID.
  5. Add new rows to Google Sheets and update rows with a matching ZPID.

For the walkthrough, we set searchLimit to 20 and detailLimit to 5, search ZIP code 11215, and shortlist homes with an asking price at or below $1 million and at least two bedrooms. These values define this small demonstration. Set the search volume and enrichment count for your own task using the settings described below. Eligible properties are selected in ascending asking-price order, with ZPID breaking ties.

The resulting sheet includes addresses, listing prices, bedrooms, bathrooms, floor area, construction year where available, coordinates and source timestamps. Property Details can fill in or update those facts and add available price and tax history. Missing source values stay blank.

The final rows of a live Google Sheets export with listing facts visible

The final rows of the 320-listing live export. The crop shows selected property facts and row numbers.

What the Actors support

Zillow Search supports ZIP codes, city or county queries, Zillow search URLs and map bounds. It can collect for-sale, rental, sold, FSBO and foreclosure listings, with search filters, automatic pagination and subdivision of dense search areas. Its public maxResults setting accepts integers of at least 20 without a fixed maximum. That minimum is a requested result limit, not a guarantee that 20 properties exist or will be returned.

Zillow Property Details accepts ZPIDs, property URLs or addresses, including bulk targets with your own record identifiers. Available output includes home facts, descriptions, photos, agent and broker attribution, schools, and price and tax history. This tutorial passes the selected ZPIDs to Details and maps a subset of the output to 26 spreadsheet columns.

The downloadable workflow exposes ZIP-code searches for homes for sale. To use the other search inputs, listing types or additional output fields, adapt the Actor input and sheet mapping in the workflow.

What you need

  • An n8n instance with the built-in HTTP Request, Code, Wait and Google Sheets nodes. The template uses Google Sheets node version 4.7; update n8n if your instance does not recognize it.
  • An Apify account, an API token and sufficient credit to run the two Actors.
  • A Google account that can edit your destination spreadsheet.
  • The workflow JSON at the end of this guide and the header row in step 1.

The template is free to use. Actor runs and your n8n hosting can incur charges. Check the current Pricing tabs for Search and Property Details before running it.

1. Prepare the spreadsheet

Create a Google spreadsheet and a tab named Properties. If you will use the optional drive.file connection in step 4, create the file through n8n as described there, then return here to add the headers. Copy the line below into A1 of the empty tab. If it lands in one cell, choose Data → Split text to columns and select comma.

zpid,property_url,address,city,state,zip_code,listing_status,price_usd,beds,baths,living_area_sqft,year_built,home_type,latitude,longitude,detail_status,detail_missing_sections,detail_error,price_history_json,tax_history_json,search_quality,search_scraped_at,detail_scraped_at,exported_at,search_run_id,details_run_id
Enter fullscreen mode Exit fullscreen mode

Keep the header names unchanged. The template maps its output fields to these names and uses zpid to match existing rows.

Copy the spreadsheet ID from its URL:

https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit
Enter fullscreen mode Exit fullscreen mode

Use the value between /d/ and /edit. The numeric gid identifies a tab and is not the spreadsheet ID.

2. Import the workflow into n8n

Copy the workflow JSON into a file named workflow.json. Create a workflow in n8n, choose Import from File, select that file, and save the workflow.

Open the Settings node. It contains all the values needed for a first run:

Setting Default Purpose
zipCodes 11215 One to 100 comma-separated US ZIP codes, such as 11215,07030. Keep leading zeros.
searchLimit 20 Requested result limit across all ZIPs. Enter an integer of 20 or more. The workflow passes it to Search as maxResults.
detailLimit 5 Maximum number of listings to enrich. Enter an integer from 0 through searchLimit. Use 0 for a search-only export.
maxEnrichmentPrice 1000000 Highest asking price eligible for enrichment. Set to 0 to disable this filter.
minEnrichmentBeds 2 Minimum bedrooms eligible for enrichment. Set to 0 to disable this filter.
searchBudgetUsd 1 Maximum charge passed to the Search run. This template accepts $0.10–$100.
detailsBudgetUsd 1 Total spending ceiling for all Details runs in this execution. This template accepts $0.10–$100.
spreadsheetId Replace before running The ID copied from your Google Sheets URL.
sheetName Properties Exact destination tab name.

The workflow divides a large shortlist into groups of up to 1,000 properties, the maximum per Property Details run. It runs these groups in order and records each group's Apify run ID on the corresponding sheet rows.

The price and bedroom settings control enrichment, not which search rows appear in the sheet. A listing outside those filters still gets exported, with detail_status set to not_selected.

If an enabled filter requires a missing field, that listing is not shortlisted. For example, a listing with an unknown price does not qualify under an active price ceiling.

3. Connect Apify

Create a Header Auth credential in n8n:

Name: Authorization
Value: Bearer YOUR_APIFY_TOKEN
Enter fullscreen mode Exit fullscreen mode

Replace YOUR_APIFY_TOKEN with your token, retaining Bearer and the following space. Save this as a credential, rather than putting the token in a node URL or in the Settings node.

Select that same credential on all six HTTP Request nodes:

  • Start Zillow Search
  • Get Search run
  • Get search listings
  • Start Property Details
  • Get Details run
  • Get property details

Each is already configured for Generic Credential Type → Header Auth. The two Start nodes create runs; the remaining nodes read their status and results.

The template starts each Actor asynchronously and polls until the run succeeds. It then requests up to 250 items per dataset page and uses Apify's returned offset and total to fetch the rest. The workflow checks that each dataset was read in full before preparing sheet rows. See the run creation, run status and dataset items references.

4. Connect Google Sheets

Open Upsert Google Sheets, then create or select a Google Sheets OAuth2 credential. On a self-hosted n8n instance, you may need to complete n8n's Google OAuth setup first.

For a connection restricted to files used with this app, enable Custom Scopes on the credential and set Enabled Scopes to https://www.googleapis.com/auth/drive.file. With that scope, use a separate one-off workflow with Manual Trigger → Google Sheets. Set the Google Sheets resource to Document and operation to Create, choose the same credential, give the spreadsheet a title, and add a sheet named Properties. Run that setup workflow once, then paste the headers into the new tab as described in step 1. Replace spreadsheetId with the newly created file ID. Pasting the ID of an arbitrary existing spreadsheet does not grant the application access. See Google’s scope guide.

The node is configured with:

  • Operation: Append or Update Row.
  • Document: By ID, using spreadsheetId from Settings.
  • Sheet: By Name, using sheetName from Settings.
  • Mapping Column Mode: Map Automatically.
  • Column to match on: zpid.
  • Cell Format: Let n8n format (RAW).
  • Use Append: enabled so new rows can extend the sheet.

Keep RAW formatting so ZIP codes and property IDs remain text and source strings are not interpreted as spreadsheet formulas. Numeric prices and measurements are still sent as numbers.

Keep the destination tab as a contiguous table with one row per ZPID. Loop over sheet rows sends up to 100 rows to Upsert Google Sheets at a time. Each batch updates matching rows and appends new ones.

If n8n asks you to refresh the column list after connecting the spreadsheet, do so and confirm that zpid is still the match column. The supplied headers must exist before the first write. See n8n's Append or Update Row documentation for the operation's behavior.

5. Run a small export

For a small first run, use searchLimit: 20 and detailLimit: 5, then click Execute workflow. These are the saved example settings; adjust them for the volume you want to collect.

In the larger live test, Zillow Search returned 320 listings in pages of 250 and 70. Property Details returned 255 complete records in pages of 250 and 5. The Google Sheets node wrote 4 batches of 100, 100, 100, and 20 rows, and the readback matched all 8,320 data cells across 26 columns.

We started the Actors in one execution and reused their completed runs in the export execution. The export fetched the real data from Apify and wrote it to a private Google spreadsheet. Both datasets were read at offsets 0 and 250. The 320 rows were written using n8n 2.47.7.

n8n execution list showing the successful live batch export

The successful export execution in n8n. It read the completed Apify datasets and ran the Google Sheets write loop.

The number returned can be lower than your requested searchLimit when fewer properties match, the source exposes fewer results, or the run reaches its budget or operational limits. The enrichment count can also be lower than detailLimit when fewer properties qualify or details cannot be retrieved.

When the execution completes, inspect the Properties tab:

Columns What to check
zpid, property_url A stable identifier and a link back to the property.
address, city, state, zip_code Location information, including leading zeros in ZIP codes.
price_usd, beds, baths, living_area_sqft Current available property facts. Detail values take precedence where available.
year_built, home_type, latitude, longitude Additional property and location fields.
detail_status, detail_missing_sections, detail_error Whether enrichment happened and what was missing.
price_history_json, tax_history_json This template keeps the ten newest available entries of each kind as JSON text. The full returned history remains in the Actor dataset.
search_quality Collection-quality metadata supplied by Search.
Source timestamps and run IDs When data was collected and which Apify runs produced it.

For a selected property, detail_status can be complete, partial, notFound or error. A complete record means the requested source sections passed validation; it does not mean every optional value exists.

not_returned means the property was selected but no matching detail row came back, for example because a budget stopped further lookups. not_selected means the workflow did not request details for that property.

The Actor datasets remain available in Apify subject to your retention settings. The spreadsheet contains the 26 mapped fields; other returned fields and history entries can be accessed from the datasets or added to a customized export.

Control the cost of enrichment

Search and Details have independent budgets. Search receives the full searchBudgetUsd for its single run. For multiple Details runs, the workflow reserves $0.10 per batch and distributes the rest roughly in proportion to batch size, in whole cents. If the total cannot cover that allocation, the workflow stops before starting Details. Check the Actor's Pricing tab for the applicable minimum. Dataset access, retention and n8n hosting can carry separate costs.

A practical sequence is to run with detailLimit: 0, inspect the listing data, then choose an enrichment filter and increase the limit. Starting the workflow again performs a fresh search and can incur new charges.

The workflow does not automatically retry either Start request. If a network error occurs after a run may have been accepted, check Apify before starting again. Read requests have bounded retries.

Understand repeat runs

Run one execution at a time against the same sheet. Sequential runs update matching ZPIDs and add new ones. Google Sheets is not a transactional database, so overlapping executions can still create duplicate inserts.

If a Sheets batch fails, earlier batches can remain in the sheet. After fixing the cause, retry the write using the prepared rows when available, or rerun the workflow. The ZPID match lets a sequential replay update rows already written.

Each observed row is refreshed with that execution's output, including blank detail fields when the property is not enriched. Rows that do not appear in a later search remain untouched; their timestamps help you identify older observations. The workflow neither deletes disappeared listings nor records a separate history of each export.

Ongoing change detection needs stored observations and rules for incomplete scans. Repeated exports from this template should not be interpreted as confirmed delistings or complete market history.

Troubleshooting

The search returns no rows. The workflow ends at Select properties to enrich, without running Details or writing to Google Sheets. Check the ZIP codes and the Search dataset in Apify.

There are listings but none were enriched. Check detailLimit, the price ceiling and minimum bedrooms. All found listings are still exported when the shortlist is empty.

An Actor fails or times out. The workflow stops before writing any sheet rows. Check the run and its partial results in Apify before retrying. The template gives each Actor run ten minutes and stops polling after fifteen minutes. The overall workflow follows your n8n instance's execution settings. Stopping n8n does not itself abort an Apify run.

Google Sheets reports missing columns or access denied. Confirm the account can edit the document, the tab exists and the header row matches step 1. Fix the connection before rerunning paid collection. The imported workflow contains no account credentials.

Some values are blank. Zillow may not expose them, enrichment may not have been selected, or the detail response may be partial. Read the status and quality columns instead of treating missing values as zero. Source availability and coverage vary; an export is not a complete MLS feed.

Start with one ZIP code and a small shortlist. Once the columns answer your research question, expand the search or adjust the selection rules while keeping the budgets explicit.

AI was used to draft and edit this tutorial. The run and screenshots show actual output from Apify, n8n, and Google Sheets.

Workflow JSON

Copy the n8n workflow JSON
{"name":"Zillow Search and Property Details to Google Sheets","nodes":[{"parameters":{},"id":"8a6dd329-867d-4ce9-a168-f7543f3fba1e","name":"Run manually","type":"n8n-nodes-base.manualTrigger","typeVersion":1,"position":[0,300]},{"parameters":{"assignments":{"assignments":[{"id":"ea7bab57-3904-4f05-981c-9227dd23ced2","name":"zipCodes","value":"11215","type":"string"},{"id":"75d8cb30-e32c-4706-a7ca-e53a677fd81e","name":"searchLimit","value":20,"type":"number"},{"id":"ef79602f-b578-432a-a380-7f35d554f228","name":"detailLimit","value":5,"type":"number"},{"id":"bafda049-06dd-44f0-bb45-7e349feb36f6","name":"maxEnrichmentPrice","value":1000000,"type":"number"},{"id":"f3db582c-26d5-4e5b-afb9-c7065c3f1d1f","name":"minEnrichmentBeds","value":2,"type":"number"},{"id":"2f9e0cf9-3f14-4f28-9ae3-70b87eefbb28","name":"searchBudgetUsd","value":1,"type":"number"},{"id":"3467716b-b123-431d-95e3-23bdd35e911e","name":"detailsBudgetUsd","value":1,"type":"number"},{"id":"e9e120c6-15c0-4670-82ff-a17839932c23","name":"spreadsheetId","value":"REPLACE_WITH_GOOGLE_SPREADSHEET_ID","type":"string"},{"id":"f9ea7e50-d1a2-46b1-8c8a-cc2504bfd611","name":"sheetName","value":"Properties","type":"string"}]},"options":{}},"id":"87cb9201-2725-4067-902e-92ec82f58201","name":"Settings","type":"n8n-nodes-base.set","typeVersion":3.4,"position":[220,300]},{"parameters":{"mode":"runOnceForAllItems","jsCode":"const c = { ...$input.first().json };\nconst integer = (name, min) => {\n  if (!Number.isSafeInteger(c[name]) || c[name] < min)\n    throw new Error(name + ' must be an integer of at least ' + min + '.');\n};\ninteger('searchLimit', 20);\ninteger('detailLimit', 0);\nif (c.detailLimit > c.searchLimit) throw new Error('detailLimit cannot exceed searchLimit.');\nfor (const key of ['maxEnrichmentPrice', 'minEnrichmentBeds']) {\n  if (typeof c[key] !== 'number' || !Number.isFinite(c[key]) || c[key] < 0)\n    throw new Error(key + ' must be a non-negative number.');\n}\nfor (const key of ['searchBudgetUsd', 'detailsBudgetUsd']) {\n  if (typeof c[key] !== 'number' || !Number.isFinite(c[key]) || c[key] < 0.10 || c[key] > 100)\n    throw new Error(key + ' must be between 0.10 and 100 USD. Check each Actor Pricing tab for its current minimum.');\n}\nconst zipCodes = [...new Set(String(c.zipCodes).split(',').map(x => x.trim()))];\nif (!zipCodes.length || zipCodes.length > 100 || zipCodes.some(x => !/^\\d{5}$/.test(x)))\n  throw new Error('Enter 1–100 comma-separated five-digit ZIP codes, keeping leading zeros.');\nif (typeof c.spreadsheetId !== 'string' || c.spreadsheetId.includes('REPLACE') || !/^[A-Za-z0-9_-]{20,}$/.test(c.spreadsheetId))\n  throw new Error('Set spreadsheetId to the ID between /d/ and /edit in your Google Sheets URL.');\nif (typeof c.sheetName !== 'string' || !c.sheetName.trim()) throw new Error('Set sheetName to an existing tab.');\nc.sheetName = c.sheetName.trim();\nreturn [{ json: { ...c, zipCodes, searchInput: {\n  zipCodes, listingTypes: ['forSale'], maxResults: c.searchLimit,\n  maxTotalChargeUsd: c.searchBudgetUsd, maxConcurrency: 5,\n} } }];"},"id":"16be51f2-af3a-463a-a7f9-efa75bb230c1","name":"Validate settings","type":"n8n-nodes-base.code","typeVersion":2,"position":[440,300]},{"parameters":{"authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","method":"POST","url":"https://api.apify.com/v2/actors/alol~zillow-search/runs","sendQuery":true,"queryParameters":{"parameters":[{"name":"timeout","value":"600"},{"name":"maxTotalChargeUsd","value":"={{ $('Validate settings').first().json.searchBudgetUsd }}"},{"name":"restartOnError","value":"false"}]},"sendBody":true,"specifyBody":"json","jsonBody":"={{ $json.searchInput }}","options":{"timeout":60000,"response":{"response":{"responseFormat":"json","fullResponse":false}}}},"id":"a8553ffb-8347-4f12-b456-611bd9553218","name":"Start Zillow Search","type":"n8n-nodes-base.httpRequest","typeVersion":4.2,"position":[660,300],"retryOnFail":false,"notes":"Select the same Apify Header Auth credential on all six HTTP Request nodes. Name: Authorization. Value: Bearer YOUR_APIFY_TOKEN.","notesInFlow":false},{"parameters":{"resume":"timeInterval","amount":5,"unit":"seconds"},"id":"f4363c96-c860-492c-bac4-97666ea0680d","name":"Wait for Search","type":"n8n-nodes-base.wait","typeVersion":1.1,"position":[880,300],"webhookId":"144f9d28-db2f-4266-b3f1-8b73fbca8565"},{"parameters":{"authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","url":"={{ 'https://api.apify.com/v2/actor-runs/' + $('Start Zillow Search').first().json.data.id }}","options":{"timeout":60000,"response":{"response":{"responseFormat":"json","fullResponse":false}}}},"id":"0d1576ae-c5c9-4bb4-ab1b-e0bb40819cd4","name":"Get Search run","type":"n8n-nodes-base.httpRequest","typeVersion":4.2,"position":[1100,300],"retryOnFail":true,"maxTries":3,"waitBetweenTries":3000,"notes":"Select the same Apify Header Auth credential on all six HTTP Request nodes. Name: Authorization. Value: Bearer YOUR_APIFY_TOKEN.","notesInFlow":false},{"parameters":{"mode":"runOnceForAllItems","jsCode":"const run = $input.first().json.data;\nconst started = $('Start Zillow Search').first().json.data;\nif (!run || !/^[A-Za-z0-9]+$/.test(run.id ?? '') || run.id !== started?.id)\n  throw new Error('Unexpected Apify run response. Inspect the previous HTTP node.');\nif (['FAILED', 'ABORTED', 'TIMED-OUT'].includes(run.status))\n  throw new Error('Apify run ' + run.id + ' ended with ' + run.status + '. Inspect its log and dataset in Apify before retrying; partial output may exist.');\nif (run.status === 'SUCCEEDED') {\n  if (!/^[A-Za-z0-9]+$/.test(run.defaultDatasetId ?? '')) throw new Error('Successful run has no valid dataset ID.');\n  return [{ json: { ...run, ready: true } }];\n}\nif (!['READY', 'RUNNING', 'TIMING-OUT', 'ABORTING'].includes(run.status))\n  throw new Error('Unknown Apify run status: ' + run.status);\nconst startedAt = Date.parse(started.startedAt);\nif (!Number.isFinite(startedAt) || Date.now() - startedAt > 15 * 60 * 1000)\n  throw new Error('Stopped waiting for Apify run ' + run.id + '. Check it in Apify. Stopping n8n does not abort the Actor.');\nreturn [{ json: { ...run, ready: false } }];"},"id":"5a058307-d115-4aa8-8f1b-1b5e8a69e949","name":"Check Search run","type":"n8n-nodes-base.code","typeVersion":2,"position":[1320,300]},{"parameters":{"conditions":{"options":{"caseSensitive":true,"leftValue":"","typeValidation":"strict","version":2},"conditions":[{"id":"d684ebb7-3ac1-4d54-b482-09ef5d35aa8b","leftValue":"={{ $json.ready }}","rightValue":"","operator":{"type":"boolean","operation":"true","singleValue":true}}],"combinator":"and"},"options":{}},"id":"9444faf5-fc12-4c5f-a2ad-3059d232f27e","name":"Search finished","type":"n8n-nodes-base.if","typeVersion":2.2,"position":[1540,300]},{"parameters":{"authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","url":"={{ 'https://api.apify.com/v2/datasets/' + $json.defaultDatasetId + '/items' }}","sendQuery":true,"queryParameters":{"parameters":[{"name":"format","value":"json"},{"name":"limit","value":"250"}]},"options":{"timeout":60000,"response":{"response":{"responseFormat":"json","fullResponse":true}},"pagination":{"pagination":{"paginationMode":"updateAParameterInEachRequest","parameters":{"parameters":[{"type":"qs","name":"offset","value":"={{ $pageCount === 0 ? 0 : Number($response.headers['x-apify-pagination-offset']) + $response.body.length }}"}]},"paginationCompleteWhen":"other","completeExpression":"={{ !Array.isArray($response.body) || $response.body.length === 0 || !/^\\d+$/.test(String($response.headers?.['x-apify-pagination-total'] ?? '')) || !/^\\d+$/.test(String($response.headers?.['x-apify-pagination-offset'] ?? '')) || Number($response.headers['x-apify-pagination-offset']) + $response.body.length >= Number($response.headers['x-apify-pagination-total']) }}","limitPagesFetched":false}}}},"id":"aa2d6053-166a-4003-bac1-0a9996fd9dad","name":"Get search listings","type":"n8n-nodes-base.httpRequest","typeVersion":4.2,"position":[1760,200],"retryOnFail":true,"maxTries":3,"waitBetweenTries":3000,"notes":"Select the same Apify Header Auth credential on all six HTTP Request nodes. Name: Authorization. Value: Bearer YOUR_APIFY_TOKEN.","notesInFlow":false},{"parameters":{"mode":"runOnceForAllItems","jsCode":"const rows = [];\nlet expectedTotal;\nfor (const { json: page } of $input.all()) {\n  if (page.statusCode !== 200 || !Array.isArray(page.body))\n    throw new Error('Expected a full Apify dataset response with a JSON array.');\n  const headerNumber = name => {\n    const value = page.headers?.['x-apify-pagination-' + name];\n    if (!/^\\d+$/.test(String(value ?? '')) || !Number.isSafeInteger(Number(value)))\n      throw new Error('Invalid Apify dataset pagination header: ' + name);\n    return Number(value);\n  };\n  const offset = headerNumber('offset');\n  const total = headerNumber('total');\n  expectedTotal ??= total;\n  if (total !== expectedTotal || offset !== rows.length || offset + page.body.length > total ||\n      (page.body.length === 0 && offset < total))\n    throw new Error('Inconsistent Apify dataset pages. Export stopped before writing to Google Sheets.');\n  for (const row of page.body) rows.push(row);\n}\nif (rows.length !== expectedTotal)\n  throw new Error('Incomplete Apify dataset. Export stopped before writing to Google Sheets.');\nconst config = $('Validate settings').first().json;\nconst unique = new Map();\nfor (const row of rows) {\n  if (!row || typeof row !== 'object' || row.error || !/^\\d{1,32}$/.test(String(row.zpid ?? '')))\n    throw new Error('Search returned a row without a valid ZPID. Inspect the dataset before exporting.');\n  if (!unique.has(String(row.zpid))) unique.set(String(row.zpid), row);\n}\nconst listings = [...unique.values()];\nif (!listings.length) return [];\nconst hasNumber = x => typeof x === 'number' && Number.isFinite(x);\nconst selected = listings.filter(row =>\n  (config.maxEnrichmentPrice === 0 || (hasNumber(row.price) && row.price >= 0 && row.price <= config.maxEnrichmentPrice)) &&\n  (config.minEnrichmentBeds === 0 || (hasNumber(row.beds) && row.beds >= config.minEnrichmentBeds))\n).sort((a, b) => {\n  const priceA = hasNumber(a.price) ? a.price : Infinity;\n  const priceB = hasNumber(b.price) ? b.price : Infinity;\n  return (priceA < priceB ? -1 : priceA > priceB ? 1 : 0) || String(a.zpid).localeCompare(String(b.zpid));\n}).slice(0, config.detailLimit);\nconst selectedZpids = selected.map(row => String(row.zpid));\nreturn [{ json: {\n  listings, selectedZpids, hasTargets: selected.length > 0,\n} }];"},"id":"32846e42-2217-44bc-94a4-9f1b18732242","name":"Select properties to enrich","type":"n8n-nodes-base.code","typeVersion":2,"position":[1980,200]},{"parameters":{"conditions":{"options":{"caseSensitive":true,"leftValue":"","typeValidation":"strict","version":2},"conditions":[{"id":"98e705be-c4e4-477d-9de5-a5d97f41400c","leftValue":"={{ $json.hasTargets }}","rightValue":"","operator":{"type":"boolean","operation":"true","singleValue":true}}],"combinator":"and"},"options":{}},"id":"4c7bd756-efeb-4c39-b635-8b77dc9421a8","name":"Enrich selected properties","type":"n8n-nodes-base.if","typeVersion":2.2,"position":[2200,200]},{"parameters":{"authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","method":"POST","url":"https://api.apify.com/v2/actors/alol~zillow-property-details/runs","sendQuery":true,"queryParameters":{"parameters":[{"name":"timeout","value":"600"},{"name":"maxTotalChargeUsd","value":"={{ $json.detailsInput.maxTotalChargeUsd }}"},{"name":"restartOnError","value":"false"}]},"sendBody":true,"specifyBody":"json","jsonBody":"={{ $json.detailsInput }}","options":{"timeout":60000,"response":{"response":{"responseFormat":"json","fullResponse":false}}}},"id":"383a084e-3679-4702-841c-6d552dd5fdd5","name":"Start Property Details","type":"n8n-nodes-base.httpRequest","typeVersion":4.2,"position":[2860,100],"retryOnFail":false,"notes":"Select the same Apify Header Auth credential on all six HTTP Request nodes. Name: Authorization. Value: Bearer YOUR_APIFY_TOKEN.","notesInFlow":false},{"parameters":{"resume":"timeInterval","amount":5,"unit":"seconds"},"id":"f3098270-da7d-4460-93c5-4d0486c5721a","name":"Wait for Details","type":"n8n-nodes-base.wait","typeVersion":1.1,"position":[3080,100],"webhookId":"825a8bbb-ca38-4217-b9f9-c65169e6ae55"},{"parameters":{"authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","url":"={{ 'https://api.apify.com/v2/actor-runs/' + $('Start Property Details').item.json.data.id }}","options":{"timeout":60000,"response":{"response":{"responseFormat":"json","fullResponse":false}}}},"id":"13530e97-cfa1-4617-a47d-8465c0c712a9","name":"Get Details run","type":"n8n-nodes-base.httpRequest","typeVersion":4.2,"position":[3300,100],"retryOnFail":true,"maxTries":3,"waitBetweenTries":3000,"notes":"Select the same Apify Header Auth credential on all six HTTP Request nodes. Name: Authorization. Value: Bearer YOUR_APIFY_TOKEN.","notesInFlow":false},{"parameters":{"mode":"runOnceForAllItems","jsCode":"const run = $input.first().json.data;\nconst started = $('Start Property Details').itemMatching(0).json.data;\nif (!run || !/^[A-Za-z0-9]+$/.test(run.id ?? '') || run.id !== started?.id)\n  throw new Error('Unexpected Apify run response. Inspect the previous HTTP node.');\nif (['FAILED', 'ABORTED', 'TIMED-OUT'].includes(run.status))\n  throw new Error('Apify run ' + run.id + ' ended with ' + run.status + '. Inspect its log and dataset in Apify before retrying; partial output may exist.');\nif (run.status === 'SUCCEEDED') {\n  if (!/^[A-Za-z0-9]+$/.test(run.defaultDatasetId ?? '')) throw new Error('Successful run has no valid dataset ID.');\n  return [{ json: { ...run, ready: true } }];\n}\nif (!['READY', 'RUNNING', 'TIMING-OUT', 'ABORTING'].includes(run.status))\n  throw new Error('Unknown Apify run status: ' + run.status);\nconst startedAt = Date.parse(started.startedAt);\nif (!Number.isFinite(startedAt) || Date.now() - startedAt > 15 * 60 * 1000)\n  throw new Error('Stopped waiting for Apify run ' + run.id + '. Check it in Apify. Stopping n8n does not abort the Actor.');\nreturn [{ json: { ...run, ready: false } }];"},"id":"f3f14074-27ea-4c69-9598-4f8d5b203f5b","name":"Check Details run","type":"n8n-nodes-base.code","typeVersion":2,"position":[3520,100]},{"parameters":{"conditions":{"options":{"caseSensitive":true,"leftValue":"","typeValidation":"strict","version":2},"conditions":[{"id":"f697432f-d945-4f66-b25d-476a4c16e65a","leftValue":"={{ $json.ready }}","rightValue":"","operator":{"type":"boolean","operation":"true","singleValue":true}}],"combinator":"and"},"options":{}},"id":"f9f98911-96e0-40ae-b3cb-4510eab409c1","name":"Details finished","type":"n8n-nodes-base.if","typeVersion":2.2,"position":[3740,100]},{"parameters":{"authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","url":"={{ 'https://api.apify.com/v2/datasets/' + $json.defaultDatasetId + '/items' }}","sendQuery":true,"queryParameters":{"parameters":[{"name":"format","value":"json"},{"name":"limit","value":"250"}]},"options":{"timeout":60000,"response":{"response":{"responseFormat":"json","fullResponse":true}},"pagination":{"pagination":{"paginationMode":"updateAParameterInEachRequest","parameters":{"parameters":[{"type":"qs","name":"offset","value":"={{ $pageCount === 0 ? 0 : Number($response.headers['x-apify-pagination-offset']) + $response.body.length }}"}]},"paginationCompleteWhen":"other","completeExpression":"={{ !Array.isArray($response.body) || $response.body.length === 0 || !/^\\d+$/.test(String($response.headers?.['x-apify-pagination-total'] ?? '')) || !/^\\d+$/.test(String($response.headers?.['x-apify-pagination-offset'] ?? '')) || Number($response.headers['x-apify-pagination-offset']) + $response.body.length >= Number($response.headers['x-apify-pagination-total']) }}","limitPagesFetched":false}}}},"id":"abecfd2a-22f3-4312-b756-3672ea15ddb0","name":"Get property details","type":"n8n-nodes-base.httpRequest","typeVersion":4.2,"position":[3960,0],"retryOnFail":true,"maxTries":3,"waitBetweenTries":3000,"notes":"Select the same Apify Header Auth credential on all six HTTP Request nodes. Name: Authorization. Value: Bearer YOUR_APIFY_TOKEN.","notesInFlow":false},{"parameters":{"mode":"runOnceForAllItems","jsCode":"const selection = $('Select properties to enrich').first().json;\nconst batches = selection.hasTargets ? $input.all().map(item => item.json) : [];\nconst runByZpid = new Map();\nconst selected = new Set(selection.selectedZpids);\nconst byId = new Map();\nfor (const { runId, zpids, rows } of batches) {\n  if (!/^[A-Za-z0-9]+$/.test(runId ?? '')) throw new Error('Missing detail run ID.');\n  const batchTargets = new Set(zpids);\n  for (const zpid of batchTargets) {\n    if (!selected.has(zpid) || runByZpid.has(zpid))\n      throw new Error('Unexpected or repeated ZPID in detail batches.');\n    runByZpid.set(zpid, runId);\n  }\n  for (const row of rows) {\n    const urlId = typeof row.url === 'string' ? row.url.match(/\\/(\\d+)_zpid(?:\\/|$|[?#])/)?.[1] : undefined;\n    const id = String(row.externalId ?? row.propertyId ?? urlId ?? '');\n    if (!batchTargets.has(id)) throw new Error('A detail row cannot be matched to a selected ZPID. Inspect the dataset; no sheet rows were written.');\n    if (row.propertyId != null && String(row.propertyId) !== id)\n      throw new Error('Detail propertyId does not match externalId. Refusing to attach data to the wrong property.');\n    if (byId.has(id)) throw new Error('Duplicate detail ZPID: ' + id);\n    if (!row.error && (row.recordType !== 'propertyDetail' || row.schemaVersion !== 1 || !['complete', 'partial', 'notFound'].includes(row.status)))\n      throw new Error('Unsupported property-detail schema or status. Inspect the dataset before exporting.');\n    byId.set(id, row);\n  }\n}\nif (runByZpid.size !== selected.size) throw new Error('A detail batch is missing.');\nconst searchRunId = $('Start Zillow Search').first().json.data.id;\nconst exportedAt = new Date().toISOString();\nconst text = value => value == null ? '' : String(value);\nconst number = (...values) => values.find(x => typeof x === 'number' && Number.isFinite(x)) ?? '';\nconst history = (items, key) => {\n  if (!Array.isArray(items) || items.length === 0) return '';\n  const latest = [...items].sort((a,b) => String(b[key] ?? '').localeCompare(String(a[key] ?? ''))).slice(0, 10);\n  const result = JSON.stringify(latest);\n  if (result.length > 45000) throw new Error('History exceeds a spreadsheet cell limit. Reduce history columns before exporting.');\n  return result;\n};\nreturn selection.listings.map(listing => {\n  const zpid = String(listing.zpid);\n  const d = byId.get(zpid);\n  const valid = d && !d.error && ['complete', 'partial'].includes(d.status) ? d : {};\n  const a = valid.location?.address ?? {};\n  return { json: {\n    zpid,\n    property_url: text(valid.url ?? listing.url),\n    address: text(a.full ?? listing.address?.full ?? listing.address?.street),\n    city: text(a.city ?? listing.address?.city),\n    state: text(a.stateCode ?? listing.address?.state),\n    zip_code: text(a.postalCode ?? listing.address?.zip),\n    listing_status: text(listing.status),\n    price_usd: number(valid.pricing?.list, listing.price),\n    beds: number(valid.facts?.beds, listing.beds),\n    baths: number(valid.facts?.baths, listing.baths),\n    living_area_sqft: number(valid.facts?.sqft, listing.livingAreaSqft),\n    year_built: number(valid.facts?.yearBuilt, listing.yearBuilt),\n    home_type: text(valid.facts?.type ?? listing.homeType),\n    latitude: number(valid.location?.coordinates?.latitude, listing.latitude),\n    longitude: number(valid.location?.coordinates?.longitude, listing.longitude),\n    detail_status: d ? (d.error ? 'error' : d.status) : (selected.has(zpid) ? 'not_returned' : 'not_selected'),\n    detail_missing_sections: Array.isArray(d?.quality?.missingSections) ? d.quality.missingSections.join(', ') : '',\n    detail_error: d?.error ? text(d.message ?? d.error) : '',\n    price_history_json: history(valid.history?.property, 'date'),\n    tax_history_json: history(valid.history?.tax, 'year'),\n    search_quality: JSON.stringify(listing.quality ?? {}),\n    search_scraped_at: text(listing.scrapedAt),\n    detail_scraped_at: text(d?.scrapedAt),\n    exported_at: exportedAt,\n    search_run_id: searchRunId,\n    details_run_id: runByZpid.get(zpid) ?? '',\n  } };\n});"},"id":"08c1b5fd-90eb-4267-90a6-3978aa165582","name":"Prepare sheet rows","type":"n8n-nodes-base.code","typeVersion":2,"position":[4400,200]},{"parameters":{"resource":"sheet","operation":"appendOrUpdate","documentId":{"__rl":true,"value":"={{ $('Validate settings').first().json.spreadsheetId }}","mode":"id"},"sheetName":{"__rl":true,"value":"={{ $('Validate settings').first().json.sheetName }}","mode":"name"},"columns":{"mappingMode":"autoMapInputData","value":{},"matchingColumns":["zpid"],"schema":[{"id":"zpid","displayName":"zpid","required":false,"defaultMatch":true,"display":true,"type":"string","canBeUsedToMatch":true},{"id":"property_url","displayName":"property_url","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"address","displayName":"address","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"city","displayName":"city","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"state","displayName":"state","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"zip_code","displayName":"zip_code","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"listing_status","displayName":"listing_status","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"price_usd","displayName":"price_usd","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"beds","displayName":"beds","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"baths","displayName":"baths","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"living_area_sqft","displayName":"living_area_sqft","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"year_built","displayName":"year_built","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"home_type","displayName":"home_type","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"latitude","displayName":"latitude","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"longitude","displayName":"longitude","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"detail_status","displayName":"detail_status","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"detail_missing_sections","displayName":"detail_missing_sections","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"detail_error","displayName":"detail_error","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"price_history_json","displayName":"price_history_json","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"tax_history_json","displayName":"tax_history_json","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"search_quality","displayName":"search_quality","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"search_scraped_at","displayName":"search_scraped_at","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"detail_scraped_at","displayName":"detail_scraped_at","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"exported_at","displayName":"exported_at","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"search_run_id","displayName":"search_run_id","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false},{"id":"details_run_id","displayName":"details_run_id","required":false,"defaultMatch":false,"display":true,"type":"string","canBeUsedToMatch":false}],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{"cellFormat":"RAW","handlingExtraData":"error","useAppend":true}},"id":"f03bf7e9-6260-4653-9034-12362b0c45c9","name":"Upsert Google Sheets","type":"n8n-nodes-base.googleSheets","typeVersion":4.7,"position":[4840,100],"notes":"Connect Google Sheets OAuth2. Create the tab and import headers.csv first. Match on zpid. Run one execution at a time to avoid concurrent inserts.","notesInFlow":true},{"parameters":{"content":"## Zillow listings to Google Sheets\n1. Import headers.csv into a new tab named Properties.\n2. Edit Settings: spreadsheet ID, ZIP codes, shortlist and budgets.\n3. Create Header Auth: Authorization = Bearer YOUR_APIFY_TOKEN. Select it on all six HTTP nodes.\n4. Connect Google Sheets on the last node.\n5. Execute manually. Open the accompanying `article.md` file for the walkthrough.\n\nAll found listings are exported; only the shortlist is enriched. No schedule is enabled.","height":330,"width":620},"id":"1d9be7c6-df96-424c-8f61-71fb2bd1f62e","name":"Setup guide","type":"n8n-nodes-base.stickyNote","typeVersion":1,"position":[0,-120]},{"parameters":{"content":"## Choose where to spend on details\nDefault: at most 5 properties, price ≤ $1M, beds ≥ 2.\nEligible properties are sorted by asking price ascending, then ZPID.\nSet detailLimit = 0 to export search results only.\nA zero-result search ends without writing sheet rows.\nDatasets are paginated. Selected properties are processed in runs of up to 1,000 targets, sharing the configured details budget.","height":260,"width":610},"id":"6ef58606-52e6-4f59-9658-668b13389e49","name":"Selection guide","type":"n8n-nodes-base.stickyNote","typeVersion":1,"position":[1760,-180]},{"parameters":{"content":"## One row per ZPID\nRepeated sequential executions update matching rows.\nRows absent from a later search remain in the sheet.\nDetail fields refresh on each observed row, including blanks when not enriched. This is not a price-history monitor.\nHistory JSON contains up to 10 newest available entries.\nFailed Actor runs stop before any sheet writes.\nThe Sheets node upserts 100 rows per batch. Earlier batches can remain written if a later Google Sheets batch fails.","height":300,"width":620},"id":"ab3496f8-c1e6-4a5f-8388-d1f288e357e8","name":"Output guide","type":"n8n-nodes-base.stickyNote","typeVersion":1,"position":[4400,-260]},{"name":"Prepare detail batches","type":"n8n-nodes-base.code","typeVersion":2,"position":[2420,100],"parameters":{"jsCode":"const { selectedZpids } = $input.first().json;\nconst totalBudget = $('Validate settings').first().json.detailsBudgetUsd;\n// Apify's propertyTargets input permits at most 1,000 targets per run.\nconst batchSize = 1000;\nconst batchCount = Math.ceil(selectedZpids.length / batchSize);\nconst totalCents = Math.floor(totalBudget * 100 + 1e-9);\nif (totalCents < 10 * batchCount)\n  throw new Error('Increase detailsBudgetUsd to allow at least $0.10 for each of the ' + batchCount + ' detail runs.');\n\nconst remainingCents = totalCents - 10 * batchCount;\nconst batches = [];\nfor (let index = 0; index < batchCount; index++) {\n  const start = index * batchSize;\n  const stop = Math.min(start + batchSize, selectedZpids.length);\n  const zpids = selectedZpids.slice(start, stop);\n  const allocatedCents = position => Math.round(remainingCents * (position / selectedZpids.length));\n  const batchCents = 10 + allocatedCents(stop) - allocatedCents(start);\n  const maxTotalChargeUsd = batchCount === 1 ? totalBudget : batchCents / 100;\n  batches.push({ json: { zpids, detailsInput: {\n    propertyTargets: zpids.map(zpid => ({ zpid, externalId: zpid })),\n    maxResults: zpids.length,\n    maxTotalChargeUsd,\n    maxConcurrency: 5,\n  } }, pairedItem: { item: 0 } });\n}\nreturn batches;"},"id":"3ef102de-0a9e-415d-98a3-8e4501006510"},{"name":"Loop over detail batches","type":"n8n-nodes-base.splitInBatches","typeVersion":3,"position":[2640,100],"parameters":{"batchSize":1,"options":{}},"id":"e7401f73-fc56-44d6-82cd-2ba1f45c170c"},{"name":"Collect detail batch","type":"n8n-nodes-base.code","typeVersion":2,"position":[4180,0],"parameters":{"jsCode":"const rows = [];\nlet expectedTotal;\nfor (const { json: page } of $input.all()) {\n  if (page.statusCode !== 200 || !Array.isArray(page.body))\n    throw new Error('Expected a full Apify dataset response with a JSON array.');\n  const headerNumber = name => {\n    const value = page.headers?.['x-apify-pagination-' + name];\n    if (!/^\\d+$/.test(String(value ?? '')) || !Number.isSafeInteger(Number(value)))\n      throw new Error('Invalid Apify dataset pagination header: ' + name);\n    return Number(value);\n  };\n  const offset = headerNumber('offset');\n  const total = headerNumber('total');\n  expectedTotal ??= total;\n  if (total !== expectedTotal || offset !== rows.length || offset + page.body.length > total ||\n      (page.body.length === 0 && offset < total))\n    throw new Error('Inconsistent Apify dataset pages. Export stopped before writing to Google Sheets.');\n  for (const row of page.body) rows.push(row);\n}\nif (rows.length !== expectedTotal)\n  throw new Error('Incomplete Apify dataset. Export stopped before writing to Google Sheets.');\nconst { id } = $('Check Details run').itemMatching(0).json;\nconst { zpids } = $('Loop over detail batches').itemMatching(0).json;\nreturn [{ json: { runId: id, zpids, rows }, pairedItem: { item: 0 } }];"},"id":"215e827b-0b55-4d0b-8e53-cf65caa05ee1"},{"name":"Loop over sheet rows","type":"n8n-nodes-base.splitInBatches","typeVersion":3,"position":[4620,200],"parameters":{"batchSize":100,"options":{}},"id":"cd0e50ca-6924-4c43-82ba-14393a944e9b"}],"pinData":{},"connections":{"Run manually":{"main":[[{"node":"Settings","type":"main","index":0}]]},"Settings":{"main":[[{"node":"Validate settings","type":"main","index":0}]]},"Validate settings":{"main":[[{"node":"Start Zillow Search","type":"main","index":0}]]},"Start Zillow Search":{"main":[[{"node":"Wait for Search","type":"main","index":0}]]},"Wait for Search":{"main":[[{"node":"Get Search run","type":"main","index":0}]]},"Get Search run":{"main":[[{"node":"Check Search run","type":"main","index":0}]]},"Check Search run":{"main":[[{"node":"Search finished","type":"main","index":0}]]},"Search finished":{"main":[[{"node":"Get search listings","type":"main","index":0}],[{"node":"Wait for Search","type":"main","index":0}]]},"Get search listings":{"main":[[{"node":"Select properties to enrich","type":"main","index":0}]]},"Select properties to enrich":{"main":[[{"node":"Enrich selected properties","type":"main","index":0}]]},"Enrich selected properties":{"main":[[{"node":"Prepare detail batches","type":"main","index":0}],[{"node":"Prepare sheet rows","type":"main","index":0}]]},"Start Property Details":{"main":[[{"node":"Wait for Details","type":"main","index":0}]]},"Wait for Details":{"main":[[{"node":"Get Details run","type":"main","index":0}]]},"Get Details run":{"main":[[{"node":"Check Details run","type":"main","index":0}]]},"Check Details run":{"main":[[{"node":"Details finished","type":"main","index":0}]]},"Details finished":{"main":[[{"node":"Get property details","type":"main","index":0}],[{"node":"Wait for Details","type":"main","index":0}]]},"Get property details":{"main":[[{"node":"Collect detail batch","type":"main","index":0}]]},"Prepare sheet rows":{"main":[[{"node":"Loop over sheet rows","type":"main","index":0}]]},"Prepare detail batches":{"main":[[{"node":"Loop over detail batches","type":"main","index":0}]]},"Loop over detail batches":{"main":[[{"node":"Prepare sheet rows","type":"main","index":0}],[{"node":"Start Property Details","type":"main","index":0}]]},"Collect detail batch":{"main":[[{"node":"Loop over detail batches","type":"main","index":0}]]},"Loop over sheet rows":{"main":[[],[{"node":"Upsert Google Sheets","type":"main","index":0}]]},"Upsert Google Sheets":{"main":[[{"node":"Loop over sheet rows","type":"main","index":0}]]}},"active":false,"settings":{"executionOrder":"v1"},"tags":[]}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)