How to Test Sendgrid api key is valid or not Without sending emails?

Viewed 2761

I am using sendgrid api-keys to send bulk emails, and i want to test the it is an valid api-key or not. Is there any function to test the api-key in nodejs.

1 Answers

There is an endpoint to retrieve the scopes enabled for the given key at GET https://api.sendgrid.com/v3/scopes. Every valid key seems to work here, with 401 for invalid keys. Additionally it returns the scopes so you can check the api key is valid for the application, so for sending mail it should contain mail.send.

Example pulled from their docs (search for "scope"):

var http = require("https");

var options = {
  "method": "GET",
  "hostname": "api.sendgrid.com",
  "port": null,
  "path": "/v3/scopes",
  "headers": {
    "on-behalf-of": "The subuser's username. This header generates the API call as if the subuser account was making the call",
    "authorization": "Bearer <<YOUR_API_KEY_HERE>>"
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.write("{}");
req.end();
Related