Making API Calls in Other Programming Languages

This topic will demonstrate how to make API calls using the PurpleAir API in different programming languages. The request that each example will be completing is the Get Sensor Data request. If you would like to learn the basics of making an API call using the PurpleAir API, reference this topic.


Python Example

The following example will show an API call made using Python. I’ve used a library named Requests which would have to be installed and imported in order for this function to work properly. You can view the documentation for Requests to learn more.

import requests

# Here we store our API read key in a string variable that we can reference later.
my_api_read_key = '********-****-****-****-************'

# This function will be used to collect data for a specific and public PurpleAir sensor.
def getSensorData(sensor_index):

    # my_url is assigned the URL we are going to send our request to.
    my_url = 'https://api.purpleair.com/v1/sensors/' + str(sensor_index)

    # my_headers is assigned the context of our request we want to make. In this case
    # we will pass through our API read key using the variable created above.
    my_headers = {'X-API-Key':my_api_read_key}

    # my_params is assigned a list of fields of data we are requesting. Excluding the
    # fields parameter will collect all available fields. In this example, we ask for the
    # temperature and the PM2.5 ATM average.
    my_params = {'fields':'temperature,pm2.5_atm'}

    # This line creates and sends the request and then assigns its response to the
    # variable, r.
    r = requests.get(my_url, headers=my_headers, params=my_params)

    # We then return the response we received.
    return r

Here we can see a function named getSensorData. When run, this function will send a request to collect data from an individual, public sensor and return that data. One of the first things we can see is that it requires a parameter named sensor_index. This is the unique 4-6 digit code that each PurpleAir sensor on the map is assigned.

The next two variables we see create the two necessary parts of our request; the request line and the header. The variable, my_url is assigned the URL that we are going to send our request to and at the end we make sure to append the sensor index of the sensor we want to collect data from. The my_headers variable is assigned the context of our request we are making. All we would need to include here is our API read key.

The next variable we see named my_params holds parameters we can send with our request. For the getSensorData request, this is not required unless you want to collect only specific fields. Inside of this variable, we specify a key named fields and a string value for it. The value will be a comma separated list of fields we want to request.

After the variables are created, we use a function from the Requests library named requests.get() and assign its response to a variable, r. We then pass in the two variables we created earlier; my_url and my_headers. Pass in the my_params variable if you are using it. Finally, we return the variable r.

JavaScript Example Using Fetch

This example will show the Get Sensor Data request written in JavaScript using the Fetch API. You can find documentation for the fetch API at Mozilla’s Developer Page.

my_api_read_key = '********-****-****-****-************'

function getSensorData(sensor_index) {
    // my_url is assigned the URL we are going to send our request to.
    let my_url = 'https://api.purpleair.com/v1/sensors/' + sensor_index.toString();

    // We use the Fetch API to send our request and return the response.
    fetch (my_url, {
        headers: {
            'X-API-KEY': my_api_read_key
        }
    })
    .then(response => response.json());
    .then(data => console.log(data));
}

Here we create a function named getSensorData. This function requires a sensor index to be passed in as a parameter. This would be the unique 4-6 digit code of the sensor we want to collect data from.

We create a variable named my_url that will create the URL for our request using the sensor_index parameter we pass in.

After the URL has been created, we use the fetch() function to make our API call. We input the my_url variable as the first parameter, and then we input other necessary information for our request in the second parameter. In this instance, all we need to send is a header including the my_api_read_key variable.

Fetch returns a Promise from the response to our request. Because of this, we will use .then() as we have to wait until a response is received. In this statement, we take the response we got from the server and parse it using .json(). Then we take that data and log it to the console.

JavaScript Example Using an XMLHttpRequest Object

This example will show the Get Sensor Data request written in JavaScript using an XMLHttpRequest object. You can find documentation for XMLHttpRequest objects at Mozilla’s Developer Page.

// Here we store our API read key in a string variable that we can reference later.
my_api_read_key = '********-****-****-****-************'

// This function will be used to collect data for a specific and public PurpleAir sensor.
function getSensorData(sensor_index) {

    // Here we initialize a new XMLHttpRequest object and we assign it to a variable, http.
    let http = new XMLHttpRequest();

    // my_url is assigned the URL we are going to send our request to.
    let my_url = 'https://api.purpleair.com/v1/sensors/' + sensor_index.toString();

    // Here we initialize a request and pass in our request line in two separate parameters,
    // one being the request method and the other being the URL.
    http.open("GET", my_url);

    // Here we use the setRequestHeader method set the header of our request. We will
    // use our API Read Key, stored in a string variable named myAPIReadKey.
    http.setRequestHeader("X-API-KEY", my_api_read_key);

    // Now that our request has been initialized and put together, we can send it using this
    // send method.
    http.send();

    // The onreadystatechange method will be called whenever the state of the request is
    // changed. The state of the request is stored in a variable named readyState. We
    // use it here to detect whether or not the request was successful, and to collect any
    // data it may have brought back. We return that data by checking the response of
    // our http variable.
    http.onreadystatechange = (e) => {
        return http.response;
    }
}

For this request we’ve again created a function named getSensorData. This function requires a sensor index to be passed in as a parameter. This would be the unique 4-6 digit code of the sensor we want to collect data from.

The next variable you see that’s been created, http, will hold the XMLHttpRequest object that we will use to make our request.

The variable, my_url, just like the last request, is assigned the URL that we are going to send our request to. At the end we make sure to include the sensor index of the sensor we want to collect data from.

Now that we have declared our variables the next step is to initialize our request. This is done by calling the method open() on our XMLHttpRequest object. Inside of the parameters we will first pass through "GET", since we are collecting a data entry, and second we will pass through the my_url variable.

To add headers to an XMLHttpRequest object we will use the setRequestHeader() method. For the Get Sensor Data request we will only need to pass in our API read key.

With the headers added to our object we are now ready to send it. We do this by calling send() on our XMLHttpRequest object.

To get the response that was assigned to our request we will access it through http.response and have our getSensorData function return that. However, before we do that I’ve added http.onreadystatechange. This is called whenever the state of the request is changed. We use onreadystatechange to make sure we wait until the response is received before we try to collect it. I have not included any error handling in this example, but this is most likely the spot where you would want to include that.


If you want to use the PurpleAir API and do not have API keys, you can create your own API keys here: PurpleAir Develop.

You will need a Gmail or Gmail associated account to sign in. You can learn more information here: Sign in to your Google Account with another email address - Computer - Google Account Help.

Learn more about creating and managing API keys here: Creating API Keys

1 Like