# Restaurant Health Inspection Intelligence (`c0rrupt3d/restaurant-health-inspection-intelligence`) Actor

Find failed inspections, repeated violations, closures, and compliance trends from official public records (NYC, Chicago). Returns normalized records plus derived intelligence: risk score, repeat-offender flags, and likely service needs.

- **URL**: https://apify.com/c0rrupt3d/restaurant-health-inspection-intelligence.md
- **Developed by:** [Aiden Mason](https://apify.com/c0rrupt3d) (community)
- **Categories:** Automation, Lead generation, Real estate
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 record scrapeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js/docs.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python/docs.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## Restaurant Health Inspection Intelligence

Find **failed inspections, repeated violations, closures, reinspections, and restaurant compliance trends** from official public records — and turn them into structured, commercially useful intelligence.

This Apify Actor collects restaurant health inspection records from official public open-data sources, normalizes them into one consistent schema, and adds a derived **intelligence layer**: risk scores, repeat-offender flags, declining-performance detection, reinspection opportunities, and likely service needs (pest control, deep cleaning, food-safety consulting, equipment maintenance, training).

> It is positioned as **inspection intelligence**, not just a scraper. Every record includes a source URL and source record ID so you can verify it with the original agency.

---

### Supported jurisdictions (v1)

| Jurisdiction | Source | Platform | Records | Updated |
|---|---|---|---|---|
| **New York City (DOHMH)** | DOHMH Restaurant Inspection Results (`43nn-pn8j`) | Socrata | ~296,000 | Daily |
| **Chicago (CDPH)** | Food Inspections (`4ijn-s7e5`) | Socrata | ~313,000 | Frequent |

Both are official, free, no-login public open-data endpoints accessed via direct HTTP (Socrata SODA API). No proxies, no browser automation, no CAPTCHA, no authentication required.

More Socrata jurisdictions (Seattle/King County, NYS, San Francisco, Dallas, Toronto) share the same connector and are on the expansion roadmap.

---

### What it answers

- Which restaurants failed an inspection this week / month?
- Which restaurants have repeated violations?
- Which restaurants have declining scores?
- Which restaurant chains/locations have the most violations?
- Which businesses received emergency closures?
- Which restaurants were reinspected?
- Which newly inspected restaurants may need compliance services (pest control, cleaning, consulting, maintenance, training)?

---

### Input

See `.actor/input_schema.json` for the full, UI-documented schema. Key fields:

| Field | Type | Description |
|---|---|---|
| `jurisdiction` | enum | `nyc` or `chicago` (required) |
| `restaurantName` | string | Case-insensitive contains match on business name |
| `zipCode` | string | Filter to one ZIP/postal code |
| `dateFrom` / `dateTo` | date (YYYY-MM-DD) | Inspection date range (leave empty for no bound) |
| `inspectionResults` | multi-select | `pass`/`fail`/`conditional`/`closed`/`pending`/`not_scored`/`unknown` |
| `minScore` / `maxScore` | number | Inspection score range (NYC; higher = more violations) |
| `violationCategories` | multi-select | `food_temp`/`food_protection`/`pest_control`/`sanitation`/`plumbing_water`/`equipment`/`hygiene`/`structural`/`signage`/`other` |
| `criticalViolationsOnly` | boolean | Keep only inspections with ≥1 critical violation |
| `closureOnly` | boolean | Keep only closures |
| `reinspectionOpportunityOnly` | boolean | Fail/conditional with no later pass |
| `maxResults` | integer | Cap on returned records (default 1000; 0 = up to 100,000) |
| `sortOrder` | enum | `date_desc`/`date_asc`/`score_desc`/`risk_desc` |
| `includeViolationDetails` | boolean | Populate the nested `violations` array (default true) |
| `includeHistoricalInspections` | boolean | Aggregate per-business history for intelligence (default true) |
| `keyword` | string | Substring match on violation description text (e.g. `rodent`) |
| `socrataAppToken` | string (secret) | Optional free token to raise rate limits; not required |
| `requestDelayMs` | integer | Polite delay between paginated requests (default 150) |

#### Example input

```json
{
  "jurisdiction": "nyc",
  "dateFrom": "2026-06-01",
  "dateTo": "2026-06-30",
  "inspectionResults": ["fail", "conditional"],
  "criticalViolationsOnly": true,
  "maxResults": 1000,
  "sortOrder": "risk_desc"
}
````

***

### Output

Each dataset row is **one inspection** (NYC's per-violation source rows are aggregated into one record per inspection). Records use a stable normalized schema (see `.actor/dataset_schema.json`, which also defines the Apify Output-tab views). Unavailable values are `null`.

#### Core fields

`record_id`, `source_record_id`, `source_url`, `jurisdiction`, `county`, `state`, `restaurant_name`, `legal_business_name`, `facility_type`, `chain_name`, `address`, `city`, `postal_code`, `latitude`, `longitude`, `license_number`, `inspection_id`, `inspection_date` (ISO 8601), `inspection_type`, `inspection_result`, `inspection_score`, `inspection_grade`, `risk_level`, `closure_status`, `closure_date`, `reopen_date`, `reinspection_required`, `reinspection_date`, `total_violations`, `critical_violation_count`, `noncritical_violation_count`, `violations[]`, `inspector_notes`, `source_platform`, `scraped_at`.

#### Violation objects (`violations[]`)

`violation_code`, `violation_description`, `violation_category`, `severity` (`critical`/`major`/`minor`/`informational`/`unknown`), `critical`, `corrected_on_site`, `repeat_violation`.

#### Intelligence fields (derived, documented, configurable)

`lead_category`, `risk_score` (0–100), `repeat_offender`, `recent_failure`, `recent_closure`, `declining_performance`, `reinspection_opportunity`, `likely_service_needs[]`, `inspection_frequency_days`, `days_since_last_inspection`, `days_since_last_failure`, `location_inspection_count`, `chain_inspection_count`, `violation_trend` (`improving`/`stable`/`worsening`/`unknown`), `data_completeness_score`.

> Original source values are preserved in `_src_*` fields (e.g. `_src_inspection_type`, `_src_action`, `_src_cuisine`) so nothing is silently overwritten.

#### Intelligence rules (documented thresholds)

| Field | Rule | Default threshold |
|---|---|---|
| `recent_failure` | Business has a failed inspection within N days of now | 30 days |
| `repeat_offender` | ≥ N failed/conditional inspections within trailing M months | 2 / 12 months |
| `recent_closure` | Business has a closure within N days of now | 90 days |
| `declining_performance` | Latest score worse than average of prior two by ≥ Δ (NYC); or result rank worsens (Chicago) | Δ = 7 |
| `reinspection_opportunity` | Latest inspection fail/conditional with no later pass in the returned set | — |
| `likely_service_needs` | Violation categories in the last 90 days mapped to services | 90 days |
| `risk_score` | Weighted: recent\_failure +25, repeat\_offender +20, recent\_closure +15, declining +10, reinspection +15, critical-density up to +15, score up to +10 (capped 100) | — |
| `lead_category` | Primary service need, or `compliance_monitoring` for closures, else `research`/`none` | — |

**Category → service mapping:** `pest_control`→pest\_control, `sanitation`/`structural`→deep\_cleaning, `plumbing_water`/`equipment`→equipment\_maintenance, `food_temp`/`food_protection`→food\_safety\_consulting, `hygiene`→training, `signage`→compliance\_monitoring.

Thresholds are configurable via input overrides (`recentFailureDays`, `recentClosureDays`, `repeatMonths`) and `DEFAULT_THRESHOLDS` in `src/intelligence/index.js`.

> Derived fields are **estimates** ("likely"/"possible"). They never assert a business is unsafe. Always verify with the original agency.

#### Example output

See `docs/example_output.json` for five full enriched records. Example snippet:

```json
{
  "record_id": "nyc:50188053:2026-07-09:preopening",
  "restaurant_name": "LILEO",
  "city": "BROOKLYN",
  "state": "NY",
  "inspection_date": "2026-07-09",
  "inspection_result": "pending",
  "inspection_grade": "N",
  "inspection_score": 33,
  "critical_violation_count": 2,
  "risk_score": 45,
  "recent_failure": false,
  "likely_service_needs": ["food_safety_consulting"],
  "lead_category": "food_safety_consulting",
  "source_url": "https://data.cityofnewyork.us/Health/DOHMH-New-York-City-Restaurant-Inspection-Results/43nn-pn8j",
  "source_record_id": "camis:50188053",
  "scraped_at": "2026-07-13T17:00:00.000Z"
}
```

***

### Run locally

Requirements: Node.js 18+.

```bash
npm install
## Unit + integration tests (Node test runner)
npm test
## Live validation against the NYC source (writes docs/05-validation-report.md)
node scripts/validate.js
## Run the Actor locally (uses Apify local storage)
APIFY_LOCAL_STORAGE_DIR=./storage node src/main.js   # provide input via storage/default_value.json
```

Example local input (`storage/key_value_stores/default/INPUT.json`):

```json
{ "jurisdiction": "nyc", "dateFrom": "2026-06-01", "dateTo": "2026-06-30", "maxResults": 500 }
```

### Deploy

```bash
apify login
apify create   # or push this folder
apify push
```

The Dockerfile builds on `apify/actor-node:20`. Dependencies are production-only in the image.

***

### Example API call

```bash
curl -X POST "https://api.apify.com/v2/acts/<your-username>/restaurant-health-inspection-intelligence/runs?token=$APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"jurisdiction":"nyc","inspectionResults":["fail"],"criticalViolationsOnly":true,"dateFrom":"2026-06-01","maxResults":1000}'
```

***

### Architecture

```
src/
  main.js                 # Actor entry: input validation, orchestration, dataset push, OUTPUT summary
  sources/
    socrata.js            # Reusable Socrata SODA client (pagination, retries, rate limiting)
    nyc.js                # NYC config + per-violation -> per-inspection aggregation + normalization
    chicago.js            # Chicago config + violation-blob parser + normalization
    index.js              # Source registry + collect()
  normalization/
    dates.js              # ISO 8601 date normalization
    results.js            # Result/severity/inspection-type controlled vocabularies
    violations.js         # Violation parsing + service-category classification
    addresses.js          # Address/postal/dedup-key helpers
  intelligence/
    index.js              # Risk scoring, repeat offenders, trends, likely service needs
  utils/
    filters.js            # Post-aggregation filtering + sorting + maxResults
    monitoring.js         # Source-change / data-quality warnings
.actor/                   # Apify Actor definition (publish config)
  actor.json              # Name, version, memory limits, input/output/dataset schema wiring
  input_schema.json       # UI-documented input schema
  dataset_schema.json     # Dataset item JSON Schema + Output-tab views (overview/leads/compliance)
  output_schema.json      # OUTPUT run-summary schema
docs/                     # Research + validation deliverables
tests/                    # 122 automated tests (Node test runner)
scripts/validate.js       # Live 100-record validation + 1000-record smoke test
```

Source-specific extraction is kept separate from shared normalization and intelligence logic, so new Socrata jurisdictions plug in via a config + normalizer without touching the core.

***

### Required Actor features

Input schema ✓ · Dataset output ✓ · Pagination ✓ · Request retries ✓ · Rate limiting ✓ · Duplicate detection (record\_id) ✓ · Date filtering ✓ · Result filtering ✓ · Score filtering ✓ · Restaurant-name filtering ✓ · Violation parsing ✓ · Severity classification ✓ · Max-result limits ✓ · Clear logs ✓ · Run statistics (OUTPUT) ✓ · Graceful missing-field handling ✓ · Source-link preservation ✓ · Error reporting (circuit breaker + warnings) ✓ · Data-quality rules ✓.

### Monitoring & source-change detection

The Actor logs warnings (and records them in the `OUTPUT` summary) for: sudden zero-result runs, raw-rows-but-no-normalized (schema drift), missing required fields (>5%), unmapped `inspection_result` values, and pagination accounting mismatches.

### Validation

A live validation run against NYC DOHMH (see `docs/05-validation-report.md`) validated 100 inspections field-by-field: **100% match** on restaurant name, address, inspection date, result, score, grade, violation text, closure status, source URL, and record ID. A 1000-record smoke test passed (1,446 inspections processed without crashing).

***

### Legal & ethical use

- Uses **only public records** from official open-data portals. No authentication, CAPTCHA, paywall, or access-control circumvention.
- Does **not** collect or republish inspector personal information or unnecessary personal data.
- Preserves inspection dates and result context; old inspections are not presented as current conditions.
- Distinguishes open / closed / reopened and corrected vs. historical violations.
- Derived scores are estimates and **never** label a business as dangerous. Users must verify with the original agency (NYC DOHMH / CDPH via the preserved `source_url`).
- Data is attributed to the issuing agency; every record carries `source_url` and `source_record_id`.

See `docs/03-source-recommendation.md` for the full access & compliance assessment.

***

### Known limitations (v1)

- v1 fully supports NYC; Chicago is supported as an expansion target (no numeric score, so Chicago risk uses result-rank decline and the violation-text blob is parsed heuristically).
- `chain_name` is intentionally `null` — chain ownership is not inferred from name similarity without a documented rule.
- The dataset reflects each source's rolling window (NYC ~3 years of active establishments).
- Socrata unauthenticated requests are rate-limited; provide a free `socrataAppToken` for high-volume runs.

### Changelog

- **1.0.0** — Initial release. NYC + Chicago Socrata adapters, normalized schema, intelligence layer, 122 tests, live 100-record validation (100% match).

# Actor input Schema

## `jurisdiction` (type: `string`):

Public open-data source to query. v1 fully supports 'nyc' (DOHMH Restaurant Inspection Results, updated daily). 'chicago' is supported as an expansion target.

## `restaurantName` (type: `string`):

Case-insensitive substring match on the business name (DBA). Leave empty to match all.

## `zipCode` (type: `string`):

Filter to a single ZIP/postal code. Leave empty to match all.

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

Include inspections on or after this date (YYYY-MM-DD). Leave empty for no lower bound.

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

Include inspections on or before this date (YYYY-MM-DD). Leave empty for no upper bound.

## `inspectionResults` (type: `array`):

Normalized result categories to keep. Leave empty to include all. Controlled vocabulary: pass, fail, conditional, closed, pending, not\_scored, unknown.

## `minScore` (type: `number`):

Keep inspections with score >= this value (NYC: higher score = more violations). Leave empty for no minimum.

## `maxScore` (type: `number`):

Keep inspections with score <= this value. Leave empty (0) for no maximum.

## `violationCategories` (type: `array`):

Keep inspections containing at least one violation in these categories. Leave empty to include all. Categories: food\_temp, food\_protection, pest\_control, sanitation, plumbing\_water, equipment, hygiene, structural, signage, other.

## `criticalViolationsOnly` (type: `boolean`):

Keep only inspections that contain at least one critical violation.

## `closureOnly` (type: `boolean`):

Keep only inspections where the establishment was closed (DOHMH action).

## `reinspectionOpportunityOnly` (type: `boolean`):

Keep only inspections that represent a reinspection opportunity (failed/conditional with no later passing inspection in the returned set).

## `maxResults` (type: `integer`):

Cap on the number of inspection records (post-aggregation, one row per inspection) returned to the dataset. 0 = unlimited (capped at 100,000 for safety).

## `sortOrder` (type: `string`):

Order of output records.

## `includeViolationDetails` (type: `boolean`):

Populate the nested 'violations' array with per-violation code/description/category/severity. Disable for a lighter output.

## `includeHistoricalInspections` (type: `boolean`):

Enrich each business with its inspection history within the returned set to compute repeat\_offender, declining\_performance, and inspection counts. Recommended.

## `keyword` (type: `string`):

Case-insensitive substring match on violation description text (e.g. 'rodent', 'cockroach', 'grease'). Leave empty to skip.

## `socrataAppToken` (type: `string`):

Optional free Socrata app token to raise rate limits. The Actor runs without it. Register at https://dev.socrata.com/ if needed.

## `requestDelayMs` (type: `integer`):

Polite delay between paginated Socrata requests.

## `maxConsecutiveErrors` (type: `integer`):

Abort after this many consecutive failed page requests.

## Actor input object example

```json
{
  "jurisdiction": "nyc",
  "restaurantName": "",
  "zipCode": "",
  "dateFrom": "",
  "dateTo": "",
  "inspectionResults": [],
  "minScore": 0,
  "maxScore": 0,
  "violationCategories": [],
  "criticalViolationsOnly": false,
  "closureOnly": false,
  "reinspectionOpportunityOnly": false,
  "maxResults": 1000,
  "sortOrder": "date_desc",
  "includeViolationDetails": true,
  "includeHistoricalInspections": true,
  "keyword": "",
  "requestDelayMs": 150,
  "maxConsecutiveErrors": 5
}
```

# Actor output Schema

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

Normalized inspection records (one per inspection) with derived intelligence fields: risk\_score, repeat\_offender, likely\_service\_needs, etc. Use dataset views (overview, leads, compliance) to explore the data.

## `summary` (type: `string`):

Run summary with jurisdiction, counts, data-quality warnings, and aggregate tallies for lead categories and service needs.

# 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 = {
    "jurisdiction": "nyc",
    "restaurantName": "",
    "zipCode": "",
    "dateFrom": "",
    "dateTo": "",
    "inspectionResults": [],
    "minScore": 0,
    "maxScore": 0,
    "violationCategories": [],
    "criticalViolationsOnly": false,
    "closureOnly": false,
    "reinspectionOpportunityOnly": false,
    "maxResults": 1000,
    "sortOrder": "date_desc",
    "includeViolationDetails": true,
    "includeHistoricalInspections": true,
    "keyword": "",
    "requestDelayMs": 150,
    "maxConsecutiveErrors": 5
};

// Run the Actor and wait for it to finish
const run = await client.actor("c0rrupt3d/restaurant-health-inspection-intelligence").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 = {
    "jurisdiction": "nyc",
    "restaurantName": "",
    "zipCode": "",
    "dateFrom": "",
    "dateTo": "",
    "inspectionResults": [],
    "minScore": 0,
    "maxScore": 0,
    "violationCategories": [],
    "criticalViolationsOnly": False,
    "closureOnly": False,
    "reinspectionOpportunityOnly": False,
    "maxResults": 1000,
    "sortOrder": "date_desc",
    "includeViolationDetails": True,
    "includeHistoricalInspections": True,
    "keyword": "",
    "requestDelayMs": 150,
    "maxConsecutiveErrors": 5,
}

# Run the Actor and wait for it to finish
run = client.actor("c0rrupt3d/restaurant-health-inspection-intelligence").call(run_input=run_input)

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

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

```

## CLI example

```bash
echo '{
  "jurisdiction": "nyc",
  "restaurantName": "",
  "zipCode": "",
  "dateFrom": "",
  "dateTo": "",
  "inspectionResults": [],
  "minScore": 0,
  "maxScore": 0,
  "violationCategories": [],
  "criticalViolationsOnly": false,
  "closureOnly": false,
  "reinspectionOpportunityOnly": false,
  "maxResults": 1000,
  "sortOrder": "date_desc",
  "includeViolationDetails": true,
  "includeHistoricalInspections": true,
  "keyword": "",
  "requestDelayMs": 150,
  "maxConsecutiveErrors": 5
}' |
apify call c0rrupt3d/restaurant-health-inspection-intelligence --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=c0rrupt3d/restaurant-health-inspection-intelligence",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Restaurant Health Inspection Intelligence",
        "description": "Find failed inspections, repeated violations, closures, and compliance trends from official public records (NYC, Chicago). Returns normalized records plus derived intelligence: risk score, repeat-offender flags, and likely service needs.",
        "version": "1.0",
        "x-build-id": "xcWZZabN6n7qwwes0"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/c0rrupt3d~restaurant-health-inspection-intelligence/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-c0rrupt3d-restaurant-health-inspection-intelligence",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/c0rrupt3d~restaurant-health-inspection-intelligence/runs": {
            "post": {
                "operationId": "runs-sync-c0rrupt3d-restaurant-health-inspection-intelligence",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/c0rrupt3d~restaurant-health-inspection-intelligence/run-sync": {
            "post": {
                "operationId": "run-sync-c0rrupt3d-restaurant-health-inspection-intelligence",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "jurisdiction"
                ],
                "properties": {
                    "jurisdiction": {
                        "title": "Jurisdiction",
                        "enum": [
                            "nyc",
                            "chicago"
                        ],
                        "type": "string",
                        "description": "Public open-data source to query. v1 fully supports 'nyc' (DOHMH Restaurant Inspection Results, updated daily). 'chicago' is supported as an expansion target.",
                        "default": "nyc"
                    },
                    "restaurantName": {
                        "title": "Restaurant name (contains)",
                        "type": "string",
                        "description": "Case-insensitive substring match on the business name (DBA). Leave empty to match all.",
                        "default": ""
                    },
                    "zipCode": {
                        "title": "ZIP code",
                        "type": "string",
                        "description": "Filter to a single ZIP/postal code. Leave empty to match all.",
                        "default": ""
                    },
                    "dateFrom": {
                        "title": "Inspection date from",
                        "type": "string",
                        "description": "Include inspections on or after this date (YYYY-MM-DD). Leave empty for no lower bound.",
                        "default": ""
                    },
                    "dateTo": {
                        "title": "Inspection date to",
                        "type": "string",
                        "description": "Include inspections on or before this date (YYYY-MM-DD). Leave empty for no upper bound.",
                        "default": ""
                    },
                    "inspectionResults": {
                        "title": "Inspection results",
                        "type": "array",
                        "description": "Normalized result categories to keep. Leave empty to include all. Controlled vocabulary: pass, fail, conditional, closed, pending, not_scored, unknown.",
                        "items": {
                            "type": "string",
                            "enum": [
                                "pass",
                                "fail",
                                "conditional",
                                "closed",
                                "pending",
                                "not_scored",
                                "unknown"
                            ],
                            "enumTitles": [
                                "Pass",
                                "Fail",
                                "Conditional",
                                "Closed",
                                "Pending",
                                "Not scored",
                                "Unknown"
                            ]
                        },
                        "default": []
                    },
                    "minScore": {
                        "title": "Minimum inspection score",
                        "type": "number",
                        "description": "Keep inspections with score >= this value (NYC: higher score = more violations). Leave empty for no minimum.",
                        "default": 0
                    },
                    "maxScore": {
                        "title": "Maximum inspection score",
                        "type": "number",
                        "description": "Keep inspections with score <= this value. Leave empty (0) for no maximum.",
                        "default": 0
                    },
                    "violationCategories": {
                        "title": "Violation categories",
                        "type": "array",
                        "description": "Keep inspections containing at least one violation in these categories. Leave empty to include all. Categories: food_temp, food_protection, pest_control, sanitation, plumbing_water, equipment, hygiene, structural, signage, other.",
                        "items": {
                            "type": "string",
                            "enum": [
                                "food_temp",
                                "food_protection",
                                "pest_control",
                                "sanitation",
                                "plumbing_water",
                                "equipment",
                                "hygiene",
                                "structural",
                                "signage",
                                "other"
                            ],
                            "enumTitles": [
                                "Food temperature",
                                "Food protection/handling",
                                "Pest control",
                                "Sanitation/cleaning",
                                "Plumbing/water",
                                "Equipment",
                                "Employee hygiene",
                                "Structural/facility",
                                "Signage/permit",
                                "Other"
                            ]
                        },
                        "default": []
                    },
                    "criticalViolationsOnly": {
                        "title": "Critical violations only",
                        "type": "boolean",
                        "description": "Keep only inspections that contain at least one critical violation.",
                        "default": false
                    },
                    "closureOnly": {
                        "title": "Closures only",
                        "type": "boolean",
                        "description": "Keep only inspections where the establishment was closed (DOHMH action).",
                        "default": false
                    },
                    "reinspectionOpportunityOnly": {
                        "title": "Reinspection opportunities only",
                        "type": "boolean",
                        "description": "Keep only inspections that represent a reinspection opportunity (failed/conditional with no later passing inspection in the returned set).",
                        "default": false
                    },
                    "maxResults": {
                        "title": "Maximum number of results",
                        "type": "integer",
                        "description": "Cap on the number of inspection records (post-aggregation, one row per inspection) returned to the dataset. 0 = unlimited (capped at 100,000 for safety).",
                        "default": 1000
                    },
                    "sortOrder": {
                        "title": "Sort order",
                        "enum": [
                            "date_desc",
                            "date_asc",
                            "score_desc",
                            "risk_desc"
                        ],
                        "type": "string",
                        "description": "Order of output records.",
                        "default": "date_desc"
                    },
                    "includeViolationDetails": {
                        "title": "Include violation details",
                        "type": "boolean",
                        "description": "Populate the nested 'violations' array with per-violation code/description/category/severity. Disable for a lighter output.",
                        "default": true
                    },
                    "includeHistoricalInspections": {
                        "title": "Aggregate historical inspections per business",
                        "type": "boolean",
                        "description": "Enrich each business with its inspection history within the returned set to compute repeat_offender, declining_performance, and inspection counts. Recommended.",
                        "default": true
                    },
                    "keyword": {
                        "title": "Keyword (violation text contains)",
                        "type": "string",
                        "description": "Case-insensitive substring match on violation description text (e.g. 'rodent', 'cockroach', 'grease'). Leave empty to skip.",
                        "default": ""
                    },
                    "socrataAppToken": {
                        "title": "Socrata app token (optional)",
                        "type": "string",
                        "description": "Optional free Socrata app token to raise rate limits. The Actor runs without it. Register at https://dev.socrata.com/ if needed."
                    },
                    "requestDelayMs": {
                        "title": "Request delay (ms)",
                        "type": "integer",
                        "description": "Polite delay between paginated Socrata requests.",
                        "default": 150
                    },
                    "maxConsecutiveErrors": {
                        "title": "Max consecutive request errors",
                        "type": "integer",
                        "description": "Abort after this many consecutive failed page requests.",
                        "default": 5
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
