To push (upload) an .ics (iCalendar) file using Python’s requests library, you typically send it as part of a multipart/form-data POST request. This is common when interacting with APIs that accept calendar event data, such as Google Calendar, Outlook, or custom backend services.
Here’s a step-by-step guide and example:
1. Prepare Your .ics File
Ensure your .ics file is correctly formatted. Example content:
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:1234567890@example.com
DTSTAMP:20260225T120000Z
DTSTART:20260225T120000Z
DTEND:20260225T130000Z
SUMMARY:Meeting with Team
END:VEVENT
END:VCALENDAR
2. Python Code Example
Use the following code to upload the .ics file:
import requests
# URL of the API endpoint
url = "https://example.com/api/calendar/upload"
# Path to your .ics file
ics_file_path = "event.ics"
# Open the file in binary mode
with open(ics_file_path, "rb") as file:
files = {"file": (ics_file_path, file, "text/calendar")}
data = {"key": "value"} # Optional: Additional form data
# Send the POST request
response = requests.post(url, files=files, data=data)
# Check the response
print("Status Code:", response.status_code)
print("Response:", response.text)
3. Key Points
files Parameter: The files dictionary is used to send the file as multipart/form-data. The tuple format is (filename, file_object, content_type).
- Headers: Most APIs require authentication headers (e.g.,
Authorization: Bearer YOUR_TOKEN). Add them using the headers parameter in requests.post().
- Response Handling: Always check the response status code and content to confirm success or debug issues.
4. Common Use Cases
- Google Calendar API: Use the Events: import endpoint.
- Custom APIs: Refer to the API documentation for the correct endpoint and parameters.