ESP32 Google Calendar: Secure API Key Setup
In this article
Connecting an ESP32 to Google Calendar normally means embedding API keys in your firmware, which is risky if the device is lost or the binary is extracted. This guide shows a secure alternative: a small server-side proxy that holds your credentials and forwards requests to the Google Calendar API. The ESP32 only talks to your proxy, so your keys never leave your server. You'll need a Google Cloud project with the Calendar API enabled, a service account, and a server (or a free-tier cloud function) that can run a simple Python or Node script.
What You'll Need
- An ESP32 board (any variant with Wi-Fi)
- Arduino IDE or PlatformIO with ESP32 board support installed
- A Google Cloud project with the Calendar API enabled
- A service account JSON key file from Google Cloud
- A server or cloud function (e.g., a free-tier service like Heroku, Glitch, or a Raspberry Pi on your network) that can run Python or Node.js
- Basic familiarity with the command line and editing config files
Step-by-Step
- Set up Google Cloud and get a service account key. Go to the Google Cloud Console, create a new project (or select an existing one), enable the Google Calendar API for that project, then go to “Credentials” → “Create Credentials” → “Service Account”. Assign the role “Viewer” (or a custom role with calendar read access), then create a JSON key for that service account. Download the JSON file — this contains your private key, so treat it like a password.
- Share your calendar with the service account email. In the service account JSON file, you'll find an email address like
your-service-account@your-project.iam.gserviceaccount.com. Open Google Calendar, go to the calendar you want to access, click the three dots next to it → “Settings and sharing”, then under “Share with specific people” add that email with “See all event details” permission. This lets the service account read your calendar. - Create the proxy server script. On your server, create a simple HTTP endpoint that accepts a request from the ESP32, fetches the calendar data using the service account credentials, and returns only the JSON you need. For Python, use the
google-api-python-clientandgoogle-authlibraries. A minimal Flask app would look like this:
Replacefrom flask import Flask, jsonify, request from google.oauth2 import service_account from googleapiclient.discovery import build app = Flask(__name__) SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] SERVICE_ACCOUNT_FILE = 'service_account.json' @app.route('/events') def get_events(): creds = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) service = build('calendar', 'v3', credentials=creds) now = datetime.utcnow().isoformat() + 'Z' events_result = service.events().list( calendarId='primary', timeMin=now, maxResults=5, singleEvents=True, orderBy='startTime').execute() return jsonify(events_result.get('items', [])) if __name__ == '__main__': app.run(host='0.0.0.0', port=8080)service_account.jsonwith the path to your key file. If you're using Node.js, use thegoogleapispackage similarly. The proxy should only expose the data you need, not the credentials. - Deploy the proxy. Upload the script and the service account JSON to your server. Run it (e.g.,
python app.py). Make sure the server is reachable from the internet if your ESP32 is on a different network, or use a local IP if both are on the same LAN. For security, add a simple shared secret header that the ESP32 must send, so random internet users can't query your proxy. - Test the proxy with a browser or curl. Open
http://your-server:8080/eventsin a browser (or usecurl). You should see a JSON array of upcoming events. If you added a secret header, include it in the test. - Write the ESP32 firmware. In the Arduino IDE, include the
WiFi.handHTTPClient.hlibraries. Connect to your Wi-Fi, then make an HTTP GET request to your proxy URL. If you used a secret header, add it. Parse the JSON response with theArduinoJsonlibrary. Here's a minimal sketch:
Adjust the JSON parsing based on your proxy's response structure.#include <WiFi.h> #include <HTTPClient.h> #include <ArduinoJson.h> const char* ssid = "YOUR_WIFI"; const char* password = "YOUR_PASS"; const char* proxyURL = "http://your-server:8080/events"; const char* secret = "your-secret"; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); } HTTPClient http; http.begin(proxyURL); http.addHeader("X-Secret", secret); int code = http.GET(); if (code > 0) { String payload = http.getString(); DynamicJsonDocument doc(2048); deserializeJson(doc, payload); for (JsonObject evt : doc.as<JsonArray>()) { Serial.println(evt["summary"].as<String>()); } } http.end(); } void loop() {} - Upload and test. Compile and upload the sketch to your ESP32. Open the Serial Monitor; you should see the event summaries printed. If not, check the HTTP status code and payload for errors.
Common Mistakes
- Forgetting to share your calendar with the service account email — you'll get a 403 error.
- Hardcoding the service account key in the ESP32 firmware — that defeats the purpose.
- Not enabling the Calendar API in the Google Cloud project.
- Using the wrong calendar ID — if you want a specific calendar, use its email address, not 'primary'.
- Exposing the proxy without any authentication — anyone can read your calendar.
Tips
- Use environment variables on the server to store the service account file path and secret, so they're not in the source code.
- Limit the proxy to return only fields you need (e.g., summary, start time) to reduce payload size and parsing complexity.
- Add a timeout in your ESP32 HTTP client to avoid hanging if the server is down.
- For frequent updates, consider caching the calendar response on the server for 30 seconds to reduce API calls.
- If your server has a static IP, use that instead of a hostname to avoid DNS delays.
Troubleshooting
- 403 Forbidden from the proxy: Check that the service account has been added to the calendar's sharing settings and that the calendar ID is correct.
- 401 Unauthorized: Your service account key might be expired or the scopes are wrong. Regenerate the key and ensure you're using
calendar.readonly. - ESP32 can't connect to the server: Verify the server is reachable from the same network (try pinging from a computer). Check the firewall on the server — port 8080 might be blocked.
- Empty response: If the proxy returns
[], that's fine — you have no upcoming events. If it returns an error, check the server logs. - JSON parsing errors: Make sure the response is a JSON array, not an object. Adjust the ArduinoJson filter or use a different deserialization method.
- Wi-Fi disconnects: Add a reconnect function in the ESP32 code to handle unstable networks.
Frequently Asked Questions
Can I use a free cloud function instead of my own server?
Yes, you can deploy the proxy as a serverless function on AWS Lambda, Google Cloud Functions, or Cloudflare Workers. Just ensure it has an HTTP endpoint and can store the service account key securely (e.g., via environment variables or a secret manager).
Is it safe to use the service account key on a server?
Yes, as long as the server is secure and the key file is not publicly accessible. The key is only used server-side, never sent to the ESP32.
Can I write events to Google Calendar from the ESP32?
Yes, but you'll need to modify the proxy to accept POST requests and use the calendar.events.insert method. Make sure your service account has editor permissions on the calendar.
What if I don't have a server?
You can use a free tier of a cloud provider, or even a Raspberry Pi at home. The proxy script is lightweight and runs on any device with Python or Node.js.
How do I add a shared secret to the proxy?
In the proxy script, check for a custom header (e.g., X-Secret) and compare it to a value you define. If it doesn't match, return a 401 response. On the ESP32, add that header to the HTTP request.
Can I use OAuth2 instead of a service account?
Yes, but it requires user consent and token refresh, which is more complex. Service accounts are simpler for server-to-server communication and work fine for a single calendar you own.