# Use the Python client

> Install the Cost Explorer Python client, create it from an OpenStack SDK connection, and handle the errors it raises.

The `vexxhost-costexplorerclient` package is the Python client for Cost Explorer. It signs in with the same session as the
OpenStack SDK, so it works with your existing `clouds.yaml`.

## Before you begin

Set up a `clouds.yaml` entry or an application credential. See
[Use OpenStack from Python](/developer/python).

## 1. Install the client

```sh
pip install vexxhost-costexplorerclient
```

## 2. Create the client

```python
import openstack
from costexplorerclient import Client

conn = openstack.connect(cloud="vexxhost")
costs = Client("1", session=conn.session)
```

The client finds Cost Explorer in the [service catalog](/identity/service-catalog).
The other Cost Explorer guides call it `costs`.

## 3. Make a call

Methods take and return dictionaries with the same fields as the API's JSON, so the
[API reference](/cost-explorer/api) also describes each call. `costs.cost_reports` creates reports and `costs.cost_forecasts` creates forecasts.

```python
report = costs.cost_reports.create(
    time_period={"start": "2026-09-01T00:00:00Z", "end": "2026-10-01T00:00:00Z"},
    granularity="monthly",
)
print(report["results_by_time"][0]["total"]["cost"]["amount"])
```

## 4. Handle errors

A failed request raises an exception from `costexplorerclient.exceptions`, such as `Conflict`,
`TooManyRequests` or `Unauthorized`. The exceptions are also `keystoneauth1.exceptions` HTTP errors.

| Attribute     | Contents                                                                 |
| ------------- | ------------------------------------------------------------------------ |
| `status_code` | The HTTP status.                                                         |
| `problem`     | The API's error document, with `title`, `detail` and any field `errors`. |
| `request_id`  | The `X-Request-ID` of the request, for support.                          |
| `retry_after` | Seconds to wait before retrying, on `429 Too Many Requests`.             |

```python
from costexplorerclient import exceptions

try:
    costs.cost_reports.create(time_period={"start": "2026-09-01T00:00:00Z", "end": "2026-10-01T00:00:00Z"}, granularity="monthly")
except exceptions.ClientException as error:
    print(error.status_code, error.request_id, error.problem["detail"])
    raise
```

## Next steps

* Use `costs` in the Python examples of the other Cost Explorer guides.
