Metadata-Version: 2.1
Name: apccapi
Version: 0.2.1
Summary: APCC Climate Information toolKit API package
Home-page: https://www.apcc21.org
Author: APEC Climate Center
Author-email: joohyung@apcc21.org
Project-URL: CLIK, https://apcc21.org/clik/
Keywords: APCC,apcc,Climate,Climate Information,Climate API
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.7
Description-Content-Type: text/markdown
License-File: LICENSE

# apccapi

Python client for the Open API of the [APCC Climate Information toolKit
(CLIK)](https://apcc21.org/clik/). It submits a data request, waits for the job
to finish, downloads the result file, and raises `apccapi.ClikApiError` if
anything goes wrong.

| Function | Data |
|---|---|
| `download_MME_3MONTH`, `download_MME_6MONTH` | APCC multi-model ensemble (MME) forecasts, 3- and 6-month |
| `download_MME_MODEL` | Individual model forecasts |
| `download_CMIP5` | CMIP5 |
| `download_ERA5` | ERA5 |
| `download_NCEP1`, `download_NCEP2` | NCEP1 / NCEP2 |
| `download_S2S_MME` | Subseasonal-to-seasonal (S2S) MME forecasts, new in 0.2.0 ([details](#s2s-mme-download)) |

Also included: the low-level `Client.retrieve()` for any job type, and
`ClippingClient` for cropped PNG/NetCDF output.

**Requirements:** Python 3.7 or later. The automated tests run on Python
3.7-3.12 in CI. `requests` and `urllib3` are installed automatically.

## Installation

Install via pip with:

```bash
$ pip install apccapi
```

## Configure (Linux)

Obtain your API key from the CLIK (Climate Information toolKit) at https://apcc21.org/clik/ and enter it into the apccapi.properties file, formatting it as follows:

```
$ vi ~/apccapi.properties

key={your API key}
request_url=https://apcc21.org/clikapi/request/apccdata
status_url=https://apcc21.org/clikapi/request/status
```

## Configure (Windows)

Obtain your API key from the CLIK (Climate Information toolKit) at https://apcc21.org/clik/, and create the apccapi.properties file in your Windows Home directory (typically C:\Users\YourUserName) with the following format:

```
key={your API key}
request_url=https://apcc21.org/clikapi/request/apccdata
status_url=https://apcc21.org/clikapi/request/status
```

## Service availability

The `request_url` / `status_url` above point to the production CLIK API
(`apcc21.org`), which is what all dataset helpers except S2S MME use.

**`download_S2S_MME` is not available on the production API yet.** The
production server rejected the `S2S_MME` job type when last checked
(2026-11-11), so the helper raises `ClikApiError` with the server's message
there. The helper itself was verified end-to-end against a CLIK server that
supports S2S MME (downloaded and validated on 2026-11-11). To use it before it
reaches production, ask the APCC CLIK team which server provides S2S MME and set
`request_url` / `status_url` in your properties file to that server's addresses.
Once S2S MME is deployed to production, no package update is needed: keep the
default production URLs.

## Usage

### Quick start: dataset download helpers

Each helper submits the request, polls until it's done, downloads the
result, and returns the output file path (or raises on failure - see
[Error handling](#error-handling)).

```python
import apccapi

apccapi.download_MME_3MONTH(
	{
		'type': 'FORECAST',
		'method': 'SCM',
		'variable': ['prec', 't2m'],
		'period': ['Monthly mean'],
		'yearmonth': ['201909']
	},
	'mme3.zip'
)

apccapi.download_MME_6MONTH(
	{
		'type': 'FORECAST',
		'method': 'SCM',
		'variable': ['prec', 't2m'],
		'period': ['Monthly mean'],
		'yearmonth': ['201909']
	},
	'mme6.zip'
)

apccapi.download_MME_MODEL(
	{
		'type': 'FORECAST',
		'institute': 'APCC',
		'model': 'SCOPS',
		'variable': ['prec', 't2m'],
		'yearmonth': ['201909']
	},
	'model.zip'
)

apccapi.download_CMIP5(
	{
		'code': 'AD'
	},
	'cmip5.zip'
)

apccapi.download_ERA5(
	{
		'timestep': 'DAILY',      # 'DAILY' | 'MONTHLY' | 'HOURLY'
		'level': 'single',        # 'pressure' | 'single'
		'variable': 't2m',
		'year': '2020',
		'month': '12'             # omit for 'MONTHLY'
	},
	't2m_202012.nc'
)

apccapi.download_NCEP1(
	{
		'timestep': 'DAILY',      # 'DAILY' | 'MONTHLY'
		'level': 'pressure',
		'variable': 'air',
		'year': '2022'            # only required for 'DAILY'
	},
	'air.2022.nc'
)

apccapi.download_NCEP2(
	{
		'timestep': 'DAILY',
		'level': 'pressure',
		'variable': 'air',
		'year': '2022'
	},
	'air.2022.nc'
)

apccapi.download_S2S_MME(
	{
		'prediction_type': 'FORECAST',
		'mme_type': 'DMME',
		'timestep': 'WEEK_MEAN',
		'variables': ['prec', 'sst', 't2m'],
		'issued_ymd': ['20261019']
	},
	's2s_mme.zip'
)
```

More runnable examples (one file per dataset) are in [`example/`](example/).

### S2S MME download

`download_S2S_MME(request, output_zipfile_name)` requests subseasonal-to-seasonal
multi-model ensemble data. It returns `output_zipfile_name` on success and
raises `apccapi.ClikApiError` on failure. All five request fields are required;
a missing field raises `ClikApiError`.

| Field | Type | Example |
|---|---|---|
| `prediction_type` | str | `'FORECAST'` |
| `mme_type` | str | `'DMME'` |
| `timestep` | str | `'WEEK_MEAN'` |
| `variables` | list of str | `['prec', 'sst', 't2m']` |
| `issued_ymd` | list of str, `'YYYYMMDD'` | `['20261019']` |

These field names differ from the other MME helpers (`type`, `method`,
`variable`, `period`, `yearmonth`), because the helper sends them to the server
unchanged. The accepted values are defined by the server; the example values
above are the combination verified with this release. Requires a server that
supports S2S MME (see [Service availability](#service-availability)).

```python
import zipfile
import apccapi

try:
	path = apccapi.download_S2S_MME(
		{
			'prediction_type': 'FORECAST',
			'mme_type': 'DMME',
			'timestep': 'WEEK_MEAN',
			'variables': ['prec', 'sst', 't2m'],
			'issued_ymd': ['20261019']
		},
		's2s_mme.zip'
	)
except apccapi.ClikApiError as e:
	print('Request failed:', e)
else:
	with zipfile.ZipFile(path) as z:
		z.extractall('s2s_mme')
		print(z.namelist())
```

For this request a server supporting S2S MME returned a zip archive with six
NetCDF files: `prec`, `sst`, and `t2m`, each as a week 1-4 mean and a week 3-4
mean (1-degree global grid, one time step per file).

### Low-level usage: `Client.retrieve`

The helpers above are thin wrappers around `Client.retrieve()`. Call it
directly when you need a `jobtype`/`dataset` combination that doesn't have
a dedicated helper yet, or the clipping jobtypes (`Clipping_MME`,
`Clipping_Model`):

```python
import apccapi

c = apccapi.Client()
c.retrieve(
	{
		'jobtype': 'MME',
		'dataset': 'MME_3MONTH',
		'type': 'FORECAST',
		'method': 'SCM',
		'variable': ['prec', 't2m'],
		'period': ['Monthly mean'],
		'yearmonth': ['201909']
	},
	'mme3.zip'
)
```

### Clipping

`ClippingClient` calls a separate clipping/masking service and returns a
cropped PNG or NetCDF file for a bounding box. On success, `clip()` returns
`True` after writing the result file or files to the current directory:

```python
import apccapi

c = apccapi.ClippingClient()
c.clip(
	{
		'lead_month': '3-MON',      # '3-MON' | '6-MON'
		'variable': 'prec',         # prec, slp, sst, t2m, t850, z500
		'method': 'SCM',            # SCM, GAUS
		'period': 'Monthly mean',   # Monthly mean, Seasonal mean
		'iyear': '2021',            # issued year
		'imonth': '2',              # issued month
		'cowest': '188',
		'coeast': '191',
		'conorth': '-11',
		'cosouth': '-15',
		'return_type': 'png'        # 'png' | 'nc'
	}
)
```

The clipping service determines each result filename. For every result URL,
`clip()` writes the file using the substring after its final `/` in the current
working directory (for example, `https://example.test/results/crop.png` is
saved as `./crop.png`). The name assembled from the request fields is only
used in the start log; it is not the output filename. `clip()` has no output
path or custom-filename option, so callers that need a chosen filename should
run it from the desired directory and rename the downloaded file after it
returns `True`. This preserves the existing `True` success return type.

### Error handling

Every expected failure (invalid helper/clipping input, rejected request,
malformed API response, job that ends in `Failed`, exhausted retries, or a
broken download) raises `apccapi.ClikApiError` instead of failing silently.
This applies to `Client`, all dataset helpers, and `ClippingClient`:

```python
import apccapi

try:
	apccapi.download_ERA5(
		{'timestep': 'MONTHLY', 'level': 'single', 'variable': 't2m', 'year': '2020'},
		't2m_2020.nc'
	)
except apccapi.ClikApiError as e:
	print('Request failed:', e)
```

### Optional polling deadline

`Client` preserves its existing automatic polling behavior by default. To
bound the time spent waiting for a submitted job, pass `polling_timeout` in
seconds. Once the deadline expires, `retrieve()` raises
`apccapi.PollingTimeoutError` (a `ClikApiError` subclass).

```python
import apccapi

c = apccapi.Client(polling_timeout=900)
c.retrieve(details, 'output.nc')  # details: a request dict, as in the low-level example
```

### Upgrading from 0.1.1 to 0.2.0

New in 0.2.0: `download_S2S_MME`, the `polling_timeout` option, and
`PollingTimeoutError`. Existing code keeps working unless it relied on the old
failure behavior:

- `Client.download()` and `ClippingClient.clip()` no longer return `False` for
  expected failures; they raise `ClikApiError`. Replace `if not ...` checks
  with `try/except apccapi.ClikApiError`.
- Missing helper input fields, malformed API responses, and an unreadable
  properties file now raise `ClikApiError` instead of `KeyError`, `TypeError`,
  JSON parsing errors, or `OSError`.
- `ClippingClient` no longer prints; it reports through `logging` (logger
  `clipsapi`).
- Unchanged: the properties file (`~/apccapi.properties`) and its keys, the
  return value of `Client.retrieve()` and the dataset helpers (the output
  path), and `True` from a successful `Client.download()` / `clip()`.

Downloads are written to a temporary file in the destination directory and
replace an existing output file only after a successful HTTP response and
complete write, so a failed download leaves an existing output file unchanged.
A non-2xx HTTP status counts as a failed attempt (0.1.1 saved its body as the
result file).

See `CHANGELOG.md` in the source repository for the full list.

## License

MIT License

Copyright (c) 2019 - 2024, APEC Climate Center

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
