Skip to content

A .NET Rest client for the Tomorrow electricity map API using C# and .NET Core ⚡ Understand and optimize the carbon footprint of electricity.

License

Notifications You must be signed in to change notification settings

kristofferandreasen/tomorrow-electricity-api-dotnet-client

Repository files navigation

⚡ Tomorrow Electricity Map API C# .NET Rest Client ⚡

This API wrapper is built to make it easier to use the ELectricity Map API from Tomorrow. It provides a simple interface to understand and optimize the carbon footprint of electricity.

A C# .NET Core REST client for the ElectricityMap API. Built with ❤︎ by Kristoffer Andreasen

Installation

You need to install the NuGet Package to use the library. You can use on of the following ways are install it through Visual Studio.

Install with Package Manager

Install-Package ElectricityMap.DotNet.Client

Install with .NET CLI

dotnet add package ElectricityMap.DotNet.Client

Available Methods

There is one method available for each of the endpoints provided by the Electricity Map API. The following table will show you all of them. Check the full API docs for more information on the endpoints. Most of the endpoints take a zone or latitude/longitude as parameters. You can find all the available zones in the ZoneConstants class. Be aware API keys are typically limited to specific zones.

Method Description
GetAvailableZonesAsync Get the available zones for your API Key.
GetLiveCarbonIntensityAsync Data on the live carbon intensity.
GetLivePowerBreakdownAsync Live breakdown of the power usage.
GetRecentCarbonIntensityHistoryAsync Get data for recent carbon intensity measurements.
GetRecentPowerBreakdownHistoryAsync Get data for recent power breakdown measurements.
GetPastCarbonIntensityHistoryAsync Get data for past carbon intensity measurements.
GetPastPowerBreakdownHistoryAsync Get data for past power breakdown measurements.
GetForecastedCarbonIntensityAsync Get data for forecasted carbon intensity measurements.
GetForecastedPowerConsumptionBreakdownAsync Get data for forecasted power breakdown measurements.
GetForecastedMarginalCarbonIntensityAsync Get data for forecasted marginal carbon intensity measurements.
GetForecastedMarginalPowerConsumptionBreakdownAsync Get data for forecasted marginal power breakdown measurements.
GetUpdateInfoAsync Get data for API update history.

Using the package

The easiest way to use the library is by using dependency injection. In the following sections you can see the easiest ways to use the library.

Dependency Injection: .NET Core Web Application

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();

    // Register the electricity map client for dependency injection
    string electricityMapApiKey = Configuration.GetValue<string>("ElectricityMap:ApiKey");
    services.AddElectricityMapClient(electricityMapApiKey);
}
namespace RazorPages.Example.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly IElectricityMapClient _electricityMapClient;

        public IndexModel(
            ILogger<IndexModel> logger,
            IElectricityMapClient electricityMapClient
        )
        {
            _logger = logger;
            _electricityMapClient = electricityMapClient;
        }

        public LiveCarbonIntentsity CarbonIntensity { get; set; }

        public async Task OnGet()
        {
            CarbonIntensity = await _electricityMapClient.GetLiveCarbonIntensityAsync(ZoneConstants.Denmark_East_Denmark);
        }
    }
}

Dependency Injection: Azure Function

The pattern for using dependency injection in an Azure Function is similar to a web application.

  • Create a startup.cs file to enable dependency injection
  • Register the ElectricityMapClient interface in the startup file
  • Inject the service in the class where you want to use it
  • See full example in Example folder

Startup.cs file

[assembly: FunctionsStartup(typeof(Azure.Function.Example.Startup))]
namespace Azure.Function.Example
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddHttpClient();
            builder.Services.AddLogging();

            // Register the electricity map client with your api key
            string electricityMapApiKey = Environment.GetEnvironmentVariable("ElectricityMapApiKey");
            builder.Services.AddElectricityMapClient(electricityMapApiKey);
        }
    }
}

GetCarbonIntensity.cs file

public class GetCarbonIntensityFunction
{
    private readonly IElectricityMapClient _electricityMapClient;

    public GetCarbonIntensityFunction(IElectricityMapClient electricityMapClient)
    {
        _electricityMapClient = electricityMapClient;
    }

    [FunctionName(nameof(GetCarbonIntensityFunction))]
    public  async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string zone = req.Query["zone"];

        var carbonIntensity = await _electricityMapClient.GetLiveCarbonIntensityAsync(zone);

        return carbonIntensity != null
            ? (ActionResult)new OkObjectResult(carbonIntensity)
            : new BadRequestObjectResult("Please pass a url on the query string or in the request body");
    }
}

Developing

The project is developed as a .NET Core Class Library. The current framework version used is .NET Core 3.1.

To start developing, you need to clone the repo on your local workstation.

Restore Dependencies

dotnet restore

Run Project

dotnet run

Test Project

The project is using XUnit for testing.

dotnet test

This will start up the development server allowing you to see the results. Be aware that the solution is setting a cookie and this cookie will be stored in your browser. In order to see the banner again, you will need to open the localhost link in incognito or clear your browser cookies.

Contributing

Your contributions are always welcome! Please have a look at the contribution guidelines first 🎉

License

MIT © kristofferandreasen

About

A .NET Rest client for the Tomorrow electricity map API using C# and .NET Core ⚡ Understand and optimize the carbon footprint of electricity.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages