# US Code Violations Tracker: NYC, Chicago, LA, Detroit (`metal_spinney/us-code-violations`) Actor

Housing and building code violations from official open data (NYC HPD and DOB, Chicago, Los Angeles, Detroit blight tickets). Filter by keyword, ZIP and status, with a new-since-last-run mode for property investor, pest control and remediation leads.

- **URL**: https://apify.com/metal_spinney/us-code-violations.md
- **Developed by:** [Open Registry Data](https://apify.com/metal_spinney) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## US Code Violations Scraper: NYC, Chicago, Los Angeles, Detroit

Pull **building, housing and blight code violations** from official city open-data portals into one normalized schema: **NYC HPD housing violations, NYC DOB violations, Chicago Department of Buildings violations, Los Angeles (LADBS) code enforcement cases, and Detroit blight tickets**. No login, no API key, no browser. Filter by **keyword (mold, rodent, lead, heat, fire escape...), ZIP code, status and date range**. **Diff mode** returns only violations that are new since the last run.

**Keywords:** code violations scraper, building violations, housing code violations, HPD violations, DOB violations, Chicago building violations, LADBS code enforcement, Detroit blight tickets, distressed property leads, motivated seller leads, real estate investor leads, property compliance data, open data API.

### Use cases

- **Real estate investors and wholesalers**: build distressed / motivated-seller lead lists from fresh violations and unpaid blight fines (Detroit includes the fine and balance due).
- **Contractors and service companies**: pest control (rodent/mice), mold remediation, roofing, windows, boilers, elevators, and fire-escape repair, each targeted at the exact address that was just cited.
- **Property managers, lenders and insurers**: monitor a portfolio for new violations (filter by ZIP, run in diff mode).
- **Tenant advocates, journalists and researchers**: track enforcement trends across cities.

### Datasets (`datasets`)

| key | City | Official source |
|---|---|---|
| `nyc-hpd` | New York | HPD Housing Maintenance Code Violations (data.cityofnewyork.us `wvxf-dwi5`) |
| `nyc-dob` | New York | DOB Violations (`3h2n-5cm9`) |
| `chicago` | Chicago | Building Violations (data.cityofchicago.org `22u3-xenr`) |
| `la-open` / `la-closed` | Los Angeles | LADBS Code Enforcement Cases, open / closed (data.lacity.org `u82d-eh7z`, `rken-a55j`) |
| `detroit` | Detroit | Blight Tickets (City of Detroit ArcGIS open data) |
| `customSocrata` | any | Point it at another city's Socrata dataset (advanced) |

### Input example

```json
{ "datasets": ["chicago", "nyc-hpd"], "keywords": ["mold", "rodent", "mice"], "lookbackDays": 7 }
{ "mode": "diff", "datasets": ["detroit"], "zipCodes": ["48227"], "stateKey": "detroit-48227" }
```

### Output (normalized, one item per violation)

`dataset, city, violationId, date, address, borough (or LA area / Detroit neighborhood), zip, category, code, description, status, statusDetail, statusDate, parcelId, buildingId, latitude, longitude, source` (+ `fineAmount, balanceDue` for Detroit; `raw` when `includeRaw` is on; `changeType, firstSeenAt` in diff mode).

Example output (real records, Oct 2026 test run):

```json
[
  {
    "dataset": "nyc-hpd",
    "city": "New York, NY",
    "violationId": "19281631",
    "date": "2026-10-05",
    "address": "179 EAST 54 STREET Apt 1R",
    "borough": "BROOKLYN",
    "zip": "11203",
    "category": "Class A",
    "code": "556",
    "description": "§ 27-2013 ADM CODE PAINT WITH LIGHT COLORED PAINT TO THE SATISFACTION OF THIS DEPARTMENT ALL PEELING PAINT SURFACES IN THE BATHROOM , THE KITCHEN LOCATED AT APT 1R, 1st STORY, 1st APARTMENT FROM NORTH AT EAST",
    "status": "Open",
    "statusDetail": "VIOLATION OPEN",
    "statusDate": "2026-10-05",
    "parcelId": "3046600039",
    "buildingId": "3101545",
    "latitude": 40.654619,
    "longitude": -73.926774
  },
  {
    "dataset": "chicago",
    "city": "Chicago, IL",
    "violationId": "7554231",
    "date": "2026-10-06",
    "address": "739 W BELMONT AVE",
    "borough": null,
    "zip": null,
    "category": "CONSERVATION",
    "code": "CN104015",
    "description": "REPLCE WINDOW PANES, PLEXGLAS — SOUTH ELEVATION AT GRADE / PANES - BROKEN LOUVERED WINDOWS. 14X-3-303.13",
    "status": "OPEN",
    "statusDetail": "FAILED",
    "statusDate": "2026-10-06",
    "parcelId": null,
    "buildingId": "7945",
    "latitude": 41.9398831797,
    "longitude": -87.6483880441
  },
  {
    "dataset": "detroit",
    "city": "Detroit, MI",
    "violationId": "26073643DAH",
    "date": "2026-10-06",
    "address": "15261 FORRER",
    "borough": "Grand River-St Marys",
    "zip": "48227",
    "category": "Buildings, Safety Engineering & Env Department",
    "code": "8-15-472",
    "description": "Failure to maintain or properly install electrical equipment, wiring, or appliance in a safe or approved manner one- or two- family dwelling or building",
    "status": null,
    "statusDetail": "NO PAYMENT APPLIED",
    "statusDate": "2026-10-23",
    "parcelId": "22054455.",
    "buildingId": null,
    "fineAmount": 50.0,
    "balanceDue": 80.0,
    "latitude": 42.401276967,
    "longitude": -83.201938682
  }
]
```

### "New since last run" (diff mode)

Set **Mode = diff** and schedule the actor daily or weekly. Each run looks at a rolling date window and returns **only records it has never returned before**, tagged `changeType: "new"` and `firstSeenAt`. Seen IDs are stored in a named key-value store (`stateStoreName`, separate `stateKey` per saved search), so the state survives between scheduled runs. On the first run you can output the whole window (flagged `baselineRun: true`) or store a silent baseline (`firstRunBehaviour: baselineOnly`). Pair it with an Apify integration (Slack, email, Google Sheets, Zapier, Make, webhook) to get a lead alert feed.

### Notes

- The LA datasets only publish a case type code (e.g. `PACE`, `GENERAL`, `FRP`), not free-text descriptions, so keyword filters don't match LA rows. NYC DOB doesn't publish coordinates.
- Respect each portal's terms. Violations concern addresses and owners, so use the data lawfully (e.g. follow FCRA/TCPA rules when you contact owners).

### Source and licence

Public records from NYC Open Data, the City of Chicago Data Portal, Los Angeles Open Data, and City of Detroit Open Data, used under each portal's open-data terms. Every item carries a `source` block (publisher, dataset URL, retrieval time). Not affiliated with or endorsed by any city.

### Row cap and failure handling

- **`maxRowsPerSource`** (default 5000, 0 = unlimited): per-source cap on raw rows fetched, with automatic pagination. Sources that hit the cap are listed under `cappedSources` in the `OUTPUT` record and in the run's status message.
- **Failures are loud**: if any source fails (HTTP error, ArcGIS error, timeout), the run is marked **FAILED**, the status message names the failed source(s) and error, and the `OUTPUT` key-value record contains `ok: false` and `failedSources`. Rows from a failed source are never returned partially.

# Actor input Schema

## `mode` (type: `string`):

Diff mode remembers IDs already returned (named key-value store) and outputs only new ones. Schedule it daily/weekly for alerts.

## `datasets` (type: `array`):

Which official datasets to query.

## `keywords` (type: `array`):

Case-insensitive substring match on the violation description (OR), e.g. mold, rodent, lead, heat, fire escape. LA cases only carry a case type code.

## `zipCodes` (type: `array`):

Prefix match (NYC HPD, LA, Detroit).

## `statusEquals` (type: `string`):

Exact status value, e.g. Open (NYC HPD), OPEN (Chicago), O (LA).

## `dateFrom` (type: `string`):

YYYY-MM-DD. Overrides lookback days.

## `dateTo` (type: `string`):

YYYY-MM-DD. Default today.

## `lookbackDays` (type: `integer`):

Window size if Date from is empty.

## `maxItems` (type: `integer`):

0 = no limit.

## `perDatasetLimit` (type: `integer`):

Deprecated: use maxRowsPerSource. Overrides it when > 0.

## `maxRowsPerSource` (type: `integer`):

Per-source row cap (paginated). 0 = no limit. The run status/OUTPUT record flags sources that hit the cap.

## `includeRaw` (type: `boolean`):

Adds every original column under 'raw'.

## `customSocrata` (type: `object`):

Any other city's Socrata violations dataset: {"domain":"data.cityofboston.gov","dataset":"xxxx-xxxx","idField":"...","dateField":"...","textField":"...","city":"Boston, MA"}

## `stateKey` (type: `string`):

Use a different key per saved search/schedule so their 'seen' lists don't mix.

## `stateStoreName` (type: `string`):

Named key-value store holding the seen-ID state. Leave empty for the default.

## `firstRunBehaviour` (type: `string`):

What the first diff run (no state yet) returns.

## Actor input object example

```json
{
  "mode": "snapshot",
  "datasets": [
    "nyc-hpd",
    "chicago"
  ],
  "lookbackDays": 7,
  "maxItems": 0,
  "perDatasetLimit": 0,
  "maxRowsPerSource": 5000,
  "includeRaw": false,
  "stateKey": "default",
  "firstRunBehaviour": "emitAll"
}
```

# Actor output Schema

## `results` (type: `string`):

No description

## `resultsView` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "datasets": [
        "nyc-hpd",
        "chicago"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("metal_spinney/us-code-violations").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "datasets": [
        "nyc-hpd",
        "chicago",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("metal_spinney/us-code-violations").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "datasets": [
    "nyc-hpd",
    "chicago"
  ]
}' |
apify call metal_spinney/us-code-violations --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,metal_spinney/us-code-violations"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/MSSU4lhhndUNgAFE1/builds/zn8Hwmldf0wkK7dtj/openapi.json
