SendGrid query tutorial
Learn how to send email and manage contacts with SendGrid.
After setting up a SendGrid integration with Retool, your SendGrid resource is available to use in the query editor. SendGrid queries are operation-based: you select an operation from SendGrid's API, rather than writing SQL.
Create a query
- Classic app
- Workflow or agent
Retool recommends using the new app builder so you can use natural language to build React-based apps using AI.
To create a SendGrid query in a Retool app:
- In the Retool app IDE, open the Code tab, then click + in the page or global scope.
- Select Resource query.
- Choose your SendGrid resource.
- Select an operation and configure its parameters.
Workflows and agent custom tools use the same Resource query block to query SendGrid.
- Add a Resource query block to your workflow or custom tool's function canvas.
- Choose your SendGrid resource.
- Select an operation and configure its parameters.
Custom tools use the same block-based canvas as workflows, so the steps are identical in either context.
Select an operation
Available operations are derived from SendGrid's v3 API. When you select an operation, the query editor displays the parameters and request body fields for that operation. Refer to SendGrid's API reference for the complete list of operations and their request and response schemas.
For example, select POST /mail/send to send an email, or GET /marketing/lists to retrieve contact lists.
Query configuration fields
Operation
The SendGrid API operation to call, shown as an HTTP method and path (for example, POST /mail/send).
Parameters
Path, header, and query parameters for the selected operation, if any. For example, the GET /messages operation (Email Activity) accepts a limit query parameter to control how many results are returned.
{{ resultsLimitInput.value }}
Request body
For operations that accept a request body (typically POST and PATCH/PUT requests), configure each field individually or provide the full body as JSON. Use embedded expressions to reference component values.
{
"personalizations": [
{
"to": [{ "email": {{ recipientInput.value }} }]
}
],
"from": { "email": "notifications@example.com" },
"subject": {{ subjectInput.value }},
"content": [
{
"type": "text/plain",
"value": {{ messageInput.value }}
}
]
}
Common use cases
The following examples demonstrate typical SendGrid operations in Retool apps. For complete parameter and request body references, refer to the SendGrid API reference.
send a transactional email
First, add a Form component (form1) with fields for the recipient, subject, and message body.
Next, create a query with the POST /mail/send operation and configure the request body:
{
"personalizations": [
{
"to": [{ "email": {{ form1.data.recipient }} }]
}
],
"from": { "email": "notifications@example.com" },
"subject": {{ form1.data.subject }},
"content": [
{
"type": "text/plain",
"value": {{ form1.data.message }}
}
]
}
Then, add an event handler to the form's Submit event that runs the query and displays a success notification.
send email from a dynamic template
First, create a query with the POST /mail/send operation.
Next, configure the request body to reference a SendGrid dynamic template and its substitution data:
{
"personalizations": [
{
"to": [{ "email": {{ table1.selectedRow.data.email }} }],
"dynamic_template_data": {
"first_name": {{ table1.selectedRow.data.firstName }},
"order_id": {{ table1.selectedRow.data.orderId }}
}
}
],
"from": { "email": "orders@example.com" },
"template_id": "d-0123456789abcdef0123456789abcdef"
}
Then, add an event handler to a button's Click event that runs the query.
add a contact to a list
First, add a Form component with fields for contact details.
Next, create a query with the PUT /marketing/contacts operation to upsert a contact:
{
"list_ids": ["8ba9f0f0-3d0e-4a3a-8c1e-b1c8e8e3d5a0"],
"contacts": [
{
"email": {{ form1.data.email }},
"first_name": {{ form1.data.firstName }},
"last_name": {{ form1.data.lastName }}
}
]
}
Then, add an event handler to the form's Submit event that runs the query and displays a success notification.
list contact lists
Create a query with the GET /marketing/lists operation to retrieve contact lists.
Next, add a Table component to the app and set its Data property to {{ listContactListsQuery.data.result }}.
review email activity
Create a query with the GET /messages operation (Email Activity) and configure the limit parameter to control how many results are returned:
| Field | Value |
|---|---|
| Operation | GET /messages |
| limit | {{ resultsLimitInput.value }} |
Next, add a Table component to the app and set its Data property to {{ emailActivityQuery.data.messages }}.
Best practices
Follow these best practices to keep SendGrid queries fast, efficient, and safe.
Performance
- Cache responses: For data that doesn't change frequently, such as contact lists, enable query caching to reduce API calls and improve response times.
- Use pagination: Configure the
limitand offset-style parameters available on list operations (like Email Activity) to avoid retrieving more data than a page needs. - Batch contact updates: Use the PUT /marketing/contacts operation's array-based request body to upsert multiple contacts in a single request instead of one request per contact.
- Minimize payload size: Request only the fields you need using the query parameters SendGrid's API supports for a given operation.
- Set appropriate timeouts: Configure query timeouts based on expected API response times to prevent hung requests.
Data integrity
- Validate user input: Sanitize and validate email addresses and other user input before including them in a request body to prevent malformed requests.
- Handle errors gracefully: Configure error notifications and fallback behavior for failed queries, since SendGrid returns detailed error messages for invalid requests.
- Verify responses: Check response status codes and validate response data structure before using it in your app.
- Implement retry logic: For transient failures, use Retool's automatic retry settings or implement custom retry logic with exponential backoff.
- Log query activity: Enable query logging to track requests and responses for debugging and auditing.
Troubleshoot permission errors
If a query fails with a 403 Forbidden or similar permission error, the API key configured on the resource likely doesn't have access to that operation.
- Restricted access keys: If the resource uses a restricted access API key, verify it includes permission for the specific operation (for example, Mail Send or Marketing).
- Revoked or regenerated keys: Confirm the API key hasn't been revoked or regenerated in SendGrid since the resource was configured.