# Korean Statistics Analyzer (`hassy/korean-statistics-analyzer`) Actor

Extract and analyze comprehensive statistical data from Korea's KOSIS (Korean Statistical Information Service) portal. This Actor provides easy access to Korean government statistics with powerful search capabilities and structured data output.

- **URL**: https://apify.com/hassy/korean-statistics-analyzer.md
- **Developed by:** [Hassy](https://apify.com/hassy) (community)
- **Categories:** Developer tools, Automation
- **Stats:** 3 total users, 0 monthly users, 100.0% runs succeeded, 1 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

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?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — 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

## Korean Government Statistics Analyzer

Extract and analyze comprehensive statistical data from Korea's KOSIS (Korean Statistical Information Service) portal. This Apify Actor provides automated access to official Korean government statistics with structured data output.

### 🇰🇷 About KOSIS

KOSIS (Korean Statistical Information Service) is the official statistical portal operated by Statistics Korea, providing access to comprehensive government statistics including:

- Population and demographics
- Economic indicators (GDP, inflation, trade)
- Labor market statistics
- Industrial production data
- Social indicators (education, health, housing)
- Regional statistics
- Historical data (1908-1943)

### ✨ Features

- **Comprehensive Data Access**: Extract data from multiple statistical categories
- **Flexible Search**: Search by keywords, categories, or specific statistical tables
- **Multiple Output Formats**: Choose between structured, raw, or combined data formats
- **Demo Mode**: Test functionality without API credentials
- **Rate Limiting**: Built-in delays to respect API limits
- **Error Handling**: Robust error handling with fallback to demo mode
- **Metadata Support**: Optional inclusion of detailed metadata

### 🚀 Quick Start

#### Basic Usage

```json
{
  "searchKeyword": "인구",
  "maxItems": 5,
  "outputFormat": "structured"
}
```

#### Advanced Configuration

```json
{
  "searchKeyword": "경제성장",
  "vwCd": "MT_ZTITLE",
  "parentId": "A",
  "maxItems": 10,
  "includeMetadata": true,
  "outputFormat": "both",
  "delayBetweenRequests": 2000
}
```

### 📋 Input Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `searchKeyword` | string | `""` | Search keyword for filtering statistics (Korean or English) |
| `vwCd` | string | `"MT_ZTITLE"` | Service view code (see View Codes section) |
| `parentId` | string | `"A"` | Parent category ID for hierarchical browsing |
| `maxItems` | number | `10` | Maximum number of statistical tables to process (1-100) |
| `includeMetadata` | boolean | `true` | Include detailed metadata in output |
| `outputFormat` | string | `"structured"` | Output format: `"structured"`, `"raw"`, or `"both"` |
| `delayBetweenRequests` | number | `1000` | Delay between API requests in milliseconds (min: 500) |

### 🏷️ KOSIS View Codes

| Code | Description | Korean Name |
|------|-------------|-------------|
| `MT_ZTITLE` | Domestic Statistics (by Topic) | 국내통계 주제별 |
| `MT_OTITLE` | Domestic Statistics (by Agency) | 국내통계 기관별 |
| `MT_GTITLE01` | Local Indicators (by Topic) | e-지방지표(주제별) |
| `MT_GTITLE02` | Local Indicators (by Region) | e-지방지표(지역별) |
| `MT_CHOSUN_TITLE` | Historical Statistics (1908-1943) | 광복이전통계 |
| `MT_HANKUK_TITLE` | Korea Statistical Yearbook | 대한민국통계연감 |
| `MT_RTITLE` | International Statistics | 국제통계 |
| `MT_BUKHAN` | North Korea Statistics | 북한통계 |
| `MT_ETITLE` | English KOSIS | 영문 KOSIS |

### 📊 Output Data Structure

#### Structured Output

```json
{
  "statName": "인구총조사 총인구",
  "surveyDate": "2020년",
  "region": "전국",
  "category1": "총인구",
  "category2": "계",
  "value": 51829023,
  "unit": "명",
  "sourceTableId": "DT_1IN1502",
  "dataType": "population",
  "lastUpdated": "2021-08-31T00:00:00Z",
  "metadata": {
    "tableTitle": "인구총조사 총인구",
    "categories": {
      "c1": "전국",
      "c2": "계",
      "item": "총인구"
    },
    "originalData": { ... }
  },
  "extractedAt": "2024-09-21T10:30:00Z"
}
```

#### Data Types

The Actor automatically categorizes statistics into the following types:

- `population` - Population and demographic data
- `economic` - Economic indicators (GDP, growth, etc.)
- `labor` - Employment and labor market statistics
- `industry` - Industrial production and manufacturing
- `education` - Educational statistics
- `health` - Healthcare and medical statistics
- `environment` - Environmental indicators
- `housing` - Housing and real estate data
- `income` - Income and household statistics
- `prices` - Price indices and inflation data
- `general` - Other statistical categories

### 🔑 API Key Setup

#### Option 1: Environment Variable (Recommended)

Set the `KOSIS_API_KEY` environment variable in your Apify Actor settings.

#### Option 2: Actor Input

Include your API key in the Actor input (less secure):

```json
{
  "apiKey": "your-kosis-api-key-here",
  "searchKeyword": "인구"
}
```

#### Getting a KOSIS API Key

⚠️ **Important**: KOSIS API key registration requires Korean identity verification.

1. Visit [KOSIS OpenAPI Registration](https://kosis.kr/openapi/index/index.jsp)
2. Click "인증키 신청" (API Key Application)
3. Complete identity verification using:
   - Korean mobile phone number, OR
   - i-PIN (Korean digital identity)
4. Fill out the application form
5. Wait for approval (usually 1-2 business days)

**Note**: International users without Korean identity verification cannot obtain KOSIS API keys. The Actor will run in demo mode without an API key.

### 🎯 Use Cases

#### Research and Analysis

- Academic research on Korean demographics and economics
- Market research and business intelligence
- Policy analysis and government studies
- International comparative studies

#### Data Integration

- Integrate Korean statistics into dashboards
- Automated data collection for reports
- Real-time monitoring of economic indicators
- Historical trend analysis

#### Business Applications

- Market sizing and opportunity analysis
- Economic forecasting and planning
- Competitive intelligence
- Investment research

### 📈 Example Searches

#### Population Statistics

```json
{
  "searchKeyword": "인구",
  "vwCd": "MT_ZTITLE",
  "maxItems": 5
}
```

#### Economic Indicators

```json
{
  "searchKeyword": "GDP",
  "vwCd": "MT_ZTITLE",
  "maxItems": 3
}
```

#### Labor Market Data

```json
{
  "searchKeyword": "고용",
  "vwCd": "MT_ZTITLE",
  "maxItems": 8
}
```

#### Regional Statistics

```json
{
  "vwCd": "MT_GTITLE02",
  "parentId": "A",
  "maxItems": 10
}
```

### 🛠️ Technical Details

- **Runtime**: Node.js 18+
- **Dependencies**: Apify SDK, Axios
- **Rate Limiting**: Configurable delays between requests
- **Error Handling**: Automatic fallback to demo mode
- **Data Validation**: Input validation and sanitization
- **Monitoring**: Comprehensive logging and event tracking

### 📝 Demo Mode

When no API key is provided, the Actor runs in demo mode with sample Korean statistical data:

- Population census data
- Employment statistics
- GDP figures
- Consumer price index

Demo mode is perfect for:

- Testing the Actor functionality
- Understanding output formats
- Development and integration testing

### 🔍 Troubleshooting

#### Common Issues

1. **No API Key**: Actor runs in demo mode
   - Solution: Obtain KOSIS API key or use demo data

2. **API Authentication Error**: 403/401 responses
   - Solution: Verify API key validity and permissions

3. **No Data Found**: Empty results
   - Solution: Adjust search parameters or view codes

4. **Rate Limiting**: Too many requests
   - Solution: Increase `delayBetweenRequests` parameter

#### Support

For technical issues or questions:

- Check the Actor logs for detailed error messages
- Verify input parameters match the expected format
- Ensure API key has proper permissions
- Contact support through Apify platform

### 📄 License

This project is licensed under the Apache License 2.0.

### 🤝 Contributing

Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.

***

**Disclaimer**: This Actor is not officially affiliated with Statistics Korea or KOSIS. It provides a convenient interface to access publicly available statistical data through official APIs.

# Actor input Schema

## `searchKeyword` (type: `string`):

Enter keywords in Korean or English to find relevant statistical tables. For example: "인구" (population), "경제" (economy), "고용" (employment).

## `vwCd` (type: `string`):

KOSIS service view code to specify the type of statistics. MT\_ZTITLE for domestic statistics by topic is most common.

## `parentId` (type: `string`):

Parent category ID for hierarchical browsing. 'A' is the root level for most categories.

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

The maximum number of statistical tables to find and process. A higher number will result in a longer run time.

## `outputFormat` (type: `string`):

Choose the format for the output data. 'Structured' is recommended for most use cases.

## `includeMetadata` (type: `boolean`):

If checked, each data record will include a comprehensive metadata object with details about the data's source and structure.

## `delayBetweenRequests` (type: `integer`):

The delay in milliseconds between consecutive API requests to avoid rate limiting. Recommended to keep at 1000ms or higher.

## Actor input object example

```json
{
  "searchKeyword": "인구",
  "vwCd": "MT_ZTITLE",
  "parentId": "A",
  "maxItems": 10,
  "outputFormat": "structured",
  "includeMetadata": true,
  "delayBetweenRequests": 1000
}
```

# Actor output Schema

## `statName` (type: `string`):

The official name of the statistic (e.g., "인구총조사 총인구").

## `surveyDate` (type: `string`):

The date or period of the survey (e.g., "2020년").

## `region` (type: `string`):

The geographical area the data pertains to (e.g., "전국" for 'All Korea').

## `category1` (type: `string`):

The primary data category, providing the main classification for the value.

## `category2` (type: `string`):

A secondary data category for more detailed classification.

## `value` (type: `string`):

The numerical statistical value.

## `unit` (type: `string`):

The unit of measurement for the value (e.g., "명" for 'people', "원" for 'won').

## `sourceTableId` (type: `string`):

The unique identifier for the source table in the KOSIS database, useful for cross-referencing.

## `dataType` (type: `string`):

An inferred data type (e.g., 'population', 'economic') to help with filtering and analysis.

## `lastUpdated` (type: `string`):

The date the source data was last updated by the provider, in ISO 8601 format.

## `metadata` (type: `string`):

A comprehensive JSON string containing detailed metadata about the data's source and structure (if requested).

## `extractedAt` (type: `string`):

The timestamp when the data was extracted by the Actor, in ISO 8601 format.

# 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("hassy/korean-statistics-analyzer").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("hassy/korean-statistics-analyzer").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 '{}' |
apify call hassy/korean-statistics-analyzer --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,hassy/korean-statistics-analyzer"
        }
    }
}

```

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/NE9BKFCY15KzjOnzN/builds/4BhqT3TcfQwKwqU2g/openapi.json
