如何通过Google Calendar API编程将ICS文件(URL)导入谷歌日历
Great question! The web UI's "Add calendar by URL" feature does have an API equivalent, but it splits into two distinct workflows depending on whether you want to import events into your existing calendar (copying them so future ICS updates won't affect your calendar) or subscribe to the ICS feed (mirroring the feed's updates, just like the web UI does). Let's break both down:
This copies all events from the ICS file into your target calendar (they'll exist independently of the original ICS feed). Here's how to implement it:
Step 1: Fetch the ICS content
Use an HTTP client to download the raw ICS text from your URL. For example, in Python:import requests ics_url = "https://your-ics-url-here.ics" ics_content = requests.get(ics_url).textStep 2: Parse the ICS file
Use an ICS parsing library to convert the raw text into structured event data. For Python, theicslibrary works well:from ics import Calendar cal = Calendar(ics_content)Step 3: Insert events via Google Calendar API
Iterate over the parsed events, format them to match the Google Calendar API's event schema (pay close attention to time zones and RFC3339 date formats), and use theevents.insert(orevents.batchInsertfor bulk operations) endpoint to add them to your calendar.A quick example of a valid event payload for the API:
{ "summary": "Event Title from ICS", "start": { "dateTime": "2024-05-20T10:00:00-04:00", "timeZone": "America/New_York" }, "end": { "dateTime": "2024-05-20T12:00:00-04:00", "timeZone": "America/New_York" }, "description": "Event description from ICS" }
If you want the exact same behavior as the web UI—where Google automatically syncs updates from the ICS URL to a dedicated calendar—you can use the CalendarList.insert endpoint. This creates a subscribed calendar linked directly to your ICS feed.
Here's a sample request body for this operation:
{ "summary": "My Subscribed ICS Calendar", "source": { "url": "https://your-ics-url-here.ics", "format": "ics" } }
Once you send this request, Google will add a new calendar to your Calendar List that syncs with the ICS feed automatically, just like when you use the web UI tool.
- Permissions: You'll need the right OAuth 2.0 scopes. For importing events, use
https://www.googleapis.com/auth/calendar. For subscribing to feeds,https://www.googleapis.com/auth/calendarorhttps://www.googleapis.com/auth/calendar.readonly(if you only need read access) works. - Time Zones: Be careful with time zone conversions when parsing ICS events—many files use UTC or local time zones, which you'll need to map to Google's supported time zone IDs.
- Batch Operations: For large ICS files, use
events.batchInsertto cut down on API calls and boost performance.
内容的提问来源于stack exchange,提问作者Jason.Z

