Redfin Estimate and Sold Comps API in Python: AVM vs Closed Sales
The usual shortcut is to treat the Redfin Estimate as the home's value. Resolve a listing, print one AVM, drop it in a spreadsheet, ship the number. That assumption is wrong in the way that matters for pricing: an automated valuation is a model output, not a close. It does not tell you whether nearby buyers paid anything like that last quarter, whether this house flipped six months ago, or whether the tax roll still thinks it is a 2019 property.
The naive script calls estimate and stops. The correct script triangulates three sources that are supposed to disagree: the AVM, a soldWithin-filtered sold set, and the subject's own sale-and-tax timeline. That is the whole Redfin Estimate and sold comps job in Python.
Copying anything below does not send a request. Calls run only when you execute them with an authorized key from the dashboard after you sign in. Read it from OPENDATA_API_KEY, keep it server-side, and never paste full query URLs into tickets or screenshots — the key rides on the query string. This is unofficial public listing content, not an affiliated Redfin product, and not an appraisal.
An estimate without sold comps is a guess
estimate answers one question: what does the model think this listing is worth right now. An asking price answers a different one. A recorded close answers a third. Treating any of those as "the value" is how a point estimate lands in a market that only ever clears as a range.
Sold comps are the check, not decoration. Start with a recency window and the same bed/bath/size band as the subject. soldWithin only accepts 7, 30, 90, 180, 365, 730, 1095 or 1825 days — you cannot invent "last 45 days." Ninety days is the usual comp default; shorter is fresher and thinner. If the filtered set is empty, the honest output is "no comps," not "use the AVM anyway." If the AVM sits well above the median sold price per square foot, the AVM is the thing you explain.
HTTP 200 is not success. The gateway envelope carries code, message and data; treat code 200 as business success. Search payloads add their own status_code next to the data array. Autocomplete is worse: a miss is still HTTP 200 with hasFakeResults=true and a sentinel row id of 23_null. v2-details currently reports an unknown propertyId as a bare HTTP 500 — that is not-found, not "retry until it works."
import os
import requests
# Naive: one AVM printout, no sold set, no subject history.
r = requests.get(
"https://api.opendata-api.com/api/project/redfin/estimate",
params={
"key": os.environ["OPENDATA_API_KEY"],
"propertyId": "40775351",
"listingId": "224185786",
},
timeout=30,
)
print(r.json()) # a model guess, not a value range
Address to propertyId
estimate and sale-and-tax history both require the propertyId / listingId pair. They will not take a street address. Stuffing location=123 Main St into estimate is the wrong operation.
Use v2-details. Its location parameter accepts a propertyId (the documented example is 40775351), a street address, an address slug, a short path, or a full listing URL. initialInfo is where propertyId and listingId live; hasAvm tells you whether running estimate is even plausible. Take both IDs from the same record — never mix a propertyId from one row with a listingId from another.
When the job is "comps around a city or ZIP" rather than "this house," start with property-auto-complete instead. location=New York is the documented probe. Read rows[].id for a region token such as 6_30749, and subName for the canonical New York, NY, USA string. Check hasFakeResults before you touch either. Feed id into region-search-for-sold; feed subName or a ZIP into location-search-for-sold. There is no official public Redfin developer API to bypass this identity step — these GET routes are the structured path; do not scrape HTML for IDs.
Estimate, then the sold set
Once the pair exists, call estimate with both IDs, then immediately pull sold rows in the same attribute band. Do not stop after the AVM. The script below is the correct order: resolve, value, sold set, history. Store the retrieval date next to any figure you keep. The estimate schema is not a frozen fixture, so the extractor looks for a numeric field rather than pretending one key always exists.
import os
import statistics
from datetime import date
import requests
BASE = "https://api.opendata-api.com/api/project/redfin"
API_KEY = os.environ["OPENDATA_API_KEY"]
def call(operation, **params):
try:
response = requests.get(
f"{BASE}/{operation}",
params={**params, "key": API_KEY},
timeout=30,
)
except requests.RequestException:
raise RuntimeError("Request failed; use redacted diagnostics") from None
if operation == "v2-details" and response.status_code >= 500:
raise RuntimeError("v2-details HTTP 5xx; treat as not found, do not retry")
if not response.ok:
raise RuntimeError(f"HTTP {response.status_code}")
gateway = response.json()
if not isinstance(gateway, dict) or str(gateway.get("code")) != "200":
raise RuntimeError("Gateway business failure; inspect code/message safely")
payload = gateway.get("data")
if not isinstance(payload, dict):
raise ValueError("Unexpected operation payload")
return payload
def find_number(node, needle):
# Adaptive extraction: the estimate schema is not fixed.
if isinstance(node, dict):
for key, value in node.items():
if needle in key.lower() and isinstance(value, (int, float)):
return value
found = find_number(value, needle)
if found is not None:
return found
elif isinstance(node, list):
for item in node:
found = find_number(item, needle)
if found is not None:
return found
return None
def nested(payload, *keys):
node = payload
for key in keys:
if not isinstance(node, dict):
return None
node = node.get(key)
return node
# location accepts an id, address, slug or listing URL.
detail = call("v2-details", location="40775351")
info = nested(detail, "initialInfo") or nested(detail, "data", "initialInfo") or {}
property_id = info.get("propertyId")
listing_id = info.get("listingId")
if not property_id or not listing_id:
raise ValueError("No propertyId/listingId pair in v2-details")
print("retrieved", date.today().isoformat())
print("hasAvm", info.get("hasAvm"))
estimate_payload = call("estimate", propertyId=property_id, listingId=listing_id)
avm = find_number(estimate_payload, "estimate")
print("Redfin Estimate:", "unavailable" if avm is None else avm)
sold = call(
"location-search-for-sold",
location="New York, NY, USA",
soldWithin=90,
numBeds=2,
limit=50,
)
rows = sold.get("data") if isinstance(sold.get("data"), list) else []
comps = []
for row in rows:
home = row.get("homeData") or {}
price = (home.get("priceInfo") or {}).get("amount")
sqft = (home.get("sqftInfo") or {}).get("amount")
if price and sqft:
comps.append(price / sqft)
if not comps:
print("No usable sold comps; refuse a point value")
else:
median = statistics.median(comps)
print(
f"Comps: {len(comps)} sales, median ${median:,.0f}/sqft, "
f"range ${min(comps):,.0f}-${max(comps):,.0f}/sqft"
)
history = call(
"history-info-sale-and-tax-history",
propertyId=property_id,
listingId=listing_id,
)
print("History payload keys:", sorted(history.keys()) if isinstance(history, dict) else "unavailable")
Each sold row wraps homeData with propertyId, listingId, priceInfo.amount, sqftInfo.amount, beds, baths, lotSize and addressInfo — the same shape as for-sale search, so one parser covers both. Page with page / limit (up to 350) and deduplicate on the ID pair. A ZIP-shaped job skips autocomplete: pass the ZIP as location to location-search-for-sold with soldWithin=90.
Tax history as the tie-break
When the AVM and the comp band disagree, history-info-sale-and-tax-history is the tie-break, not a fourth guess. It uses the same pair. Neighbors' closes tell you the street; this route tells you the subject: recorded sale events and assessment cycles.
A last close inside the soldWithin window that sits far below the AVM is a flip or distress signal, not proof the model is currently right. A tax assessment that has not moved while nearby sold prices have is lag, not confirmation. Plot the timeline; do not average it into the AVM. If history keys are missing, leave them missing — do not invent a prior sale. Repeat events on the same propertyId are how you notice a quick resale without scraping a public-records portal.
What still will not be a full CMA
This pipeline is triangulation, not a Comparative Market Analysis. A CMA still needs condition, concessions, photos, HOA documents, and someone who walked the property. The API will not score a kitchen remodel or a noisy lot.
Thin sets are a stop, not a nudge toward the AVM. Mixed condo and single-family rows in the same band contaminate the median. Seller concessions are not in priceInfo.amount. soldWithin cannot express an arbitrary date range. v2-details 5xx is not-found. Unofficial public data moves; re-pull rather than caching one number as truth. Present a range, or present "insufficient comps." Do not present a single Redfin Estimate as the value.