Skip to main content

Amber

Struct Amber 

Source
pub struct Amber { /* private fields */ }
Expand description

Main client for the Amber Electric API.

This client provides a high-level interface to all Amber Electric API endpoints with automatic retry logic for rate limit errors.

Internally, it uses reqwest as the HTTP client, which is stored behind an Arc and can be cloned cheaply.

§Rate Limit Handling

By default, the client automatically retries requests that hit rate limits (HTTP 429). The client reads the RateLimit-Reset header to determine how long to wait before retrying. By default, up to 3 retry attempts will be made. You can configure this behavior:

use amber_api::Amber;

// Disable automatic retries
let client = Amber::builder()
    .retry_on_rate_limit(false)
    .build();

// Customize max retry attempts (default: 3)
let client = Amber::builder()
    .max_retries(5)
    .build();

When rate limit retries are disabled or exhausted, the client returns an error containing the suggested retry-after duration.

§Examples

use amber_api::Amber;

// Create a client with default retry behavior (3 retries, enabled)
let client = Amber::default();

Implementations§

Source§

impl Amber

Source

pub fn builder() -> AmberBuilder

Create an instance of Amber using the builder syntax

Source§

impl Amber

Source

pub async fn sites(&self) -> Result<Vec<Site>>

Return all sites linked to your account.

This method returns information about all electricity sites associated with your Amber account. Each site represents a location where you have electricity service.

§Authentication

This method requires authentication via API key. The API key can be provided either through the AMBER_API_KEY environment variable (when using Amber::default()) or by explicitly setting it when building the client.

§Returns

Returns a Result containing a Vec of Site objects on success.

§Errors

This method will return an error if:

  • The API key is missing or invalid (HTTP 401)
  • There’s a network error communicating with the API
  • The API returns an internal server error (HTTP 500)
§Example
use amber_api::Amber;

let client = Amber::default();
let sites = client.sites()?;

for site in sites {
    println!("Site {}: {} ({})", site.id, site.network, site.status);
}
Source

pub fn current_renewables<'f1>(&'f1 self) -> AmberCurrentRenewablesBuilder<'f1>

Returns the current percentage of renewables in the grid for a specific state.

This method retrieves renewable energy data for the specified Australian state. The data shows the current percentage of renewable energy in the grid and can optionally include historical and forecast data.

§Parameters
  • state: The Australian state (NSW, VIC, QLD, SA)
  • next: Optional number of forecast intervals to return
  • previous: Optional number of historical intervals to return
  • resolution: Optional interval duration (5 or 30 minutes, default 30)
§Authentication

This endpoint does not require authentication and can be called without an API key.

§Returns

Returns a Result containing a Vec of Renewable objects on success.

§Errors

This method will return an error if:

  • There’s a network error communicating with the API
  • The API returns an internal server error (HTTP 500)
§Example
use amber_api::Amber;
use amber_api::models::{State, Resolution};

let client = Amber::default();

// Get current renewables data for Victoria
let renewables = client.current_renewables()
    .state(State::Vic)
    .call()?;

for renewable in renewables {
    println!("{}", renewable);
}

// Get current data with 8 forecast intervals
let renewables_with_forecast = client.current_renewables()
    .state(State::Nsw)
    .next(8)
    .resolution(Resolution::FiveMinute)
    .call()?;
Source

pub fn prices<'f1, 'f2>(&'f1 self) -> AmberPricesBuilder<'f1, 'f2>

Returns all the prices between the start and end dates for a specific site.

This method retrieves historical pricing data for the specified site between the given date range. The date range cannot exceed 7 days.

§Parameters
  • site_id: ID of the site you are fetching prices for (obtained from sites())
  • start_date: Optional start date for the price range (defaults to today)
  • end_date: Optional end date for the price range (defaults to today)
  • resolution: Optional interval duration (5 or 30 minutes, defaults to your billing interval)
§Authentication

This method requires authentication via API key. The API key can be provided either through the AMBER_API_KEY environment variable (when using Amber::default()) or by explicitly setting it when building the client.

§Returns

Returns a Result containing a Vec of Interval objects on success. Intervals are returned in order: General > Controlled Load > Feed In.

§Errors

This method will return an error if:

  • The API key is missing or invalid (HTTP 401)
  • The site ID is invalid (HTTP 400)
  • The site is not found (HTTP 404)
  • The date range exceeds 7 days (HTTP 422)
  • There’s a network error communicating with the API
  • The API returns an internal server error (HTTP 500)
§Example
use std::str::FromStr;

use amber_api::Amber;
use amber_api::models::Resolution;
use jiff::civil::Date;

let client = Amber::default();
let sites = client.sites()?;
let site_id = &sites[0].id;

// Get prices for today
let prices = client.prices()
    .site_id(site_id)
    .call()?;

// Get prices for a specific date range
let start_date = Date::from_str("2021-05-01").expect("Invalid start date");
let end_date = Date::from_str("2021-05-03").expect("Invalid end date");
let prices = client.prices()
    .site_id(site_id)
    .start_date(start_date)
    .end_date(end_date)
    .resolution(Resolution::FiveMinute)
    .call()?;

for interval in prices {
    match interval {
        amber_api::models::Interval::ActualInterval(actual) => {
            println!("Actual price: {:.2}c/kWh", actual.base.per_kwh);
        }
        _ => {} // Handle other interval types as needed
    }
}
Source

pub fn current_prices<'f1, 'f2>( &'f1 self, ) -> AmberCurrentPricesBuilder<'f1, 'f2>

Returns the current price for a specific site.

This method retrieves the current pricing data for the specified site, optionally including historical and forecast data.

§Parameters
  • site_id: ID of the site you are fetching prices for (obtained from sites())
  • next: Optional number of forecast intervals to return (max 2048 total)
  • previous: Optional number of historical intervals to return (max 2048 total)
  • resolution: Optional interval duration (5 or 30 minutes, defaults to your billing interval)
§Authentication

This method requires authentication via API key. The API key can be provided either through the AMBER_API_KEY environment variable (when using Amber::default()) or by explicitly setting it when building the client.

§Returns

Returns a Result containing a Vec of Interval objects on success. Intervals are returned in order: General > Controlled Load > Feed In.

§Errors

This method will return an error if:

  • The API key is missing or invalid (HTTP 401)
  • The site ID is invalid (HTTP 400)
  • The site is not found (HTTP 404)
  • The total number of intervals exceeds 2048 (HTTP 422)
  • There’s a network error communicating with the API
  • The API returns an internal server error (HTTP 500)
§Example
use amber_api::Amber;
use amber_api::models::Resolution;

let client = Amber::default();
let sites = client.sites()?;
let site_id = &sites[0].id;

// Get current prices only
let current_prices = client.current_prices()
    .site_id(site_id)
    .call()?;

// Get current prices with forecast
let prices_with_forecast = client.current_prices()
    .site_id(site_id)
    .next(8)
    .resolution(Resolution::ThirtyMinute)
    .call()?;

// Get current prices with history and forecast
let full_prices = client.current_prices()
    .site_id(site_id)
    .previous(8)
    .next(8)
    .call()?;

for interval in current_prices {
    match interval {
        amber_api::models::Interval::CurrentInterval(current) => {
            println!("Current price: {:.2}c/kWh (estimate: {})",
                     current.base.per_kwh, current.estimate);
        }
        _ => {} // Handle other interval types as needed
    }
}
Source

pub fn usage<'f1, 'f2>(&'f1 self) -> AmberUsageBuilder<'f1, 'f2>

Returns all usage data between the start and end dates for a specific site.

This method retrieves historical usage data for the specified site between the given date range. The date range cannot exceed 7 days, and the API can only return 90 days worth of data.

§Parameters
  • site_id: ID of the site you are fetching usage for (obtained from sites())
  • start_date: Start date for the usage data (required)
  • end_date: End date for the usage data (required)
  • resolution: Optional interval duration (deprecated, will be ignored)
§Authentication

This method requires authentication via API key. The API key can be provided either through the AMBER_API_KEY environment variable (when using Amber::default()) or by explicitly setting it when building the client.

§Returns

Returns a Result containing a Vec of Usage objects on success. Usage data is returned in order: General > Controlled Load > Feed In.

§Errors

This method will return an error if:

  • The API key is missing or invalid (HTTP 401)
  • The site ID is invalid (HTTP 400)
  • The site is not found (HTTP 404)
  • The date range exceeds 7 days (HTTP 422)
  • There’s a network error communicating with the API
  • The API returns an internal server error (HTTP 500)
§Example
use std::str::FromStr;

use amber_api::Amber;
use jiff::civil::Date;

let client = Amber::default();
let sites = client.sites()?;
let site_id = &sites[0].id;

// Get usage data for a specific date range
let start_date = Date::from_str("2021-05-01").expect("Invalid start date");
let end_date = Date::from_str("2021-05-03").expect("Invalid end date");
let usage_data = client.usage()
    .site_id(site_id)
    .start_date(start_date)
    .end_date(end_date)
    .call()?;

for usage in usage_data {
    println!("Channel {}: {:.2} kWh, Cost: ${:.2}",
             usage.channel_identifier, usage.kwh, usage.cost);
}

Trait Implementations§

Source§

impl Clone for Amber

Source§

fn clone(&self) -> Amber

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Amber

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Amber

Source§

fn default() -> Self

Create a new default Amber API client.

This create a default client that is authenticated if an API key is set in the AMBER_API_KEY environment variable.

The default client has automatic rate limit retry enabled with up to 3 retry attempts.

Auto Trait Implementations§

§

impl Freeze for Amber

§

impl !RefUnwindSafe for Amber

§

impl Send for Amber

§

impl Sync for Amber

§

impl Unpin for Amber

§

impl !UnwindSafe for Amber

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more