# Get All Cost Codes

Last updated: 2026-11-25

Retrieve cost-code records for one business unit. Use the returned CostCodeId when another documented method needs a cost-code reference; Code and Description are display values.

 

## Request

 

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

 

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

 

The correct path ends at CostCode/GetAll. The previous article accidentally appended the text “cost codes” to its URL; that trailing text is not part of the request.

 

## Authentication and scope

 

| Parameter | Location | Meaning |
| --- | --- | --- |
| businessUnitApiKey | URL path | Business-unit API key; never a numeric ID. |

 

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

 

### 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/GetAll"
```

 

### 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/GetAll";

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/GetAll"

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

 

The verified request returned **HTTP 200 with a top-level JSON array**, containing 14 records in the tested business unit. Do not assume that every unit has the same number of cost codes.

 

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

 

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

 

- Consider the Skip and Take method for larger lists; GetAll has no pagination parameters in the supplied definition.
- The API collection also defines an include-deleted variant ending /true. That variant and deleted-record inclusion were not tested in this batch.
- Do not assume that GetAll returns only active records: inspect IsActive and Void and verify the behaviour your integration needs.
- Cross-business access, ordering guarantees, maximum response size 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.
