# Medicare & Medicaid Drug Spending Scraper (`compute-edge/medicare-drug-spending-scraper`) Actor

Extract CMS Medicare Part D, Part B, and Medicaid drug spending data. Filter by brand name, generic name, or manufacturer. Includes multi-year spending trends for policy research, pharma analysis, and healthcare intelligence.

- **URL**: https://apify.com/compute-edge/medicare-drug-spending-scraper.md
- **Developed by:** [Compute Edge](https://apify.com/compute-edge) (community)
- **Categories:** Lead generation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.00 / 1,000 results

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.md):

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

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.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/platform/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

## Medicare & Medicaid Drug Spending Scraper — Part B & Part D

Extract structured drug spending data from the **Centers for Medicare & Medicaid Services (CMS)** public API — no authentication, no sign-up, no rate limits. This Actor covers three major federal drug spending programs:

- **Medicare Part D** — Retail prescription drug spending (the largest program by volume)
- **Medicare Part B** — Physician-administered drugs (infusions, injectables, oncology)
- **Medicaid** — State/federal prescription drug spending for low-income beneficiaries

Each record includes multi-year spending trends (2020–2024), claims volume, beneficiary counts, and average cost per claim — the exact data used in **pharma pricing research, health policy analysis, and drug cost intelligence** reports.

### Features

- Scrape all three CMS drug spending programs from a single Actor
- Filter by **brand name**, **generic name**, or **manufacturer** (case-insensitive partial match)
- Automatically detects the latest available data year from column names
- Outputs both **normalized summary fields** (easy to query) and **all raw year columns** (no data lost)
- Pagination handled automatically — extract up to 50,000 records per run
- Empty input `{}` returns 500 Part D records immediately — no configuration required

#### Output Fields

| Field | Description |
|-------|-------------|
| `program` | Program type: `partD`, `partB`, or `medicaid` |
| `brandName` | Drug brand name (e.g. `Humira`, `Eliquis`) |
| `genericName` | Generic/chemical name (e.g. `adalimumab`, `apixaban`) |
| `manufacturer` | Manufacturer name (Part D & Medicaid only) |
| `totalManufacturers` | Number of manufacturers for this drug |
| `latestYear` | Latest year of data detected (e.g. `2024`) |
| `totalSpending` | Total Medicare/Medicaid spending in latest year (USD) |
| `totalClaims` | Total number of claims in latest year |
| `totalDosageUnits` | Total dosage units dispensed |
| `totalBeneficiaries` | Total beneficiaries covered (Part D & Part B only) |
| `avgSpendPerClaim` | Average spending per claim in latest year (USD) |
| `avgSpendPerBeneficiary` | Average spending per beneficiary (Part D & Part B only) |
| `Tot_Spndng_2020` … `Tot_Spndng_2024` | Raw annual total spending columns |
| `Tot_Clms_2020` … `Tot_Clms_2024` | Raw annual claims count columns |
| `CAGR_Avg_Spnd_Per_Dsg_Unt_20_24` | Compound annual growth rate (2020–2024) |

---

### How to scrape Medicare drug spending data

Follow these steps to extract CMS drug spending data in minutes:

1. **Open the Actor** in Apify Store and click **Try for free**.
2. **Choose a program** from the dropdown: Part D (retail prescriptions), Part B (physician-administered), or Medicaid.
3. **Optionally add filters**: enter a brand name (e.g. `Keytruda`), generic name (e.g. `pembrolizumab`), or manufacturer (e.g. `Merck`). All filters are case-insensitive partial matches — leave blank to retrieve all drugs.
4. **Set Max Results**: default is 500 records. Set up to 50,000 for a full dataset export.
5. **Click Start** and wait for the run to complete (typically under 30 seconds for 500 records).
6. **Download results** as JSON, CSV, or Excel from the Dataset tab.

#### Example: Find all Pfizer drugs in Part D with spending data

Set `program` to `partD`, `manufacturer` to `Pfizer`, and `maxResults` to `5000`. The Actor will return every Pfizer drug entry across all available years in a single structured dataset.

---

### Pricing

This Actor uses **per-result pricing**: you are charged **$0.003 per record** extracted, plus standard Apify compute time.

| Scenario | Records | Estimated Cost |
|----------|---------|----------------|
| Quick drug lookup | 500 | ~$0.002 |
| Full Part D dataset | 50,000 | ~$0.15 |
| All three programs (150K) | 150,000 | ~$0.45 |

Apify compute charges are typically under $0.01 per run for this Actor (it uses no browser, only HTTP requests).

---

### Input Example

```json
{
    "program": "partD",
    "brandName": "Humira",
    "genericName": "",
    "manufacturer": "",
    "maxResults": 100
}
````

### Output Example

```json
{
    "program": "partD",
    "brandName": "Humira",
    "genericName": "Adalimumab",
    "manufacturer": "Overall",
    "totalManufacturers": 3,
    "latestYear": 2024,
    "totalSpending": 1234567890.12,
    "totalClaims": 2345678,
    "totalDosageUnits": 5678901,
    "totalBeneficiaries": 345678,
    "avgSpendPerClaim": 526.14,
    "avgSpendPerBeneficiary": 3574.22,
    "Tot_Spndng_2020": 5678901234.56,
    "Tot_Spndng_2021": 5234567890.12,
    "Tot_Spndng_2022": 4567890123.45,
    "Tot_Spndng_2023": 2345678901.23,
    "Tot_Spndng_2024": 1234567890.12,
    "CAGR_Avg_Spnd_Per_Dsg_Unt_20_24": "-0.3012"
}
```

***

### Other Scrapers

Need more healthcare and government data? Check out our related Actors:

- [Medicare Provider Scraper](https://apify.com/compute-edge/medicare-provider-scraper) — Extract Medicare-enrolled providers, their specialties, and billing addresses
- [DailyMed Drug Labels Scraper](https://apify.com/compute-edge/dailymed-drug-labels-scraper) — Full FDA drug label data including dosage, warnings, and indications
- [FDA Drug Approvals Scraper](https://apify.com/compute-edge/fda-drug-approvals-scraper) — Track new drug approvals, supplemental NDAs, and biosimilar designations
- [HHS OIG Exclusions Scraper](https://apify.com/compute-edge/hhs-oig-exclusions-scraper) — List of healthcare providers excluded from federal programs

***

### FAQ

**Q: How current is the data?**
CMS updates these datasets annually. The Actor automatically detects the latest year available in each dataset (currently 2024 for most programs). The data typically lags about 18–24 months behind the current calendar year.

**Q: What is the difference between Part B and Part D?**
Part D covers retail prescriptions that patients fill at a pharmacy. Part B covers drugs administered by a physician or clinic (infusions, injectables, chemotherapy). Many high-cost biologics appear in Part B, not Part D.

**Q: Why does the manufacturer filter not work for Part B?**
Medicare Part B data is structured around HCPCS procedure codes, not manufacturers. The manufacturer field is not present in Part B records. Use brand name or generic name filters instead.

**Q: Can I get all records without any filters?**
Yes. Leave all filter fields blank and set `maxResults` to the number of records you need (up to 50,000 per run). Run the Actor three times (once per program) to collect the complete CMS drug spending universe.

**Q: What does "Overall" mean in the Manufacturer field?**
When `Mftr_Name` is `"Overall"`, the record represents aggregated spending across all manufacturers of that drug. Manufacturer-specific rows appear separately in the same dataset.

***

### Legal Disclaimer

This Actor retrieves publicly available data from the CMS data API (`data.cms.gov`) which publishes federal drug spending statistics under an open data policy. All data is aggregate spending information — no personal health information (PHI), no individually identifiable data. Use of this Actor does not involve accessing any protected, login-restricted, or copyrighted data. Users are responsible for ensuring their use of the extracted data complies with applicable laws and CMS data use terms. For questions, contact [support via Apify](https://apify.com/contact).

# Actor input Schema

## `program` (type: `string`):

Which CMS drug spending program to extract data from. 'partD' = Medicare Part D (retail prescriptions), 'partB' = Medicare Part B (physician-administered drugs), 'medicaid' = Medicaid drug spending.

## `brandName` (type: `string`):

Filter results to drugs whose brand name contains this text (case-insensitive). Example: 'Humira', 'Eliquis', 'Keytruda'. Leave blank for all drugs.

## `genericName` (type: `string`):

Filter results to drugs whose generic name contains this text (case-insensitive). Example: 'adalimumab', 'apixaban'. Leave blank for all drugs.

## `manufacturer` (type: `string`):

Filter results to drugs from a specific manufacturer (case-insensitive partial match). Not applicable to Part B data. Example: 'Pfizer', 'AbbVie'. Leave blank for all manufacturers.

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

Maximum number of records to return across all pages. Increase for full dataset exports (up to 50,000).

## Actor input object example

```json
{
  "program": "partD",
  "brandName": "",
  "genericName": "",
  "manufacturer": "",
  "maxResults": 500
}
```

# Actor output Schema

## `dataset` (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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("compute-edge/medicare-drug-spending-scraper").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("compute-edge/medicare-drug-spending-scraper").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 '{}' |
apify call compute-edge/medicare-drug-spending-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=compute-edge/medicare-drug-spending-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Medicare & Medicaid Drug Spending Scraper",
        "description": "Extract CMS Medicare Part D, Part B, and Medicaid drug spending data. Filter by brand name, generic name, or manufacturer. Includes multi-year spending trends for policy research, pharma analysis, and healthcare intelligence.",
        "version": "0.1",
        "x-build-id": "ejixY2RxcLoHChTey"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/compute-edge~medicare-drug-spending-scraper/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-compute-edge-medicare-drug-spending-scraper",
                "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/compute-edge~medicare-drug-spending-scraper/runs": {
            "post": {
                "operationId": "runs-sync-compute-edge-medicare-drug-spending-scraper",
                "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/compute-edge~medicare-drug-spending-scraper/run-sync": {
            "post": {
                "operationId": "run-sync-compute-edge-medicare-drug-spending-scraper",
                "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",
                "properties": {
                    "program": {
                        "title": "Program",
                        "enum": [
                            "partD",
                            "partB",
                            "medicaid"
                        ],
                        "type": "string",
                        "description": "Which CMS drug spending program to extract data from. 'partD' = Medicare Part D (retail prescriptions), 'partB' = Medicare Part B (physician-administered drugs), 'medicaid' = Medicaid drug spending.",
                        "default": "partD"
                    },
                    "brandName": {
                        "title": "Brand Name Filter",
                        "type": "string",
                        "description": "Filter results to drugs whose brand name contains this text (case-insensitive). Example: 'Humira', 'Eliquis', 'Keytruda'. Leave blank for all drugs.",
                        "default": ""
                    },
                    "genericName": {
                        "title": "Generic Name Filter",
                        "type": "string",
                        "description": "Filter results to drugs whose generic name contains this text (case-insensitive). Example: 'adalimumab', 'apixaban'. Leave blank for all drugs.",
                        "default": ""
                    },
                    "manufacturer": {
                        "title": "Manufacturer Filter",
                        "type": "string",
                        "description": "Filter results to drugs from a specific manufacturer (case-insensitive partial match). Not applicable to Part B data. Example: 'Pfizer', 'AbbVie'. Leave blank for all manufacturers.",
                        "default": ""
                    },
                    "maxResults": {
                        "title": "Max Results",
                        "minimum": 1,
                        "maximum": 50000,
                        "type": "integer",
                        "description": "Maximum number of records to return across all pages. Increase for full dataset exports (up to 50,000).",
                        "default": 500
                    }
                }
            },
            "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
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
