• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Last Call - The RapidAPI Blog

  • Marketplace
  • Add Your API
  • About
  • Docs
    • API Glossary
  • Blog
    • API Tutorials
      • Google Sheets
      • Python
      • JavaScript
      • PHP
      • Java
      • Ruby on Rails
      • C#
    • Most Popular APIs
  • Teams
  • Sign Up
    • Log In
Blog > APIs > SendGrid API Overview & How To Use The SendGrid API
sendgrid api

SendGrid API Overview & How To Use The SendGrid API

May 1, 2019 By RapidAPI Staff Leave a Comment

Table of Contents

  • What is SendGrid?
    • Is SendGrid API Free?
    • How much does SendGrid Cost?
  • SendGrid API Endpoints
    • Sending emails
    • Scheduled Sends
    • Blocks
    • Bounces
    • Invalid Emails
    • Spam Reports
    • Unsubscribe Groups (Suppression management)
    • Suppressions (Unsubscribe)
    • Settings
    • Account Stats
  • Use Case: Elon Musk Monitoring App
  • Conclusion

What is SendGrid?

Most online businesses depend on the quality of email delivery. Whether you have an online store, a social network or a news portal, you have to ensure that your notifications and transactional emails are delivered quickly and securely and are not classified as spam. SendGrid service accomplishes this task, and RapidAPI makes it easy to integrate this service into your application.

All necessary functions of SendGrid API are available through RapidAPI. You can send emails, track statistics and adjust settings. Let’s walk through the SendGrid API capabilities in a bit more detail.

SendGrid API on RapidAPI.com

In order to find this API, enter its name in the search box at the RapidAPI service, or go to the “Email” category and select this API from the list.

Connect to API

Is SendGrid API Free?

Yes and no. SendGrid API works according to the “Freemium” model, which means that you can send a certain number of emails for free (currently 100), and you have to pay to send more. To start using this API, you need to subscribe to it. Go to the Pricing section and click on Subscribe button.

How much does SendGrid Cost?

PlanBasicProUltraMega
Pricing$0.00/Month$9.95/Month$79.95/Month$199.95/Month
Quota100/day40,000/month100,000/month300,000/month
Price per additional request$0.001$0.001$0.00085$0.0005
SubscribeSubscribeSubscribeSubscribe

Related: Best Email APIs for You

SendGrid API Endpoints

The API functionality is available in the Endpoints section. The window is divided into three main areas. The first area on the left displays a list of available tasks sorted into 12 groups, and each task displays its HTTP method. For the SendGrid API, the following task groups are presented:

  • Mail
  • Blocks
  • Bounces
  • Invalid Emails
  • Spam Reports
  • Cancel Scheduled Sends
  • Unsubscribe Groups
  • Suppressions (Unsubscribe)
  • Settings – Tracking
  • Settings – Mail
  • Settings – Inbound Parse
  • Account Stats.

SendGrid API Endpoints

Sending emails

The main objective of the SendGrid API is email sending. Send endpoint in the Mail group is responsible for this function. Let’s select this task and test it right away. Just fill in the required fields (in the simplest case, just specify your email in the JSON parameter “to”) and click Test Endpoint. The API call will be sent immediately, and you will see the results on the right side of the page in the Sample Response block.

SendGrid API Response

We should also mention the Request Snippet block. You can choose a particular programming language and immediately get the code that implements the task that you have just tested. The SendGrid API is now available through RapidAPI for such programming languages as:

  • NodeJS
  • PHP
  • Python
  • Ruby
  • Objective-C
  • Java
  • and C#

For example, here’s a Ruby snippet for sending mail through SendGrid API:

response = Unirest.post "https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send",
  headers:{
    "X-RapidAPI-Host" => "rapidprod-sendgrid-v1.p.rapidapi.com",
    "X-RapidAPI-Key" => "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "Content-Type" => "application/json"
  }
  "{"personalizations":[{"to":[{"email":"[email protected]"}],"subject":"Hello, World!"}],"from":{"email":"[email protected]"},"content":[{"type":"text/plain","value":"Hello, World!"}]}"

Below, a similar task is implemented with SendGrid API C#:

Task<HttpResponse<MyClass>> response = Unirest.post("https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send")
.header("X-RapidAPI-Host", "rapidprod-sendgrid-v1.p.rapidapi.com")
.header("X-RapidAPI-Key", "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.header("Content-Type", "application/json")
.body("{"personalizations":[{"to":[{"email":"[email protected]"}],"subject":"Hello, World!"}],"from":{"email":"[email protected]"},"content":[{"type":"text/plain","value":"Hello, World!"}]}")
.asJson();

And, of course, SendGrid API Python:

response = unirest.post("https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send",
  headers={
    "X-RapidAPI-Host": "rapidprod-sendgrid-v1.p.rapidapi.com",
    "X-RapidAPI-Key": "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "Content-Type": "application/json"
  },
  params=("{"personalizations":[{"to":[{"email":"[email protected]"}],"subject":"Hello, World!"}],"from":{"email":"[email protected]"},"content":[{"type":"text/plain","value":"Hello, World!"}]}")
)

Scheduled Sends

Emails can be sent at a certain time to queued batches using a UNIX timestamp parameter. To do this, firstly, create batch_id using Create a batch ID endpoint from the Cancel Scheduled Sends group.

SendGrid API Cancel Schedule Sends

The resulting batch_id is added as a parameter in Send endpoint of Mail group along with the send time in send_at parameter in UNIX timestamp format. Emails can be scheduled only up to 72 hours in advance. You can also use send_each_at parameter, which you can learn more about in the documentation.

SendGrid API Endpoints Scheduling

Cancel Scheduled Sends group also allows you to perform the tasks necessary to control queued batches, namely:

  • validate batch ID
  • cancel or pause a scheduled send
  • retrieve all scheduled sends
  • retrieve a specific scheduled send
  • update user scheduled send information
  • delete a cancellation or pause of a scheduled send.

Blocks

After sending emails, you can explore statistics and find out which emails were blocked and which were classified as spam. To begin with, we will receive information about blocked emails (emails can be blocked for various reasons, for example, mail server IP address is on an ISP blacklist). Retrieve all blocks endpoint from the Blocks group will help us with this task. Optionally, when accessing this endpoint, you can specify the start_time and end_time parameters in UNIX timestamp format to limit the time interval in which blocked messages were created. You can also specify limit to bound the number of results obtained, and offset to determine from which element number in the list to start displaying results.

Let’s get the list of blocked emails using PHP SendGrid API:

$response = UnirestRequest::get("https://rapidprod-sendgrid-v1.p.rapidapi.com/suppression/blocks?start_time=1555410576&end_time=1555583376&limit=100&offset=10",
  array(
    "X-RapidAPI-Host" => "rapidprod-sendgrid-v1.p.rapidapi.com",
    "X-RapidAPI-Key" => "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  )
);

Blocks group also allows you to perform the following tasks:

  • Retrieve a specific block (this endpoint allows you to retrieve a specific email address from your blocks list)
  • Delete a specific block (removes a particular letter from the blocks list).

Bounces

Further, we may need to examine our bounced emails. An email is bounced when the message is undeliverable and then returned to the server that sent it. We can perform this task using Retrieve all bounces endpoint from the Bounces group. When accessing the endpoint, we can also specify the optional parameters limit and offset.

We will retrieve all our bounces with SendGrid API Java:

HttpResponse<JsonNode> response = Unirest.get("https://rapidprod-sendgrid-v1.p.rapidapi.com/suppression/bounces")
.header("X-RapidAPI-Host", "rapidprod-sendgrid-v1.p.rapidapi.com")
.header("X-RapidAPI-Key", "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.asJson();

Similar to the previous group, the Bounces group also allows you to perform the following tasks:

  • Retrieve a bounce (endpoint allows you to retrieve a specific bounce for a given email address)
  • Delete a bounce (allows you to remove an email address from your bounce list).

Invalid Emails

When sending emails, we can make some mistakes, for example, specify an email address incorrectly or send an email to a user who was removed from the recipient server a long time ago. We can retrieve a list of such invalid email addresses using Retrieve all invalid emails endpoint from the Invalid Emails group. When accessing it, we can specify start_time and end_time parameters, as well as limit and offset.

Let’s get the invalid emails list using Ruby SendGrid API:

response = Unirest.get "https://rapidprod-sendgrid-v1.p.rapidapi.com/suppression/invalid_emails?limit=100&offset=7&start_time=1555410576&end_time=1555583376",
headers:{
    "X-RapidAPI-Host" => "rapidprod-sendgrid-v1.p.rapidapi.com",
    "X-RapidAPI-Key" => "445fc65fe5msh23e488e3a6c1860p1628f3jsnecdc11ef78fd"
  }

Surely, Invalid Emails group allows you to retrieve a specific invalid email address using Retrieve a specific invalid email endpoint and remove invalid email address list using Delete a specific invalid email endpoint.

Spam Reports

Our emails may be classified by some recipients as spam. It is important for us to know the list of such recipients, and Retrieve all spam reports endpoint from Spam Reports group will help us with this. As in many previous endpoints, when accessing it we have the opportunity to specify the optional parameters start_time and end_time as well as limit and offset, and again there are Delete a specific spam report and Retrieve a specific spam report endpoints.

We will retrieve all spam reports with SendGrid API Python:

response = unirest.get("https://rapidprod-sendgrid-v1.p.rapidapi.com/suppression/spam_reports?limit=100&offset=10&start_time=1555410576&end_time=1555583376",
 headers={
    "X-RapidAPI-Host": "rapidprod-sendgrid-v1.p.rapidapi.com",
    "X-RapidAPI-Key": "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  }
)

Unsubscribe Groups (Suppression management)

SendGrid API allows you to create suppression groups or unsubscribe groups (specific types or categories of email that you would like your recipients to be able to unsubscribe from). You can create up to 25 different suppression groups. For example Daily Newsletters, Invoices, System Alerts. If your subscribers don’t like Invoices, they can add themselves to Invoices unsubscribe group or you can add your subscribers to this group by yourself.

You can create a suppression group with Create a new suppression group endpoint from Unsubscribe Groups. When accessing it, specify the necessary JSON parameters name and description and the optional parameter is_default.

Below is an example of creating a suppression group using SendGrid API Objective-C:

NSDictionary *headers = @{@"X-RapidAPI-Host": @"rapidprod-sendgrid-v1.p.rapidapi.com", @"X-RapidAPI-Key": @"4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", @"Content-Type": @"application/json"};
UNIUrlConnection *asyncConnection = [[UNIRest post:^(UNISimpleRequest *request) {
  [request setUrl:@"https://rapidprod-sendgrid-v1.p.rapidapi.com/asm/groups"];
  [request setHeaders:headers];
  [request setBody:@"{"name":"News","description":"News about products our users might like.","is_default":true}"];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
  NSInteger code = response.code;
  NSDictionary *responseHeaders = response.headers;
  UNIJsonNode *body = response.body;
  NSData *rawBody = response.rawBody;
}];

Unsubscribe Groups endpoint group provides all necessary capabilities to manage your suppression groups. In addition, to Create a new suppression group task, you can get information about a specific unsubscribe group, update information about a specific unsubscribe group, delete a specific group and retrieve all suppression groups associated with the user.

Suppressions (Unsubscribe)

After the unsubscribe group is created, you can add subscribers to it so that they stop receiving emails related to this group. To do this, you can use Add suppressions to a suppression group endpoint from Suppressions (Unsubscribe) group. When accessing the mentioned endpoint, you should specify group_id and email addresses that you want to add to unsubscribe group.

We will add suppressions to a suppression group with SendGrid API Python:

response = unirest.post("https://rapidprod-sendgrid-v1.p.rapidapi.com/asm/groups/10442/suppressions",
headers={
    "X-RapidAPI-Host": "rapidprod-sendgrid-v1.p.rapidapi.com",
    "X-RapidAPI-Key": "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "Content-Type": "application/json"
  },
  params=("{"recipient_emails":["[email protected]"]}")
)

Now the subscriber [email protected] will stop receiving our emails with the specified group id 10442.

Here is an example of sending a letter with a specific suppression group using SendGrid API Python:

response = unirest.post("https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send",
  headers={
    "X-RapidAPI-Host": "rapidprod-sendgrid-v1.p.rapidapi.com",
    "X-RapidAPI-Key": "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "Content-Type": "application/json"
  },
  params=("{"personalizations":[{"to":[{"email":"[email protected]"}],"subject":"Hello, World 3!"}],"from":{"email":"[email protected]"},"content":[{"type":"text/plain","value":"Hello, World!"}],"asm":{"group_id":10442}}")
)

Suppressions (Unsubscribe) endpoint group gives you access to all necessary functionality for managing suppressions. For example, you can

  • add/remove subscribers to/from certain suppression groups
  • get all suppressions and get suppressions for a suppression group
  • remove suppression from a suppression group
  • obtain a list of all suppression groups for an email address
  • search for suppressions within a group.
Have an API you want to add to our API Marketplace?
plus
Add your API to our marketplace

Settings

SendGrid API provides access to all of your account settings through Settings – Tracking, Settings – Mail, Settings – Inbound Parse endpoint groups. A detailed description of the settings deserves a separate article, so we will only describe in general what settings each group is responsible for.

  • Settings – Tracking allows you to manage all tracking settings that you can enable on your account. You can track a variety of the actions your recipients may take when interacting with your emails including opening your emails, clicking on links in your emails, and subscribing to (or unsubscribing from) your emails.
  • Settings – Mail helps you manage all mail settings. Mail settings allow you to tell SendGrid specific things to do to every email that you send to your recipients over SendGrid’s Web API. For example, you can add custom BCC to every email you send, manage whitelists, insert custom footer to every email you send, specify an email address to which spam reports will be forwarded, etc.
  • Settings – Inbound Parse enables managing all of your current inbound parse settings. The inbound parse webhook allows you to have incoming emails parsed, extracting some or all of the content, and then have that content posted by SendGrid to an URL that you choose.

Account Stats

After all the work is done and the emails are sent out, you may want to study the statistics of your mailings. Account Stats endpoint group will help you with this. You will be able to perform the following tasks: retrieve global email statistics, retrieve statistics by country, state, device type, client type, mailbox provider and browser. While accessing these endpoints, you can specify a variety of parameters: get statistics for a certain time interval, group results, or limit the number of results obtained.

Use Case: Elon Musk Monitoring App

We will show a small example of how you can use SendGrid API together with other APIs from the RapidAPI platform in your applications. Imagine that you are acquainted with a group of Elon Musk’s fans. They want to receive all the news about him on their emails and they don’t want to miss out anything. For such purposes, we decided to write a small application in Python that will use the full power of RapidAPI. SendGrid API will deal with high-quality and reliable sending of emails while CivicFeed – News API will get all the latest news about Elon Musk.

Elon Musk

To get started, we import the necessary libraries and specify our RapidAPI service key (you can get it in the Dashboard > My Apps > Your app name > Security section).

import unirest
import json
from time import sleep
rapidKey = "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

With the help of CivicFeed API, we create a function that will let us know the latest news about Elon Musk.

def fresh_news():
    news = unirest.get("https://civicfeed-civicfeed-news-v1.p.rapidapi.com/news/search?q=Elon+Musk&from=2019-01-01&results=30&sort=created",
      headers={
        "X-RapidAPI-Host": "civicfeed-civicfeed-news-v1.p.rapidapi.com",
        "X-RapidAPI-Key": rapidKey
      }
    )
    return news

 

We want our app to receive the latest news every minute. After that, it should clarify whether it has already sent this news by checking with the list of old news (old news headlines will be stored in the old_titles set). In case some of the news hasn’t been sent out yet – the app will send the latest news to emails list.

With the help of SendGrid API, we will create a function for sending emails:

def send_news(mails, sNews):
    jNews = json.dumps(sNews.encode('utf-8'))
    
    response = unirest.post("https://rapidprod-sendgrid-v1.p.rapidapi.com/mail/send",
      headers={
        "X-RapidAPI-Host": "rapidprod-sendgrid-v1.p.rapidapi.com",
        "X-RapidAPI-Key": rapidKey,
        "Content-Type": "application/json"
      },
      params=("{"personalizations":[{"to":[%s],"subject":"Fresh Musk News!"}],"from":{"email":"[email protected]"},"content":[{"type":"text/html","value": %s }]}" % (jMails, jNews))
    )
    return response

 

We also require a custom jDict class for more convenient conversion of our emails list in JSON. We will store our emails in emails list in which each element is a tuple containing two values: the first is the string “email”, the second is the string with the email address itself. After that, we will make a jDict object from emails list and convert it to JSON with json.dumps method. We need this approach in order to convert our emails to the required JSON array format, which is necessary for the API.

class jDict(dict):
    def __init__(self, items):
        # need to have something in the dictionary
        self['something'] = 'something'
        self.items = items
    def __getitem__(self, key):
        return self.last_val
    def __iter__(self):
        subiter = iter(self.items)
        def generator():
            for key, value in self.items:
                self.last_val = value
                yield key

        return generator()

emails = [("email", "[email protected]"), 
          ("email", "[email protected]"),
          ("email", "[email protected]")]
jMails = json.dumps(jDict(emails), sort_keys=False)

That’s all we need, so we can start sending letters and keep abreast of all the news from Elon Musk’s life.

old_titles = set()

while True:
    news = fresh_news()
    to_send = []
    for article in news.body['articles']:
        if article['title'] not in old_titles:         
            to_send.append(article['title'] + "<br>" + article['url'])
            old_titles.add(article['title']) 
    
    if len(to_send) > 0:
        sNews = ""
        for title in to_send:
            sNews += title + "<br><br>"

        response = send_news(jMails, sNews)
        print response.body
    sleep(60)

Here is an email we got:

SendGrid API Elon Musk News

Conclusion

In this article, we provided a general overview of SendGrid API capabilities through RapidAPI service. As we have shown, all the available SendGrid API functionality can be easily embedded in your application and at the same time, you have access to many other APIs. Thus, you get the possibility of vast expansion for your application and you don’t need to look for additional services as all possible APIs are available through the RapidAPI service.

3.7 / 5 ( 3 votes )
« Bing News Search API Example: News Sentiment Analysis & Summarization (with the AylienText Analysis API)
Using Skyscanner Flight Search API with Dark Sky API and City Geo-Location Lookup [Tutorial] »

Related Blog Posts

How to use the SendGrid API with Ruby
How to use the SendGrid API with Ruby

How to Build an API in Python (with Django)
How to Build an API in Python (with Django)

How To Use IMDb API with Python To Power Your Movie Search App
How To Use IMDb API with Python To Power Your Movie Search App

How To Build a Weather App in JavaScript (Node.js) Using the OpenWeatherMap API
How To Build a Weather App in JavaScript (Node.js) Using the OpenWeatherMap API

How to Send SMS Messages with PHP (using Nexmo or Twilio)
How to Send SMS Messages with PHP (using Nexmo or Twilio)

How to Build an API in Python (with Flask & RapidAPI)
How to Build an API in Python (with Flask & RapidAPI)


Filed Under: API Tutorials, APIs, Case Study, The Dev Room Tagged With: api tutorial, Email, email api, SendGrid, SendGrid API

RapidAPI Staff

The RapidAPI staff consists of various writers in the RapidAPI organization. Check out our medium team page here. For support, please email us at [email protected].

Reader Interactions

Leave a Reply

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

Primary Sidebar

Build amazing apps, faster.

Discover, evaluate, and integrate with any API. RapidAPI is the world’s largest API marketplace with over 1,000,000 developers and 10,000 APIs.

Browse APIs

Footer

Learn

  • How to use an API
  • Skyscanner Travel API Overview
  • API Glossary
  • For Developers
  • For API Providers
  • About
  • Team
  • Jobs
  • Contact Us
  • API Directory
  • Press Room
  • Privacy Policy
  • Terms of Use

© 2019 RapidAPI. All rights reserved.