or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

admin-and-rbac.mdalerting.mdauthentication.mdclient-management.mddashboards.mddata-models.mddatasources.mdindex.mdlibrary-elements.mdplugin-management.mdsnapshot-management.mdusers-and-orgs.md

index.mddocs/

0

# Grafana Client

1

2

A comprehensive Python client library for accessing the Grafana HTTP API. The grafana-client package provides both synchronous and asynchronous interfaces for managing dashboards, data sources, users, organizations, alerting, and all other aspects of Grafana via its REST API.

3

4

## Package Information

5

6

- **Package Name**: grafana-client

7

- **Language**: Python

8

- **Installation**: `pip install grafana-client`

9

10

## Core Imports

11

12

```python

13

from grafana_client import GrafanaApi, AsyncGrafanaApi

14

from grafana_client import TokenAuth, HeaderAuth

15

```

16

17

Common for working with the API:

18

19

```python

20

from grafana_client import GrafanaApi

21

from grafana_client.model import DatasourceModel, DatasourceIdentifier, PersonalPreferences, DatasourceHealthResponse

22

```

23

24

## Basic Usage

25

26

### Synchronous API

27

28

```python

29

from grafana_client import GrafanaApi, TokenAuth

30

31

# Create API client with token authentication

32

auth = TokenAuth(token="your-grafana-api-token")

33

api = GrafanaApi(auth=auth, host="your-grafana-host")

34

35

# Connect and check health

36

api.connect()

37

print(f"Grafana version: {api.version}")

38

39

# Create a dashboard

40

dashboard_data = {

41

"dashboard": {

42

"title": "My Dashboard",

43

"panels": [],

44

"tags": ["example"]

45

}

46

}

47

result = api.dashboard.update_dashboard(dashboard_data)

48

print(f"Dashboard created: {result}")

49

50

# List data sources

51

datasources = api.datasource.list_datasources()

52

for ds in datasources:

53

print(f"Data source: {ds['name']} ({ds['type']})")

54

```

55

56

### Asynchronous API

57

58

```python

59

import asyncio

60

from grafana_client import AsyncGrafanaApi, TokenAuth

61

62

async def main():

63

# Create async API client

64

auth = TokenAuth(token="your-grafana-api-token")

65

api = AsyncGrafanaApi(auth=auth, host="your-grafana-host")

66

67

# Connect and check health

68

await api.connect()

69

version = await api.version

70

print(f"Grafana version: {version}")

71

72

# Create a dashboard

73

dashboard_data = {

74

"dashboard": {

75

"title": "My Async Dashboard",

76

"panels": [],

77

"tags": ["async", "example"]

78

}

79

}

80

result = await api.dashboard.update_dashboard(dashboard_data)

81

print(f"Dashboard created: {result}")

82

83

# List data sources

84

datasources = await api.datasource.list_datasources()

85

for ds in datasources:

86

print(f"Data source: {ds['name']} ({ds['type']})")

87

88

# Run async code

89

asyncio.run(main())

90

```

91

92

## Architecture

93

94

The grafana-client follows an element-based architecture that mirrors Grafana's API structure:

95

96

### Core Components

97

98

- **GrafanaApi/AsyncGrafanaApi**: Main entry points providing access to all API elements

99

- **Element Classes**: Specialized classes for different Grafana API areas (Dashboard, Datasource, User, etc.)

100

- **Authentication**: Pluggable authentication system supporting tokens, headers, and basic auth

101

- **Client Layer**: Low-level HTTP clients handling requests, timeouts, and error handling

102

- **Data Models**: Type-safe data classes for complex API payloads and responses

103

104

### Element-Based Design

105

106

Each major Grafana API area is represented by an element class accessible as an attribute:

107

108

- `api.dashboard` - Dashboard operations

109

- `api.datasource` - Data source management

110

- `api.user` - Current user operations

111

- `api.users` - Multi-user operations

112

- `api.teams` - Team management

113

- `api.organization` - Current organization

114

- `api.organizations` - Multi-organization operations

115

- `api.admin` - Administrative functions

116

- `api.alerting` - Legacy alerting

117

- `api.alertingprovisioning` - Modern alerting provisioning

118

- `api.rbac` - Role-based access control

119

- And many more...

120

121

This design provides a clean, organized API surface while maintaining full access to Grafana's extensive functionality.

122

123

## Capabilities

124

125

### Authentication

126

127

Token-based and custom header authentication for secure API access, with support for basic authentication and custom authentication schemes.

128

129

```python { .api }

130

class TokenAuth:

131

def __init__(self, token: str): ...

132

133

class HeaderAuth:

134

def __init__(self, name: str, value: str): ...

135

```

136

137

[Authentication](./authentication.md)

138

139

### Client Management

140

141

Core client classes for both synchronous and asynchronous operations, connection management, error handling, and factory methods for convenient instantiation.

142

143

```python { .api }

144

class GrafanaApi:

145

def __init__(self, auth, host: str = "localhost", port: Optional[int] = None,

146

url_path_prefix: str = "", protocol: str = "http",

147

verify: bool = True, timeout: float = 5.0,

148

user_agent: Optional[str] = None, organization_id: Optional[int] = None,

149

session_pool_size: int = 10): ...

150

151

def connect(self) -> None: ...

152

153

@property

154

def version(self) -> str: ...

155

156

@classmethod

157

def from_url(cls, url: str, credential, timeout: float = 5.0) -> 'GrafanaApi': ...

158

159

@classmethod

160

def from_env(cls, timeout: float = 5.0) -> 'GrafanaApi': ...

161

162

class AsyncGrafanaApi:

163

def __init__(self, auth, host: str = "localhost", port: Optional[int] = None,

164

url_path_prefix: str = "", protocol: str = "http",

165

verify: bool = True, timeout: float = 5.0,

166

user_agent: Optional[str] = None, organization_id: Optional[int] = None): ...

167

168

async def connect(self) -> None: ...

169

170

@property

171

async def version(self) -> str: ...

172

```

173

174

[Client Management](./client-management.md)

175

176

### Dashboard Operations

177

178

Complete dashboard lifecycle management including creation, updates, deletion, permissions, versioning, and search capabilities.

179

180

```python { .api }

181

def get_dashboard(self, dashboard_uid: str): ...

182

def update_dashboard(self, dashboard: dict): ...

183

def delete_dashboard(self, dashboard_uid: str): ...

184

def get_permissions_by_uid(self, dashboard_uid: str): ...

185

def update_permissions_by_uid(self, dashboard_uid: str, items: list): ...

186

def get_dashboards_tags(self): ...

187

```

188

189

[Dashboards](./dashboards.md)

190

191

### Data Source Management

192

193

Comprehensive data source operations including CRUD operations, health checks, query execution, and smart query capabilities with type-safe data models.

194

195

```python { .api }

196

def list_datasources(self): ...

197

def get_datasource_by_uid(self, datasource_uid: str): ...

198

def create_datasource(self, datasource: dict): ...

199

def update_datasource_by_uid(self, datasource_uid: str, datasource: dict): ...

200

def delete_datasource_by_uid(self, datasource_uid: str): ...

201

def health(self, datasource_uid: str): ...

202

def query(self, datasource_id: int, query: dict, timestamp: Optional[int] = None): ...

203

def health_check(self, datasource: dict): ...

204

```

205

206

[Data Sources](./datasources.md)

207

208

### User and Organization Management

209

210

User lifecycle management, team operations, organization administration, and preference management with comprehensive search and filtering capabilities.

211

212

```python { .api }

213

def get_actual_user(self): ...

214

def search_users(self, query: Optional[str] = None, page: int = 1, perpage: int = 1000): ...

215

def get_user(self, user_id: int): ...

216

def find_user(self, login_or_email: str): ...

217

def search_teams(self, query: Optional[str] = None, page: int = 1, perpage: int = 1000): ...

218

def get_current_organization(self): ...

219

def list_organization(self): ...

220

```

221

222

[Users and Organizations](./users-and-orgs.md)

223

224

### Alerting and Notifications

225

226

Legacy alerting, modern alerting provisioning, notification channels, contact points, notification policies, and mute timings management.

227

228

```python { .api }

229

def get_alertrule(self, folder_name: str, alertrule_name: str): ...

230

def create_alertrule(self, folder_name: str, alertrule: dict): ...

231

def get_alertrules_all(self): ...

232

def get_contactpoints(self, name: Optional[str] = None): ...

233

def create_contactpoint(self, contactpoint: dict, disable_provenance: bool = False): ...

234

def get_notification_policy_tree(self): ...

235

```

236

237

[Alerting](./alerting.md)

238

239

### Admin and RBAC

240

241

Administrative functions, user management, role-based access control, service accounts, and system-level operations with comprehensive permission management.

242

243

```python { .api }

244

def settings(self): ...

245

def stats(self): ...

246

def create_user(self, user: dict): ...

247

def change_user_permissions(self, user_id: int, is_grafana_admin: bool): ...

248

def get_rbac_roles_all(self): ...

249

def set_rbac_datasources_teams(self, datasource_uid: str, team_id: int, permission: str): ...

250

```

251

252

[Admin and RBAC](./admin-and-rbac.md)

253

254

### Folder Management

255

256

Organization and management of dashboard folders with hierarchical structure support, including creation, updates, permissions, and nested folder operations.

257

258

```python { .api }

259

def get_all_folders(self, parent_uid: Optional[str] = None): ...

260

def get_folder(self, uid: str): ...

261

def get_folder_by_id(self, folder_id: int): ...

262

def create_folder(self, title: str, uid: Optional[str] = None, parent_uid: Optional[str] = None): ...

263

def move_folder(self, uid: str, parent_uid: str): ...

264

def update_folder(self, uid: str, title: Optional[str] = None, version: Optional[int] = None,

265

overwrite: bool = False, new_uid: Optional[str] = None): ...

266

def delete_folder(self, uid: str): ...

267

def get_folder_permissions(self, uid: str): ...

268

def update_folder_permissions(self, uid: str, items: list): ...

269

def update_folder_permissions_for_user(self, uid: str, user_id: int, items: dict): ...

270

```

271

272

[Folder Management](./folder-management.md)

273

274

### Search and Discovery

275

276

Comprehensive search functionality for dashboards, folders, and other resources with advanced filtering, tagging, and pagination capabilities.

277

278

```python { .api }

279

def search_dashboards(self, query: Optional[str] = None, tag: Optional[Union[str, list]] = None,

280

type_: Optional[str] = None, dashboard_ids: Optional[list] = None,

281

dashboard_uids: Optional[list] = None, folder_ids: Optional[list] = None,

282

folder_uids: Optional[list] = None, starred: Optional[bool] = None,

283

limit: Optional[int] = None, page: Optional[int] = None): ...

284

```

285

286

[Search and Discovery](./search-and-discovery.md)

287

288

### Service Account Management

289

290

Service account lifecycle management for programmatic access, including creation, token management, permissions, and integration with authentication systems.

291

292

```python { .api }

293

def get(self, service_account_id: int): ...

294

def create(self, service_account: dict): ...

295

def update(self, service_account_id: int, service_account: dict): ...

296

def delete(self, service_account_id: int): ...

297

def search(self, query: Optional[str] = None, page: Optional[int] = None, perpage: Optional[int] = None): ...

298

def search_one(self, service_account_name: str): ...

299

def get_tokens(self, service_account_id: int): ...

300

def create_token(self, service_account_id: int, content: dict): ...

301

def delete_token(self, service_account_id: int, service_account_token_id: int): ...

302

```

303

304

[Service Account Management](./service-account-management.md)

305

306

### Plugin Management

307

308

Plugin lifecycle management including listing, installation, uninstallation, health checks, and metrics collection for Grafana plugins.

309

310

```python { .api }

311

def list(self): ...

312

def by_id(self, plugin_id: str): ...

313

def install(self, plugin_id: str, version: Optional[str] = None, errors: str = "raise"): ...

314

def uninstall(self, plugin_id: str, errors: str = "raise"): ...

315

def health(self, plugin_id: str): ...

316

def metrics(self, plugin_id: str): ...

317

```

318

319

[Plugin Management](./plugin-management.md)

320

321

### Snapshot Management

322

323

Dashboard snapshot creation and management for sharing and archiving dashboard states with configurable expiration and external storage options.

324

325

```python { .api }

326

def create_new_snapshot(self, dashboard: dict, name: Optional[str] = None,

327

expires: Optional[int] = None, external: Optional[bool] = None,

328

key: Optional[str] = None, delete_key: Optional[str] = None): ...

329

def get_dashboard_snapshots(self): ...

330

def get_snapshot_by_key(self, key: str): ...

331

def delete_snapshot_by_key(self, key: str): ...

332

def delete_snapshot_by_delete_key(self, delete_key: str): ...

333

```

334

335

[Snapshot Management](./snapshot-management.md)

336

337

### Library Element Management

338

339

Management of reusable library panels and variables that can be shared across multiple dashboards. Available in Grafana 8.2+.

340

341

```python { .api }

342

def get_library_element(self, element_uid: str): ...

343

def get_library_element_by_name(self, element_name: str): ...

344

def get_library_element_connections(self, element_uid: str): ...

345

def create_library_element(self, model: dict, name: Optional[str] = None,

346

kind: int = 1, uid: Optional[str] = None,

347

folder_uid: Optional[str] = None): ...

348

def update_library_element(self, uid: str, model: dict, name: Optional[str] = None,

349

kind: int = 1, folder_uid: Optional[str] = None,

350

version: Optional[int] = None): ...

351

def delete_library_element(self, element_uid: str): ...

352

def list_library_elements(self, search_string: Optional[str] = None,

353

kind: Optional[int] = None, sort_direction: Optional[str] = None,

354

type_filter: Optional[str] = None, exclude_uid: Optional[str] = None,

355

folder_filter: Optional[str] = None, per_page: Optional[int] = None,

356

page: Optional[int] = None): ...

357

```

358

359

[Library Elements](./library-elements.md)

360

361

### Data Models and Types

362

363

Type-safe data classes for API payloads, responses, and configuration objects with validation and serialization support.

364

365

```python { .api }

366

@dataclass

367

class DatasourceModel:

368

name: str

369

type: str

370

url: str

371

access: str

372

database: Optional[str] = None

373

user: Optional[str] = None

374

jsonData: Optional[Dict] = None

375

secureJsonData: Optional[Dict] = None

376

secureJsonFields: Optional[Dict] = None

377

378

def asdict(self) -> Dict: ...

379

380

@dataclass

381

class DatasourceIdentifier:

382

id: Optional[str] = None

383

uid: Optional[str] = None

384

name: Optional[str] = None

385

386

@dataclass

387

class PersonalPreferences:

388

homeDashboardId: Optional[int] = None

389

homeDashboardUID: Optional[str] = None

390

locale: Optional[str] = None

391

theme: Optional[str] = None

392

timezone: Optional[str] = None

393

weekStart: Optional[str] = None

394

395

def asdict(self, filter_none: bool = False) -> Dict: ...

396

```

397

398

[Data Models](./data-models.md)

399

400

## Error Handling

401

402

The library provides a comprehensive exception hierarchy for robust error handling:

403

404

```python { .api }

405

class GrafanaException(Exception):

406

def __init__(self, status_code: int, response, message: str): ...

407

408

class GrafanaTimeoutError(GrafanaException): ...

409

class GrafanaServerError(GrafanaException): ...

410

class GrafanaClientError(GrafanaException): ...

411

class GrafanaBadInputError(GrafanaClientError): ...

412

class GrafanaUnauthorizedError(GrafanaClientError): ...

413

```

414

415

All API operations can raise these exceptions based on HTTP response codes and error conditions.