# Get Cost Code by ID

Last updated: 2026-11-25

Retrieve one cost-code record using CostCodeId and its owning business unit’s API key. Obtain the ID from a cost-code list rather than substituting the display Code.

 

## Request

 

` GET https://api.myzahara.net/api/{businessUnitApiKey}/CostCode/Get/{costCodeId} `

 

Send ` Accept: application/json `. No request body appears in the supplied API definition.

 

The path contains one numeric ID after CostCode/Get. Do not confuse it with the two-segment Skip and Take variant.

 

## Authentication and scope

 

| Parameter | Location | Meaning |
| --- | --- | --- |
| businessUnitApiKey | URL path | Business-unit API key; never a numeric ID. |
| costCodeId | URL path | Integer ≥ 1. Use an authorised reference from the same context. |

 

Keep credentials in an environment variable or secret store. The API key appears in the request path, so redact URLs in logs, proxy traces and error reporting. Do not give real keys to a coding agent in a prompt or documentation URL. Use the correct key scope; do not assume a tenancy key works in a business-unit method.

 

## Working examples

 

All three clients were executed successfully against the production API on 25 November 2026. Their JSON root shape and, where applicable, item counts matched the direct request.

 

| Environment variable | Purpose |
| --- | --- |
| ZAHARA\_BUSINESS\_UNIT\_API\_KEY | Required API key; store privately. |
| ZAHARA\_COST\_CODE\_ID | costCodeId. |

 

### cURL

 

Requires cURL 7.76.0+ for ` --fail-with-body `. It prints the complete response, including error JSON on an HTTP failure. Use a secure development terminal.

 

```sh
# cURL 7.76.0+. Set the environment variables documented below.
# Treat response data as confidential. Keep keys out of logs.
curl --fail-with-body --silent --show-error --max-time 30 \
  --request GET \
  --header 'Accept: application/json' \
  "https://api.myzahara.net/api/${ZAHARA_BUSINESS_UNIT_API_KEY:?Set ZAHARA_BUSINESS_UNIT_API_KEY}/CostCode/Get/${ZAHARA_COST_CODE_ID:?Set ZAHARA_COST_CODE_ID}"
```

 

### JavaScript (Node.js 22+)

 

Uses built-in fetch and a 30-second timeout; no extra packages are needed. Check the HTTP status and inspect the parsed result before accessing fields.

 

```javascript
// Node.js 22+. Standard library only.
function required(name) {
  const value = process.env[name];
  if (!value) throw new Error('Set ' + name);
  return value;
}
const key = required('ZAHARA_BUSINESS_UNIT_API_KEY');
const base = 'https://api.myzahara.net';
let path = "CostCode/Get/{costCodeId}";
const costCodeId = required('ZAHARA_COST_CODE_ID');
if (!/^\d+$/.test(costCodeId) || !Number.isSafeInteger(Number(costCodeId)) || Number(costCodeId) < 1) throw new Error('Invalid ZAHARA_COST_CODE_ID');
path = path.replace('{costCodeId}', encodeURIComponent(costCodeId));
const url = new URL(base + '/api/' + encodeURIComponent(key) + '/' + path);


let response;
try {
  response = await fetch(url, {
    method: 'GET', headers: { Accept: 'application/json' },
    signal: AbortSignal.timeout(30000), redirect: 'error'
  });
} catch { throw new Error('Zahara request failed or timed out; URL omitted to protect the key'); }
if (!response.ok) throw new Error('Zahara returned HTTP ' + response.status);
const text = await response.text();
// Some methods may return an empty successful body. Do not assume a JSON shape.
const result = text.trim() ? JSON.parse(text) : null;
// Use a secure console; response fields may include financial or business data.
console.log(JSON.stringify(result, null, 2));
```

 

### Python 3 (standard library)

 

Rejects redirects and reports HTTP errors without including the credential-bearing URL.

 

```python
# Python 3. Standard library only.
import json
import os
from urllib.parse import quote, urlencode
from urllib.request import Request, build_opener, HTTPRedirectHandler
from urllib.error import HTTPError, URLError

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

def required(name):
    value = os.environ.get(name)
    if not value:
        raise SystemExit('Set ' + name)
    return value

key = required('ZAHARA_BUSINESS_UNIT_API_KEY')
base = 'https://api.myzahara.net'
path = "CostCode/Get/{costCodeId}"
costCodeId = required('ZAHARA_COST_CODE_ID')
if not costCodeId.isascii() or not costCodeId.isdigit() or int(costCodeId) < 1:
    raise SystemExit('Invalid ZAHARA_COST_CODE_ID')
path = path.replace('{costCodeId}', quote(costCodeId, safe=''))
url = base + '/api/' + quote(key, safe='') + '/' + path


request = Request(url, method='GET',
    headers={'Accept': 'application/json'})
try:
    with build_opener(NoRedirect).open(request, timeout=30) as response:
        text = response.read().decode('utf-8')
except HTTPError as error:
    raise SystemExit('Zahara returned HTTP ' + str(error.code)) from None
except URLError:
    raise SystemExit('Zahara request failed; URL omitted to protect the key') from None
result = json.loads(text) if text.strip() else None
# Use a secure console: the result may contain confidential data.
print(json.dumps(result, indent=2))
```

 

## Successful response

 

A valid ID returned **HTTP 200 and one JSON object**, not an array. A nonexistent ID returned **HTTP 200 with JSON null**. Check for null before reading Code, Description or flags.

 

### Representative response example

 

This is a shortened example with fictional business identifiers, text and dates. The currency names and symbols, where shown, are reference labels. Array length is illustrative; omitted data is not a promise that it will be absent.

 

```json
{
  "Id": 1001,
  "SyncFriendlyName": "EXAMPLE-001",
  "CostCodeId": 1001,
  "BusinessUnitId": 101,
  "Code": "EXAMPLE-001",
  "Description": "Example cost code",
  "SyncId": null,
  "SyncDate": null,
  "SyncType": null,
  "LastUpdated": "2026-01-02T12:00:00Z",
  "DateCreated": "2026-01-01T12:00:00Z",
  "IsActive": true,
  "IsStartingDefaultCode": false,
  "Void": false,
  "BusinessUnit": null,
  "Suppliers": []
}
```

 

### Cost-code field reference

 

| Field | Observed type | Meaning / integration use |
| --- | --- | --- |
| CostCodeId | number | Identifier for retrieving or referencing this cost code; not the display Code. |
| Id | number | Additional identifier returned by the API. It matched CostCodeId in the tested records; use the documented CostCodeId for integration references. |
| BusinessUnitId | number | Owning business-unit ID, not its API key. |
| Code | string | Display/accounting code. Do not assume its format or uniqueness across businesses. |
| Description | string or null | Description; null appeared in the complete list. |
| SyncFriendlyName | string | Synchronisation-facing label. Do not use it in place of the numeric ID. |
| SyncId / SyncDate / SyncType | null or string / null or string / null or number | Synchronisation metadata; non-null values appeared in the complete list. Enum semantics and date format guarantees were not verified. |
| LastUpdated / DateCreated | string | Observed UTC date-time strings. |
| IsActive | boolean | Activity flag. Inspect it rather than assuming every returned code is usable. |
| IsStartingDefaultCode | boolean | Default-code configuration flag; default-selection behaviour was not tested. |
| Void | boolean | Void flag. Deleted-item behaviour was not established by the default request. |
| BusinessUnit | null | Null in the test; populated relationship shape is unverified. |
| Suppliers | array | Empty in the tested records. The shape of non-empty entries is unverified. |

 

The table combines observations from the complete cost-code list. A single record or page does not establish every possible type or null. These are observed fields, not a complete contractual schema.

 

## Handling failures

 

A deliberately invalid key returned **HTTP 401** with:

 

```json
{
  "ApiMessage": "The API key is missing or not recognised.",
  "StatusCode": 401
}
```

 

A known-absent ID in the tested business unit returned **HTTP 200 with JSON null**. Treat this as a missing result, not a populated object or a transport error.

 

Check the HTTP status before using the response. Handle timeouts, unexpected content types and unknown result shapes. Do not convert a failed request into an empty successful result. The supplied clients make a single request and do not automatically retry it.

 

## Integration notes

 

- After parsing JSON, handle a null result explicitly; HTTP 200 alone does not mean the record exists.
- The single record and complete list use the same observed fields, but one record cannot establish every possible nullable or synchronisation value.
- A separate include-deleted variant appears in the collection; it was not tested.
- Deletion/void behaviour, cross-business IDs, permission rules and rate limits remain unverified.
- These observations apply to the tested configuration, not every version or tenant. Do not infer undocumented response fields, permission rules or limits.

 

## Verification

 

Verified on 25 November 2026 against the production API with an authorised business-unit key. Direct request: HTTP 200. cURL, Node.js and Python each completed successfully. A known-absent identifier returned HTTP 200 with null.
