How to use cookies in backend API calls

cookie sample
Photo by Vyshnavi Bisani on Unsplash

There may be some websites whose APIs you may want to call programmatically (maybe for automating some stuff or setting a cron job). Now, the server may be requiring a cookie in the request header (perhaps to verify your identity and subsequently service your API request). If you don’t provide it, it may simply redirect you to the login page. Getting the 302 redirect status code, and the “Object moved to here” response is a good indication of a missing cookie.

When accessing the API in a normal browser, the cookie gets stored in your browser session as soon as you log in to the website, and is sent in the header in each subsequent API call. How do you set the cookie when calling the API programmatically? Here’s something you can try. It depends on the ability to successfully call the login API.

First, call the login API with your credentials. If the login is successful, it will reply back with a ‘set-cookie’ header. Extract the value of that header and store it. In every subsequent API call, you can add this value in the ‘Cookie’ header. That’s it, you can now access the website APIs programmatically.

Here’s an example of getting the cookie in nodejs (assuming the login API URL is example.com/login)

const https = require('https');

let cookie = "";
let bodyString = 'username=abcd&password=1234'

let options = {
    hostname: 'example.com',
    port: 443,
    path: '\login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': bodyString.length
    }
};

let result = '';
const req = https.request(options, res => {
    console.log(`statusCode: ${res.statusCode}`)
    status_code = res.statusCode;
    console.log(res.headers);
    cookie = res.headers['set-cookie']

    res.on('data', function (chunk) {
        result += chunk;
    });
    res.on('end', async function () {
        console.log(result);
    });
    res.on('error', function (err) {
        console.log(err);
    })
})

req.on('error', error => {
    console.log(error)
})

req.write(bodyString)

Once the cookie is received, add it to subsequent API calls by adding the extra ‘Cookie’ header in the request. Example:

let options = {
        hostname: 'example.com',
        port: 443,
        path: 'mydata',
        method: 'GET',
        headers: {
            'Cookie':cookie.toString()
        }
    };

That’s it. Hope you found this helpful.


Check out further posts on iotespresso.com.

Leave a comment

Your email address will not be published. Required fields are marked *