Engineering•3 min read

Scoping Piisend API Keys for Local, Staging, and Production

Learn how to securely manage your Piisend email API keys across different development environments. Implement environment-specific keys to enhance security and streamline your deployment process.

Scoping Piisend API Keys for Local, Staging, and Production

Section 1

Why Environment-Specific API Keys are Crucial

Managing API keys effectively is fundamental for application security, especially when dealing with sensitive operations like sending emails. Using distinct Piisend email API keys for your local development, staging, and production environments prevents unauthorized access and limits the blast radius in case a key is compromised. This approach allows for granular control over permissions and simplifies the process to rotate API key credentials without affecting other environments.

bash
1curl -X POST https://api.piisend.com/api/v1/emails \
2 -H "Authorization: Bearer YOUR_PRODUCTION_API_KEY" \
3 -H "Content-Type: application/json" \
4 -d '{
5 "to": ["customer@example.com"],
6 "subject": "Your Order Confirmation",
7 "html": "<p>Thank you for your order!</p>"
8 }'

Section 2

Generating Scoped API Keys in Piisend

Piisend allows you to create multiple API keys, each with specific scopes. For instance, a key used solely for sending emails might only need the emails:send scope. This principle of least privilege is vital. You can generate these keys directly from your Piisend dashboard, assigning descriptive names like 'Production Email Sender' or 'Staging Test Key' to easily identify their purpose and associated environment.

python
1import os
2import requests
3
4PIISEND_API_KEY = os.getenv("PIISEND_API_KEY")
5
6def send_email(to_email, subject, html_content):
7 if not PIISEND_API_KEY:
8 raise ValueError("PIISEND_API_KEY environment variable not set.")
9
10 headers = {
11 "Authorization": f"Bearer {PIISEND_API_KEY}",
12 "Content-Type": "application/json"
13 }
14 payload = {
15 "to": [to_email],
16 "subject": subject,
17 "html": html_content
18 }
19 response = requests.post(
20 "https://api.piisend.com/api/v1/emails",
21 headers=headers,
22 json=payload
23 )
24 response.raise_for_status()
25 print("Email sent successfully!")
26
27# Example usage for a staging environment
28send_email("test@example.com", "Staging Test Email", "<p>This is a test from staging.</p>")

Section 3

Securely Managing Keys in Your Application

Never hardcode your API keys directly into your application's source code. Instead, leverage environment variables. This ensures that your Bearer token is not exposed in version control systems and can be easily swapped out when deploying to different environments. For local development, you might use a .env file, while production environments typically use platform-specific environment variable management.

javascript
1const fetch = require('node-fetch');
2
3const PIISEND_API_KEY = process.env.PIISEND_API_KEY;
4
5async function sendEmail(toEmail, subject, htmlContent) {
6 if (!PIISEND_API_KEY) {
7 throw new Error('PIISEND_API_KEY environment variable not set.');
8 }
9
10 const response = await fetch('https://api.piisend.com/api/v1/emails', {
11 method: 'POST',
12 headers: {
13 'Authorization': `Bearer ${PIISEND_API_KEY}`,
14 'Content-Type': 'application/json'
15 },
16 body: JSON.stringify({
17 to: [toEmail],
18 subject: subject,
19 html: htmlContent
20 })
21 });
22
23 if (!response.ok) {
24 const errorData = await response.json();
25 throw new Error(`Failed to send email: ${response.status} ${response.statusText} - ${JSON.stringify(errorData)}`);
26 }
27
28 console.log('Email sent successfully!');
29}
30
31// Example usage for a local development environment
32sendEmail('dev@example.com', 'Local Dev Email', '<p>Hello from local development!</p>').catch(console.error);

Section 4

Seamless API Key Rotation Strategy

Regularly rotating your API keys is a critical security practice. With environment-specific keys, you can implement a rotation strategy without causing downtime. First, generate a new key in the Piisend dashboard. Update the PIISEND_API_KEY environment variable in your target environment (e.g., production) with the new key. Once the change is deployed and verified, you can safely revoke the old key. This ensures continuous service while maintaining robust security.

bash
1# Step 1: Set the new API key in your environment variables
2export PIISEND_API_KEY="sk_live_new_api_key_1234567890"
3
4# Step 2: Deploy your application (or restart if using a simple setup)
5# Your application will now use the new key.
6
7# Step 3: Verify that emails are sending correctly with the new key.
8# Once verified, you can revoke the old key from the Piisend dashboard.

Start sending

Ship transactional email in minutes

Create an API key, verify a domain, and send your first message with Piisend.