Headshot of Christine George, who is smiling, wears glasses, has shoulder length black hair. She is wearing a striped black shirt.
Christine George
Apr 9, 20253 min read

How to use client libraries with the Residential Electrification Model API

Client libraries offer a shortcut for pulling data on how much households can save by switching to electric appliances.

Over the past two years, Rewiring America has been assembling data and designing models around the benefits of electrification. But we don’t want to keep all of this exciting work to ourselves. So we’ve decided to share it with the world through our API.

This post is part five of a series of articles illustrating how you can incorporate the Rewiring America API into your website, research, and more.

In this installment, we’ll show you how to use client libraries to cut down on your coding time and access the Residential Electrification Model (REM) API directly from your existing Python or TypeScript code. If you’re wondering if you need to create the client libraries yourself, then we have good news for you — we've already published two that are ready for you to use!

What is a client library?

For those who haven’t used one before, a client library is a collection of pre-written code that makes calling an API simpler by cutting down on the amount of code you need to write from scratch. That might mean instead of writing 100 lines of code to pull the data you want, you could integrate our client libraries, and only have to write 30. These libraries are accessible through packages that you can easily import into your code.

Rewiring America has published two client libraries for our APIs so far: Supporting those working in Python and TypeScript. You can easily find and install these packages in the PyPi (for Python) and npm (for TypeScript) package repositories. Keep reading for a quick tutorial on how to use each of them.

Getting started in Python

This section will illustrate a simple example of getting the average annual cost savings of upgrading to a heat pump using the Python client library. All steps in this example come from this example Python script that you can use to get up and running quickly. 

As a first step, install the package for the REM Python library:

pip install rewiringamerica-rem

Then, import the package into your script:

import rewiringamerica_rem

The next section sets up your API key to allow you to make authorized requests. This configuration simplifies the need to manually set an Authorization header like you would need to when using the Python requests library:

configuration = rewiringamerica_rem.Configuration(
    access_token = "INSERT_YOUR_API_KEY_HERE"
)

Make sure to replace “INSERT_YOUR_API_KEY_HERE” with your actual key value. If you don’t have one, you can acquire a key to access all of Rewiring America’s APIs here — just sign up for a free account. (P.S.: Check out the post on protecting your API key to keep it secure!)

After this, the script sets up an instance of the API class and the parameters that you need to pass in to make a request. Rather than having to configure the URL structure yourself and troubleshoot parameter formatting, the client library turns these into classes with set values that you can easily access through dot notation:

with rewiringamerica_rem.ApiClient(configuration) as api_client:
    api_instance = rewiringamerica_rem.ResidentialElectrificationModelApi(api_client)
    upgrade = rewiringamerica_rem.SupportedUpgrade.HVAC__HEAT_PUMP_SEER15_HSPF9
    address = "INSERT_YOUR_ADDRESS_HERE"
    heating_fuel = rewiringamerica_rem.HeatingFuel.NATURAL_GAS

Make sure to replace “INSERT_YOUR_ADDRESS_HERE” with your desired address. Feel free to modify the upgrade and heating_fuel values as well. Documentation is included with the client library, so IDEs like VSCode should recognize it and display descriptions in the application itself. Otherwise, you can reference the official API documentation to learn more about the upgrades and heating fuels the API supports.

The try and except blocks, which you see at the end, send off your parameters to make a request to the API server side:

try:
    api_response = api_instance.get_by_address(upgrade, address, heating_fuel)
    totals = api_response.fuel_results["total"]
    cost_savings = round(-(totals.delta.cost.mean.value))
    print(f"I could save ${cost_savings} annually with this home upgrade!")
except Exception as e:
        print("Exception when calling get_by_address: %s\n" % e)

If any exceptions come up, they’ll be caught and printed out by the except block. Otherwise, you’ll see output that looks something like:

I could save $X annually with this home upgrade!

This value, which is the average change in total annual cost, is extracted from the Savings object that the API returns after a successful request. While this is what’s defined in the example script, there’s a whole lot more information available in the object. That includes statistics about each fuel type, a summary of the rates used to calculate annual cost, and a summary of emissions factors to calculate annual emissions. 

You can read more about the statistical values we return and the methodology we use to calculate them in the official API documentation.

Getting started in TypeScript

This section will illustrate the same process shown above, but now geared towards those who work in TypeScript. This example script showcases all the similar steps we take in this other programming language.

First, install the package for the REM TypeScript library:

npm install @rewiringamerica/rem

At the top of the file, add this list of imports:

import { ResidentialElectrificationModelApi } from "@rewiringamerica/rem/api/apis";
import { SupportedUpgrade } from "@rewiringamerica/rem/model/supportedUpgrade";
import { HeatingFuel } from "@rewiringamerica/rem/model/heatingFuel";
import { HttpBearerAuth } from "@rewiringamerica/rem/model/models";

These are all the necessary dependencies used in the script.

The next section sets up the API key needed for authorized requests to the API:

const key = new HttpBearerAuth();
key.accessToken = "INSERT_YOUR_API_KEY_HERE";

Similarly to the Python example, replace “INSERT_YOUR_API_KEY_HERE” with your own API key. This key gets added to the initialized API client in the next code snippet:

const remApi = new ResidentialElectrificationModelApi();
remApi.setDefaultAuthentication(key);

After this, we set up an async function to call the REM API address endpoint:

async function getRemByAddress(
  upgrade: SupportedUpgrade,
  address: string,
  heatingFuel: HeatingFuel
) {
  try {
    const apiResponse = await remApi.getByAddress(
      upgrade,
      address,
      heatingFuel
    );
    const totals = apiResponse.body.fuelResults.total;
    const costSavings = Math.round(-(totals.delta.cost.mean.value));
    console.log(
      `I could save $${costSavings} annually with this home upgrade!`
    );
  } catch (error) {
    console.error("Error:", error.response.body);
  }
}

Like the Python script, this function extracts the average change in total annual cost from the Savings object and displays it at the end of the script’s execution.

Outside of the async function, change the INSERT_YOUR_ADDRESS_HERE string to be one that you want to determine savings for (and the upgrade and heating fuel types, if you’d like):

const upgrade = SupportedUpgrade.HvacHeatPumpSeer15Hspf9;
const address = "INSERT_YOUR_ADDRESS_HERE";
const heatingFuel = HeatingFuel.NaturalGas;

Finally, the last line of the script calls the async function to hit the REM API:

getRemByAddress(upgrade, address, heatingFuel);

If there are no exceptions, this will result in an output just like the Python script:

I could save $X annually with this home upgrade!

How we built our client libraries

We used the FastAPI framework to build the REM API, which automatically generates an OpenAPI Specification file. This specification file includes details about different endpoints, authentication methods, response formats, documentation, and more. This file also defines the structure of a RESTful API in a standardized format. Essentially, this file is a blueprint that we can use to create client libraries in any programming language, which opens the door to us supporting more coding languages as needed.

We then used OpenAPI Generator, an open source project that automatically generates client libraries based on the information from the specification file. This generation tool greatly reduces the amount of time and manual coding effort needed to create and maintain client libraries for our API.

Conclusions

Client libraries offer a helpful shortcut to call the Rewiring America Residential Electrification Model (REM) API and see how the benefits of electrification can apply to your own home.

If you have questions, comments, or suggestions, or if you find a bug in any of the code above, please start a discussion or open an issue in the api_demos GitHub repository. You can also find additional examples of how to use the Rewiring America API in that project.