# Spain Social Security Affiliation by Municipality Scraper (`steadfetch/seg-social-afiliacion-municipal-extractor`) Actor

Monthly count of workers affiliated to the Spanish Social Security in each Spanish municipality, total and by regime, from the official Seguridad Social file. One row per municipality, month and indicator. Public data, no login.

- **URL**: https://apify.com/steadfetch/seg-social-afiliacion-municipal-extractor.md
- **Developed by:** [Steadfetch](https://apify.com/steadfetch) (community)
- **Categories:** Travel, Business
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 affiliation row delivereds

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/actors/running/actors-in-store.md#pay-per-event

## 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

## Spain Social Security Affiliation by Municipality Scraper

Returns the number of workers affiliated to the Spanish Social Security in each
municipality, total and by regime, as JSON, from the official monthly file
"Afiliados por municipio" published by the Seguridad Social.

- **Source:** [Seguridad Social, Afiliados por municipio](https://www.seg-social.es/wps/portal/wss/internet/EstadisticasPresupuestosEstudios/Estadisticas/EST8/EST10/EST305/c43ad8ea-fe79-4329-ac8e-e5758f3c4d7a/6609c55f-65e4-4e64-b1ab-8917fce27a84) (public, no login, no CAPTCHA).
- **One row per municipality, month and indicator** (7 indicators, so one municipality gives 7 rows).
- **Coverage:** every Spanish municipality in the file (8,126 in September 2026), including the 88 municipalities of the Canary Islands.
- **No personal data:** only aggregated counts of workers.

### What it does

A run does three things:

1. Reads the Seguridad Social index page and picks the requested month, or the latest one published.
2. Downloads that month's Excel file (the download needs a `Referer` header pointing at the index, which the Actor sends; it uses no browser and no proxy).
3. Emits one validated row per municipality and indicator. Figures the source hides for statistical secrecy are not turned into zero: the row has `value: null` and `valueNote` holds the literal text of the source, for example `<5`.

Province totals and the "not distributed" rows of the file are not municipalities and are left out.

### Minimum input

```json
{ "municipalityCodes": ["03047"] }
```

That returns the latest month for Calp (INE code 03047). With `{}` the Actor returns every municipality in Spain for the latest month (about 57,000 rows).

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `municipalityCodes` | array of strings | no | Five-digit INE codes with the leading zero, e.g. `"03047"`. Empty or missing means every municipality. A badly written code (`"3047"`, `3047`, `"03047 "`) fails the run before anything is downloaded. A well-formed code that is not in the file gives no rows and a warning in the log. |
| `period` | string | no | Month as `YYYY-MM`. Missing means the latest published month. A month that is not published makes the run fail and says which is the latest available; it is never replaced by another month. |

### Example output

```json
{
  "municipalityCode": "03047",
  "municipalityName": "CALPE/CALP",
  "period": "2026-09",
  "indicator": "affiliates_total",
  "value": 9620,
  "valueNote": null,
  "unit": "persons",
  "breakdown": null,
  "source": "Seguridad Social - Afiliados por municipio",
  "url": "https://www.seg-social.es/wps/portal/wss/internet/EstadisticasPresupuestosEstudios/Estadisticas/EST8/EST10/EST305/c43ad8ea-fe79-4329-ac8e-e5758f3c4d7a/6609c55f-65e4-4e64-b1ab-8917fce27a84",
  "title": "CALPE/CALP (03047) - affiliates_total - 2026-09",
  "scrapedAt": "2026-11-16T12:00:00.000Z"
}
```

A hidden figure looks like this:

```json
{
  "municipalityCode": "01001",
  "municipalityName": "ALEGRIA-DULANTZI",
  "period": "2026-09",
  "indicator": "affiliates_agrario",
  "value": null,
  "valueNote": "<5",
  "unit": "persons"
}
```

### Output fields

- `municipalityCode`: INE code, five digits.
- `municipalityName`: name exactly as written in the source file (it can be truncated, e.g. `CALPE/CALP`).
- `period`: month, `YYYY-MM`.
- `indicator`: one of `affiliates_total`, `affiliates_general`, `affiliates_agrario`, `affiliates_hogar`, `affiliates_mar`, `affiliates_autonomos`, `affiliates_carbon`.
- `value`: number of affiliated workers, or `null` when the source hides it.
- `valueNote`: literal text of the source when `value` is `null` (`<5`, or `>=768` for a total that includes a hidden component), otherwise `null`.
- `unit`: always `persons`.
- `breakdown`: always `null` (the regime is already the indicator).
- `source`, `url`, `title`, `scrapedAt`: common Steadfetch envelope; `url` is the public Seguridad Social index page that lists the monthly file.

| Indicator | Source column |
| --- | --- |
| `affiliates_total` | TOTAL |
| `affiliates_general` | Reg. General |
| `affiliates_agrario` | R. G. - S.E. Agrario |
| `affiliates_hogar` | R. G. - S.E. Hogar |
| `affiliates_mar` | R. E. MAR |
| `affiliates_autonomos` | R. E. T. Autonomos |
| `affiliates_carbon` | R. E. M. Carbon |

### Pricing

Pay per event:

| Event | When it fires | Price |
| ----- | ------------- | ----- |
| `apify-actor-start` | once per run (synthetic, automatic) | 0.00005 USD |
| `apify-default-dataset-item` | one validated row saved to the dataset (synthetic, automatic) | 0.001 USD per row = **1.00 USD per 1,000 rows** |

Works on the Apify free plan: about 4,999 rows for the $5 monthly credit (700 municipalities at 7 rows each).

Only validated rows are pushed. There is no custom per-item event, so a row is never billed twice. A single-municipality run costs about 0.007 USD.

#### Cost per 1,000 results (measured locally, 16 November 2026)

| Measurement | Value |
| ----------- | ----- |
| Calp run (`apify run`, real source) | 7 rows, 19 s wall clock including tool start-up, the 2 s courtesy pause and 2 requests |
| Whole file (September 2026 workbook, 521,876 bytes) | 56,882 rows validated in 0.4 s, 170 MB process RSS, 63 MB JS heap |
| Run memory | 512 MB minimum, 1,024 MB maximum |

At 512 MB and about 10 s of platform time, a run costs roughly 0.0014 GB-hours, well below 0.01 USD per 1,000 rows. The platform figure has not been billed yet: no platform run has been spent on this Actor.

### Development

```bash
npm install --include=dev
npm test                     # lint + typecheck + tests (no network, no credit)
npm run publish:check
npm run build && npm run verify:build
```

Tests run on the real September 2026 workbook and index page saved in `test/fixtures/`.

### Data notes

- The source is a monthly file; the Actor never mixes months. The `period` is the month of the file.
- Revised files (for example `Muni0226R`, February 2026 revised) are read like any month and replace the plain file of the same month when both are listed.
- Values are copied as published. Hidden figures keep their literal text in `valueNote`.
- Source: Seguridad Social, Afiliados por municipio. The month of each row is in `period`.

### FAQ

**Why is `value` null?** The Seguridad Social hides small counts (`<5`) and the totals that include them (`>=768`). The Actor keeps the text instead of inventing a number, and never writes zero in its place.

**Why is there a 403 or a failure?** The download refuses requests without a `Referer`; the Actor sends it. If the source still blocks the run, it aborts with a clear error and delivers nothing: no CAPTCHA solving, no proxy evasion.

**Can I get several months?** Run once per `period`. The index lists the months from January 2024.

**Does it need a proxy or a browser?** No. Plain HTTP requests and a local XLSX reader.

### Maintenance

This Actor is **tested daily**: automated runs keep the source reachable and the output schema valid, and failures open an issue in this repository. Schema changes are announced through repository releases.

### Legal and attribution

Only public, aggregated data published by the Seguridad Social is read. Its legal notice allows reuse, including commercial reuse, if the content is not distorted and the source is cited. Source: Seguridad Social, "Afiliados por municipio". The Actor honours `robots.txt`, sends an honest User-Agent with contact information and makes two requests per run (the index and one file, with a pause between them). See `docs/legal-gate.md`. Steadfetch is not affiliated with the Seguridad Social.

# Actor input Schema

## `municipalityCodes` (type: `array`):

Five-digit INE municipality codes, with the leading zero (for example "03047" for Calp, "35001" for Agaete). Leave empty to get every municipality in Spain.

## `period` (type: `string`):

Reference month in YYYY-MM format (for example "2026-09"). Leave empty for the latest month published. A month that is not published yet makes the run fail and tells you the latest one available.

## Actor input object example

```json
{
  "municipalityCodes": [
    "03047",
    "38038"
  ],
  "period": "2026-09"
}
```

# Actor output Schema

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

Dataset items validated against the item schema in dataset_schema.json (fields).

# 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 = {
    "municipalityCodes": [
        "03047"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("steadfetch/seg-social-afiliacion-municipal-extractor").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 = { "municipalityCodes": ["03047"] }

# Run the Actor and wait for it to finish
run = client.actor("steadfetch/seg-social-afiliacion-municipal-extractor").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 '{
  "municipalityCodes": [
    "03047"
  ]
}' |
apify call steadfetch/seg-social-afiliacion-municipal-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,steadfetch/seg-social-afiliacion-municipal-extractor"
        }
    }
}
```

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/8CfG6HdvmWOW1g0W0/builds/YfR5U4aIffSPYgkhE/openapi.json
