Navigation

HTTP Integration with SendGrid

This tutorial provides step-by-step instructions for creating a simple MongoDB Stitch app which allows you to send an email message using a web form. It illustrates several key MongoDB Stitch features: integration with an external API through the HTTP service, setting up rules for the HTTP service, and storing named constants in your app’s values.

SendGrid is an email service with an API you can access with HTTP requests. To complete this tutorial, you’ll need:

  • a SendGrid developer API key
  • an email address you have access to

Procedure

A. Create a MongoDB Stitch App

Estimated Time to Complete: ~8 minutes

1

Log into Atlas.

To use MongoDB Stitch, you must be logged into MongoDB Atlas. If you do not have an Atlas account, follow the instructions in the Atlas documentation to create an account.

2

Create an Atlas cluster.

If you do not already have an Atlas cluster for use with MongoDB Stitch, create a cluster.

Important

You must deploy the Atlas cluster with MongoDB version 3.4 or greater.

Atlas provides a Free Tier M0 replica set as well as paid M10+ clusters. Free Tier deployments have restrictions as compared to paid M10+ deployments but will work for the purposes of this tutorial. For complete documentation on these restrictions, see Atlas M0 (Free Tier) Limitations.

3

Add a MongoDB Stitch application.

  1. In Atlas, click Stitch Apps in the left-hand navigation.
  2. Click the Create New Application. The name can only contain ASCII letters, numbers, underscores, and hyphens.
  3. Select your Atlas cluster for your MongoDB service.
  4. Click Create.

Upon creation of your app, you will be redirected to the MongoDB Stitch console. Your app is created with a MongoDB service named mongodb-atlas.

B. Configure the HTTP Service

Estimated Time to Complete: ~5 minutes

Creating rules for the HTTP service lets you control how your the app can be used.

1

Set up application values.

  1. Click on Values in the left-side navigation.

  2. Create a value named my-email-address with the email address you’d like to appear in the From: field of your messages. Enter your email address as a string value enclosed in double quotes, e.g. "name@example.com", and click the Save button to the right.

  3. Create another value named sg-api-key and populate it with your SendGrid developer API key as a string value enclosed in double quotes. Click the Save button.

  4. Finally, create a third value named sg-url and populate it with the SendGrid API access URL as a string value enclosed in double quotes:

    "https://api.sendgrid.com/v3/mail/send"
    

    Click the Save button.

For more information, see Values.

2

Add the HTTP service.

  1. Click on Add Service in the left-side navigation.
  2. Select HTTP from the list of services and name the service http1.

For more information, see Services.

3

Configure rules for the HTTP service.

  1. Click on http1 in the left-side navigation, then select the Rules tab.

  2. Click the Add Rule button and check post in the list of actions. This means that users of your app can only send POST requests with the http1 service.

  3. Replace the contents of the WHEN text box with the following document:

    {
      "%%args.url.host": "api.sendgrid.com",
      "%%args.body.from.email": "%%values.my-email-address",
      "%%args.body.personalizations.to.email": {
        "%in": [
          "name@example.com",
          "other-name@example.com"
        ]
      }
    }
    

    The document above describes the required conditions when creating a valid POST request.

    Field Description
    %%args.url.host The hostname to which POST URLs are restricted. MongoDB Stitch checks POST URLs to ensure the hostname matches the value specified here.
    %%args.body.from.email The permitted from address. MongoDB Stitch checks that the POST body for the personalizations.to.email matches the address stored in %%values.
    %%args.body.personalizations.to.email The array of possible recipients to which emails are restricted. MongoDB Stitch checks that the POST body for the personalizations.to.email matches an address stored in this array using the %in operator.

    For more information on pipeline arguments, see %%args.

  4. Modify the %in array to include at least one email address where you can receive email.

  5. Click the Save button to save your rule.

For more information, see HTTP Service Rules.

4

Configure authentication.

  1. Click the Authentication link in the left-side navigation. Click the Edit button on the Allow users to log in anonymously row. Click the toggle then close the modal. The row’s status should display Enabled.
  2. On the Authentication page, click the Edit button on the API Keys row. Click Create API Key, give your API key the name DEBUG_USER, then click Save.

Note

With any service that facilitates user messaging, ensure you properly secure your application. For example, consider using one of the supported MongoDB Stitch OAuth authentication mechanisms instead of anonymous authentication.

C. Testing the Pipeline

Estimated Time to Complete: ~5 minutes

Use the MongoDB Stitch Debug Console to make sure your SendGrid API key and your HTTP service are working together correctly.

1

Open the Debug Console.

Click Debug Console in the left-side Admin Console navigation.

2

Select a user.

At the top of the page, click the Select User button. In the modal window, select the DEBUG_USER created in the procedure above. Click the Done button.

3

Configure the test pipeline.

  1. Mouse over the pipeline stage panel and click the edit icon.

  2. Inside the Pipeline panel, select http1 from the Service drop-down menu.

  3. Select post from the Action drop-down menu.

  4. Remove the default pipeline arguments from the text entry box.

  5. Copy and paste the following document in the arguments text entry. Replace name@example.com with an address where you can receive email, and be sure that address is also in the list of approved addresses, %%args.body.personalizations.to.email, which you added to the http1 service rule.

    {
      "url": "%%values.sg-url",
      "headers": {
        "Authorization": [
          "%%vars.auth"
        ],
        "Content-Type": [
          "application/json"
        ]
      },
      "body": {
        "personalizations": [
          {
            "to": [
              {
                "email": "name@example.com"
              }
            ]
          }
        ],
        "from": {
          "email": "%%values.my-email-address"
        },
        "subject": "SG test message",
        "content": [
          {
            "type": "text/plain",
            "value": "This is a test message from SendGrid"
          }
        ]
      }
    }
    
    Field Description
    %%values.sg-url The sg-url value saved in your app’s values.
    %%vars.auth The value in the %%vars data (let statement) containing the formatted SendGrid API key. This will be defined in the following step.
    %%values.my-email-address The my-email-address value saved in your app’s values.

    For more information, see Pipelines.

  6. Toggle the Bind Data To %%Vars switch to on and display the let statement panel.

  7. Copy and paste the following document into the text entry revealed by the Bind Data To %%Vars switch.

    {
      "auth": {
        "%concat": [
          "Bearer ",
          "%%values.sg-api-key"
        ]
      }
    }
    

    The %concat operator concatenates the “Bearer” string with your SendGrid API Key, stored in your apps values as %%values.sg-api-key. The resulting string is passed to %%vars.auth in the pipeline above.

For more information on the let statement (%%vars data), see Pipeline with let.

4

Execute the pipeline.

Once you have configured the pipeline, click Execute to run the pipeline. If successful, MongoDB Stitch displays a JSON response document in the Result panel, and the e-mail address specified in body.personalizations.to should receive an email.

Note

Look in your spam folder if you don’t see the message in your inbox. The message is sent by SendGrid but has a different From address, and that can trigger your email client’s spam filter. If it is not in your inbox or spam folder, check your SendGrid activity to see if the email was blocked.

Troubleshooting

Error Possible Cause
No matching rule found The arguments are not meeting the HTTP service validation rules. Either the url argument doesn’t match what’s in the rule, or the to: address is not listed in the rule.
The provided authorization grant is invalid, expired, or revoked Something may be wrong with the SendGrid API key you provided.
Do not know how to expand 'some-variable' There may be a variable in your arguments which the app does not recognize. Check your Values section to make sure everything is spelled correctly.

HTML for the App

Estimated Time to Complete: ~1 minute

Create a file named index.html and copy and paste the HTML below into it.

<!doctype html>
<html>
    <head>
        <title>SendGrid API emailer</title>
        <meta charset="utf-8">
        <script src="https://s3.amazonaws.com/stitch-sdks/js/library/stable/stitch.min.js"></script>
        <script defer type="text/javascript" src="app.js"></script>
        <style>
            body {
                font-family: "Helvetica";
                margin-top: 50px;
                margin-left: 50px;
            }
        </style>
    </head>
    <body>
        <h2>SendGrid API emailer</h2>
        <table>
          <tr>
            <td>To:</td>
            <td><input id="toEmail" type="text" size="30" maxlength="40"> </input></td>
          </tr>
          <tr>
            <td>Subject:</td>
            <td><input id="subject" type="text" size="30" maxlength="50"> </input></td>
          </tr>
          <tr>
            <td>Message:</td>
            <td><textarea id="messageBody" rows="4" cols="50" maxlength="300"> </textarea></td>
          </tr>
          <tr>
            <td></td>
            <td><button id="sendButton">Send email</button></td>
          </tr>
        </table>
        <div>
            <p id="jsonResponse"></p>
        </div>
    </body>
</html>

You can point your web browser to the new index.html file and see what the web form looks like, but it doesn’t do anything yet. Next you need to create another file in the same directory called app.js. This file contains the JavaScript code to make the app work.

JavaScript for the App

Estimated Time to Complete: ~4 minutes

  1. Create a file named app.js in the same location as the index.html. Copy and paste the JavaScript code below into app.js.
  2. Visit the Clients page of the Admin Console to locate your app’s Application ID. Replace STITCH-APP-ID with your Application ID in app.js.
  3. Test the application.

The app workflow is as follows:

  • Performs anonymous user authentication via the login() method without the optional parameters. For more information, see login().
  • The application executes a MongoDB Stitch pipeline when the user clicks the Send email button. The pipeline functions in the same way that it did in the Debug Console, with all the POST request arguments specified in the args object. The service and action are specified at the top of the pipeline.
  • Displays a confirmation message on success, an error message on failure, or prompts the user if no email address was entered in the form.

See the in line code comments for additional step-by-step information.

document.addEventListener('DOMContentLoaded', () => {

    'use strict'

    // Replace STITCH-APP-ID with your Application ID
    const stitchClient = new stitch.StitchClient("STITCH-APP-ID");
    const sendButton = document.getElementById('sendButton');

    // Allow anonymous user access for this app
    function doAnonymousAuth() {
      stitchClient.login()
        .then( result => {
          console.log("authenticated");
        }).catch( err => {
          console.error("Error performing auth", err)
        });
    }

    // Execute pipeline when Send button is clicked
    sendButton.onclick = () => {

      const toEmail = document.getElementById("toEmail").value;
      const subject = document.getElementById("subject").value;
      const messageBody = document.getElementById("messageBody").value;

      // Check to make sure there's a To: address
      if (toEmail != "") {

        stitchClient.executePipeline([
          {
            // "http1" is the name of our HTTP service
            service:"http1",
            action:"post",
            let: {
              "sgUrl": "%%values.sg-url",
              "auth": {
                "%concat": ["Bearer ", "%%values.sg-api-key"]
              },
              "myEmail" : "%%values.my-email-address"
            },
            args: {
              "url": "%%vars.sgUrl",
              "headers": {
                "Authorization": [ "%%vars.auth" ],
                "Content-Type": [ "application/json" ]
              },
              "body": {
                // Include fields required by SendGrid
                "personalizations": [
                  {
                    "to": [{ "email": toEmail }]
                  }
                ],
                "from": {
                  "email": "%%vars.myEmail"
                },
                "subject": subject,
                "content": [
                  {
                    "type": "text/plain",
                    "value": messageBody
                  }
                ]
              }
            }
          }

        ]).then (function (result) {
          if (result) {
            // Show a message for successful execution
            document.getElementById('jsonResponse').innerText = "Message successfully sent to " + toEmail;
          }
        }).catch( err => {
          // Possible errors: invalid URL, invalid API key, To address not on approved list
          document.getElementById('jsonResponse').innerText = "Message could not be sent. " + err;
        });

      } else {
        // No To: address entered
        document.getElementById('jsonResponse').innerText = "Please enter an email address.";
      }
    }

    doAnonymousAuth()

});