Angular/TypeScript SDK (Beta)
The Angular/TypeScript SDK is an auto-generated client library for the EnergyCAP REST API, built as an Angular module. It provides injectable service classes for every API resource, typed request/response models, and returns RxJS Observables — so you can work with EnergyCAP data using standard Angular patterns.
Installation
Install from npm:
npm install @energycap/energycap-sdk-angular
| Package | @energycap/energycap-sdk-angular |
| Current version | 8.2603.x |
| Peer dependencies | @angular/core >= 21.1.0, @angular/common >= 21.1.0 |
| Dependencies | tslib ^2.3.0 |
| License | Apache-2.0 |
Quick Start
1. Import the module
Add EnergyCapSdkModule to your Angular module with your API key and base URL:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {
EnergyCapSdkModule,
Configuration,
BASE_PATH
} from '@energycap/energycap-sdk-angular';
import { AppComponent } from './app.component';
const sdkConfig = new Configuration({
apiKeys: {
'ECI-ApiKey': 'YOUR_API_KEY'
}
});
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
EnergyCapSdkModule.forConfig(() => sdkConfig)
],
providers: [
{ provide: BASE_PATH, useValue: 'https://app.energycap.com' }
],
bootstrap: [AppComponent]
})
export class AppModule {}
2. Inject a service and make a request
import { Component, OnInit } from '@angular/core';
import { MeterService, MeterResponse } from '@energycap/energycap-sdk-angular';
@Component({
selector: 'app-meters',
template: `
<ul>
<li *ngFor="let meter of meters">
{{ meter.meterId }}: {{ meter.meterCode }} — {{ meter.meterInfo }}
</li>
</ul>
`
})
export class MetersComponent implements OnInit {
meters: MeterResponse[] = [];
constructor(private meterService: MeterService) {}
ngOnInit(): void {
this.meterService.getMeters(undefined, 10, 1).subscribe(meters => {
this.meters = meters;
});
}
}
Configuration
The Configuration class accepts the following options:
| Property | Type | Description |
|---|---|---|
apiKeys |
{ [key: string]: string } |
Header-based API keys. Set 'ECI-ApiKey' for API key auth. |
accessToken |
string | (() => string) |
Bearer token for legacy authentication. Can be a static string or a function that returns a token. |
basePath |
string |
Override the base URL (alternative to using the BASE_PATH injection token). |
username |
string |
Username for legacy credential auth (deprecated). |
password |
string |
Password for legacy credential auth (deprecated). |
withCredentials |
boolean |
Include cookies in cross-origin requests. |
Setting the base URL
You can set the base URL in two ways:
Via the BASE_PATH injection token (recommended):
providers: [
{ provide: BASE_PATH, useValue: 'https://app.energycap.com' }
]
Via the Configuration object:
const sdkConfig = new Configuration({
apiKeys: { 'ECI-ApiKey': 'YOUR_API_KEY' },
basePath: 'https://app.energycap.com'
});
See Environments for the full list of environment URLs.
Authentication
API key (recommended)
Pass your API key in the Configuration object:
const sdkConfig = new Configuration({
apiKeys: {
'ECI-ApiKey': 'YOUR_API_KEY'
}
});
See Authentication for how to create and manage API keys.
Bearer token (legacy)
const sdkConfig = new Configuration({
apiKeys: {
'Authorization': 'Bearer YOUR_TOKEN'
}
});
Or use the AuthenticationService to obtain a token dynamically:
import { AuthenticationService, LoginRequest } from '@energycap/energycap-sdk-angular';
constructor(private authService: AuthenticationService) {}
async authenticate(): Promise<void> {
const request = new LoginRequest();
request.dataSource = 'your_datasource';
request.username = 'your_username';
request.password = 'your_password';
const response = await this.authService.login(request).toPromise();
// Update the configuration with the token
this.sdkConfig.apiKeys['Authorization'] = 'Bearer ' + response.token;
}
Available Services
The SDK provides an injectable service for each API resource. Inject any service into your components or other services via Angular’s dependency injection:
constructor(
private meterService: MeterService,
private billService: BillService,
private accountService: AccountService
) {}
Commonly used services include:
| Service | Description |
|---|---|
AccountService |
Manage accounts |
BatchService |
Manage bill batches |
BillService |
Create, edit, and query bills |
ChannelService |
Manage meter channels |
CommodityService |
Look up commodities |
CostCenterService |
Manage cost center hierarchy |
ImportService |
Import bills and readings |
MeterService |
Create, edit, and query meters |
PlaceService |
Manage places (buildings, sites) |
ReportService |
Run and manage reports |
VendorService |
Manage vendors |
WebhookService |
Manage webhooks |
The full SDK includes 80+ services covering every API endpoint.
Common Operations
Retrieve a single resource
this.meterService.getMeter(1234).subscribe(meter => {
console.log(`${meter.meterCode}: ${meter.meterInfo}`);
});
List resources with filters
// Get all electric accounts
this.accountService.getAccounts("commodityCode equals 'ELECTRIC'").subscribe(accounts => {
accounts.forEach(a => console.log(`${a.accountId}: ${a.accountCode}`));
});
See Filters for the full filter syntax.
Create a resource
import { AccountCreate } from '@energycap/energycap-sdk-angular';
const newAccount = new AccountCreate();
newAccount.accountCode = 'ACCT-NEW-001';
newAccount.accountInfo = 'New Office Account';
newAccount.vendorId = 10;
newAccount.accountTypeId = 1;
this.accountService.createAccount(newAccount).subscribe(account => {
console.log(`Created account ${account.accountId}`);
});
Update a resource
import { AccountEdit } from '@energycap/energycap-sdk-angular';
const update = new AccountEdit();
update.accountCode = 'ACCT-001-UPDATED';
update.accountInfo = 'Updated Account Description';
this.accountService.editAccount(1234, update).subscribe(account => {
console.log(`Updated account ${account.accountId}`);
});
Delete a resource
this.meterService.deleteMeter(1234).subscribe(() => {
console.log('Meter deleted');
});
Pagination
List methods accept optional filter, pageSize, and pageNumber parameters:
// getMeters(filter?, pageSize?, pageNumber?)
this.meterService.getMeters(undefined, 500, 1).subscribe(meters => {
console.log(`Page 1: ${meters.length} meters`);
});
Iterating through all pages
Since the SDK returns Observable<Array<T>> without pagination headers, use the extraHttpRequestParams to access the raw response and read headers:
import { HttpClient, HttpResponse } from '@angular/common/http';
async getAllMeters(): Promise<MeterResponse[]> {
const allMeters: MeterResponse[] = [];
const pageSize = 500;
let page = 1;
let totalPages = 1;
do {
const meters = await this.meterService
.getMeters(undefined, pageSize, page)
.toPromise();
allMeters.push(...meters);
// If fewer results than pageSize, we've reached the last page
if (meters.length < pageSize) {
break;
}
page++;
} while (page <= totalPages);
return allMeters;
}
See Pagination for more details on pagination behavior.
Field Reduction
Reduce response size by passing the field parameter via extraHttpRequestParams:
this.meterService.getMeters(
undefined, // filter
100, // pageSize
1, // pageNumber
{ search: 'field=meterId,meterCode,meterInfo' }
).subscribe(meters => {
// Each meter only contains meterId, meterCode, and meterInfo
});
See Field Reduction for include/exclude modes.
Error Handling
Service methods return Observables, so handle errors with RxJS:
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
this.meterService.getMeter(99999).pipe(
catchError(error => {
console.error(`Status: ${error.status}`);
console.error(`Body: ${error.error}`);
// Common status codes:
// 400 — Bad request (check your parameters)
// 401 — Unauthorized (invalid API key)
// 404 — Resource not found
// 429 — Rate limited (wait and retry)
return of(null);
})
).subscribe(meter => {
if (meter) {
console.log(meter.meterCode);
}
});
Retry with delay on rate limit
import { retry, catchError, delay } from 'rxjs/operators';
import { throwError, timer } from 'rxjs';
import { retryWhen, mergeMap } from 'rxjs/operators';
this.meterService.getMeters().pipe(
retryWhen(errors =>
errors.pipe(
mergeMap((error, attempt) => {
if (error.status === 429 && attempt < 3) {
console.log(`Rate limited — retrying in 10 seconds (attempt ${attempt + 1})`);
return timer(10000);
}
return throwError(() => error);
})
)
)
).subscribe(meters => {
console.log(`Retrieved ${meters.length} meters`);
});
Standalone Components (Angular 14+)
If you’re using standalone components instead of NgModules, provide the SDK configuration at the application level:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { BASE_PATH, Configuration, MeterService } from '@energycap/energycap-sdk-angular';
import { AppComponent } from './app.component';
const sdkConfig = new Configuration({
apiKeys: { 'ECI-ApiKey': 'YOUR_API_KEY' }
});
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(),
{ provide: BASE_PATH, useValue: 'https://app.energycap.com' },
{ provide: Configuration, useValue: sdkConfig },
MeterService,
// ... other services you need
]
});
Environment-Based Configuration
Use Angular’s environment files to switch between environments:
// environments/environment.ts (development)
export const environment = {
production: false,
energyCapBaseUrl: 'https://implement.energycap.com',
energyCapApiKey: 'YOUR_DEV_API_KEY'
};
// environments/environment.prod.ts (production)
export const environment = {
production: true,
energyCapBaseUrl: 'https://app.energycap.com',
energyCapApiKey: 'YOUR_PROD_API_KEY'
};
import { environment } from '../environments/environment';
const sdkConfig = new Configuration({
apiKeys: { 'ECI-ApiKey': environment.energyCapApiKey }
});
@NgModule({
imports: [
BrowserModule,
EnergyCapSdkModule.forConfig(() => sdkConfig)
],
providers: [
{ provide: BASE_PATH, useValue: environment.energyCapBaseUrl }
],
bootstrap: [AppComponent]
})
export class AppModule {}