Exploring the Carbon Intensity Public API with JavaScript

The Carbon Intensity Public API is an open-access API that provides information about the carbon intensity of electricity generation in Great Britain. This API allows developers to obtain valuable data on the mix of electricity generation sources, including renewable energy and fossil fuels, and their respective carbon emissions.

In this blog post, we will explore how to use the Carbon Intensity Public API with JavaScript, including examples of how to access the API and display the data.

Getting Started

Firstly, we need to obtain an API key from Carbon Intensity Public API website. Once you have an API key, we can start by sending an HTTP GET request to the Carbon Intensity Public API endpoint.

const endpoint = 'https://api.carbonintensity.org.uk/intensity';
const API_KEY = 'YOUR-API-KEY';

fetch(`${endpoint}?key=${API_KEY}`)
    .then(response => response.json())
    .then(data => console.log(data));

This will send a GET request to the Carbon Intensity Public API endpoint and return a JSON object containing the carbon intensity data.

Displaying Data

Now that we have successfully obtained the data from the API endpoint, we can display the data in a more user-friendly way. Let's retrieve the data for the current half-hour period and display it in the console.

const getCurrentIntensity = () => {
    const endpoint = 'https://api.carbonintensity.org.uk/intensity';
    const API_KEY = 'YOUR-API-KEY';

    fetch(`${endpoint}?key=${API_KEY}`)
        .then(response => response.json())
        .then(data => {
            const currentIntensity = data.data[0].intensity.actual;
            console.log(`The current carbon intensity is ${currentIntensity} gCO2/kWh.`);
        })
        .catch(error => console.log(error));
};

getCurrentIntensity();

This code will send a GET request to the Carbon Intensity Public API endpoint and retrieve the carbon intensity data for the current half-hour period.

We access the actual carbon intensity value from the data object using the data[0].intensity.actual property. Then, we display this data in the console using a template literal.

Conclusion

The Carbon Intensity Public API is a valuable resource for developers looking to obtain real-time data on the carbon intensity of electricity generation in Great Britain. By making a few simple HTTP requests using JavaScript, we were able to obtain and display this data in a user-friendly way.

Happy coding!

Related APIs