SendGrid API Key Setup: Create, Secure, and Manage Access Credentials
In this tutorial, you will learn about SendGrid API Key Setup: Create, Secure, and Manage Access Credentials. We cover key concepts, practical examples, and best practices to help you master this topic.
SendGrid API keys authenticate your application to send emails. Creating scoped keys with minimal permissions and rotating them regularly is essential for security.
What You'll Learn
How to create SendGrid API keys with specific permissions, store them securely, rotate keys without downtime, and revoke compromised credentials.
Why It Matters
A compromised API key can send spam on your account, damaging your reputation and incurring costs. DodaTech uses separate keys per environment (dev, staging, prod) with minimal permissions and automatic rotation.
Real-World Use
A developer creates a key with "Mail Send" permission only for the staging environment. If leaked, the key can only send mail from staging, not access billing or account settings.
flowchart LR
A["Create API Key\nSendGrid Console"] --> B["Select Permissions\nMinimal Scope"]
B --> C["Copy Key\nOne-time Display"]
C --> D["Store in\nSecret Manager"]
D --> E["App Uses Key\nEnvironment Variable"]
E --> F["Rotate Every\n90 Days"]
style A fill:#dbeafe,stroke:#2563eb
style D fill:#fef3c7,stroke:#d97706
style F fill:#bbf7d0,stroke:#16a34a
Creating an API Key
# In SendGrid Dashboard:
# Settings > API Keys > Create API Key
# Name: "prod-mail-sender"
# Permissions: "Mail Send" (Restricted Access)
# Or create programmatically:
import sendgrid
sg = sendgrid.SendGridAPIClient("ROOT_API_KEY")
data = {
"name": "ci-cd-deploy-key",
"scopes": ["mail.send", "stats.read"]
}
response = sg.client.api_keys.post(request_body=data)
print("Key created:", response.status_code)
# Key is shown once: copy immediately!
Expected output:
Key created: 201
API Key: SG.abc123...xyz (save this now — won't be shown again)
Storing Keys Securely
import os
# Never hardcode API keys in source code
# Correct: environment variables
SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY")
# Better: secret manager (e.g., AWS Secrets Manager, Google Secret Manager)
import boto3
def get_key():
session = boto3.session.Session()
client = session.client("secretsmanager")
secret = client.get_secret_value(SecretId="sendgrid/prod/api-key")
return secret["SecretString"]
# Best: CI/CD secrets (GitHub Actions)
# Settings > Secrets and variables > Actions > New repository secret
# Name: SENDGRID_API_KEY
# Value: SG.abc123...
Key Rotation
# Rotation process:
# 1. Create new API key in SendGrid Console
# 2. Deploy new key to production (keep old key active)
# 3. Verify new key works
# 4. Revoke old API key
def rotate_key(old_key_name, new_key_name):
sg = sendgrid.SendGridAPIClient(os.environ["ADMIN_API_KEY"])
# Create new key
new_key = sg.client.api_keys.post(request_body={
"name": new_key_name,
"scopes": ["mail.send"]
})
# Deploy new key to your app
print("New key deployed. Verify before revoking old key.")
# Revoke old key
# Find old key ID first
keys = sg.client.api_keys.get()
for key in keys.to_dict()["result"]:
if key["name"] == old_key_name:
sg.client.api_keys._(key["id"]).delete()
print(f"Revoked old key: {old_key_name}")
break
Common Mistakes
1. Hardcoding API Keys in Code
Keys committed to git are exposed. Anyone with repo access can use them. Always use environment variables or secret managers.
2. Using Full Access Keys
Full access keys can modify account settings, access billing, and delete data. Create keys with minimal permissions (Mail Send only).
3. Not Rotating Keys
Static keys are vulnerable to long-term exposure. Rotate API keys every 90 days or immediately after a suspected breach.
4. Storing Keys in Client-Side Code
Web and mobile apps expose bundled keys. Use a backend proxy to send email, never embed SendGrid API keys in client applications.
5. Forgetting to Revoke Old Keys
After rotation, the old key remains active. Revoke it immediately after verifying the new key works.
Practice Questions
- What is the principle of Least Privilege for API keys?
- How do you rotate a SendGrid API key without downtime?
- Why should you never embed API keys in client-side code?
- How do you revoke a compromised API key?
Answers:
- Create keys with only the permissions needed (e.g., Mail Send only), not full account access. Use separate keys per environment.
- Create a new key, deploy it alongside the old key, verify the new key works, then revoke the old key.
- Client-side code can be inspected. Anyone can extract the key and use your SendGrid account to send spam.
- In SendGrid Console > Settings > API Keys, find the key and click "Remove." Or use the API:
DELETE /v3/api_keys/{key_id}.
Challenge: Set up a key management system: create separate API keys for dev, staging, and prod with Mail Send only permissions, store in environment variables, implement rotation every 90 days, and write a key revocation script.
FAQ
Mini Project
Create a secure API key management Process: generate scoped keys for dev/staging/prod, implement environment variable loading, set up a 90-day rotation script, and configure IP restrictions.
What's Next
Send Your First Email — send your first transactional email using the REST API.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro