Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.6.0+

Outlook Calendar: Create, Rename, or Delete a Secondary Calendar

See more Outlook Calendar Examples

Select one operation: create (the default), rename, or delete. Creation returns an opaque calendar ID to save with the application record. To rename or delete, explicitly set that ID and change action. The example retrieves the calendar first and refuses to operate on the default calendar. Names are display labels and are not unique identifiers.

Live changes: rename changes the calendar name; delete removes the secondary calendar and its events. The operations are alternatives, not a create/rename/delete sequence. Never delete a calendar merely to clean up an example without checking its contents and ownership. Deletion succeeds with HTTP 204 and no JSON body.

Unlike event creation, calendar creation has no transactionId deduplication property. A private pending record is saved before sending; an uncertain outcome or failed receipt write blocks automatic repeat creation. Inspect the calendar list and reconcile that attempt first. Keep operation files per account, with a single writer. Use a new filename only for a deliberately new calendar. A completed receipt prevents accidental creation when rerunning the sample.

Delegated permission: Calendars.ReadWrite.

Uses Microsoft Graph v1.0 in the global cloud with a delegated access token saved by the calendar OAuth2 example. Both personal Outlook.com accounts and Microsoft 365 work/school accounts with a mailbox can use this flow. The app registration must support the selected account type. A token for SMTP/IMAP/POP or another API is not a Graph token.

/me means the signed-in user and requires delegated authentication. An unattended Microsoft 365 service instead needs application permissions and administrator consent, and addresses an explicit mailbox through /users/{id-or-userPrincipalName}. That client-credentials flow does not apply to personal Outlook.com accounts. These samples target the global cloud; national clouds use different authority and Graph hosts.

HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and calendar data private.

Microsoft documentation

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Obtain a delegated Microsoft Graph token using the calendar authorization example.
-- See Authorize Outlook Calendar with OAuth2 and PKCE.
local token = chilkat.JsonObject.new()
token.strict = true
success = token:load_file("qa_data/tokens/outlookCalendar.json")
if not success then
    print("Could not read the private calendar token cache.")
    return
end

if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
    print("Expected a nonempty access_token in the JSON.")
    return
end

local http = chilkat.Http.new()
http.auth_token = token:string_of("access_token")
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 30
http:set_request_header("Accept", "application/json")
local resp = chilkat.HttpResponse.new()
local result = chilkat.JsonObject.new()
result.strict = true
local action = "create"   -- Choose create, rename, or delete.
local calendarId = "YOUR_SECONDARY_CALENDAR_ID"
if (action ~= "create") and ((action ~= "rename") and (action ~= "delete")) then
    print("Choose create, rename, or delete.")
    return
end

local body = chilkat.JsonObject.new()
local fac = chilkat.FileAccess.new()
if action == "create" then
    success = fac:dir_ensure_exists("qa_data/outlookCalendar")
    if not success then
        print("Could not create the private operation directory.")
        return
    end

    local receiptPath = "qa_data/outlookCalendar/secondary-calendar.json"
    local operation = chilkat.JsonObject.new()
    operation.strict = true
    if fac:file_exists(receiptPath) then
        success = operation:load_file(receiptPath)
        if not success then
            print("Could not read the previous operation; inspect it before retrying.")
            return
        end

        if operation:string_of_equals("status", "created", true) then
            if (operation:json_type_of("id") ~= 1) or (operation:string_of_equals("id", "", true)) then
                print("Expected a nonempty id in the JSON.")
                return
            end

            print("Already created calendar ID: " .. operation:string_of("id"))
        else
            print("Creation may already have occurred. Reconcile the calendar list before starting another operation.")
        end

        return
    end

    body:update_string("name", "Secondary calendar")
    operation:update_string("status", "pending")
    operation:update_string("name", body:string_of("name"))
    -- Calendar creation has no event transactionId. Record an attempt before sending.
    success = operation:write_file(receiptPath)
    if not success then
        print("Could not record the creation attempt; no request sent.")
        return
    end

    success = http:http_json("POST", "https://graph.microsoft.com/v1.0/me/calendars", body, "application/json", resp)
    -- A false result can still include an HTTP error response.
    if (not success) and (resp.status_code == 0) then
        print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
        return
    end

    if resp.status_code ~= 201 then
        print("Unexpected HTTP status: " .. resp.status_code)
        print("Request ID: " .. resp:get_header_field("request-id"))
        if resp.status_code == 429 then
            print("Retry-After: " .. resp:get_header_field("Retry-After"))
        end

        if resp.status_code == 401 then
            print("Refresh the Graph access token or authorize again.")
        end

        return
    end

    success = result:load(resp.body_str)
    if not success then
        print("Expected a well-formed JSON response.")
        return
    end

    if (result:json_type_of("id") ~= 1) or (result:string_of_equals("id", "", true)) then
        print("Expected a nonempty id in the JSON.")
        return
    end

    operation:update_string("id", result:string_of("id"))
    operation:update_string("status", "created")
    success = operation:write_file(receiptPath)
    if not success then
        print("Could not save the receipt. Reconcile the pending attempt before retrying.")
        return
    end

    print("Created calendar ID: " .. result:string_of("id"))
    return
end

-- Use the saved ID for a deliberately selected secondary calendar.
local endpoint = chilkat.StringBuilder.new()
endpoint:append("https://graph.microsoft.com/v1.0/me/calendars/")
endpoint:append(http:url_encode(calendarId))
success = http:http_no_body("GET", endpoint:get_as_string(), resp)
-- A false result can still include an HTTP error response.
if (not success) and (resp.status_code == 0) then
    print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
    return
end

if resp.status_code ~= 200 then
    print("Unexpected HTTP status: " .. resp.status_code)
    print("Request ID: " .. resp:get_header_field("request-id"))
    if resp.status_code == 429 then
        print("Retry-After: " .. resp:get_header_field("Retry-After"))
    end

    if resp.status_code == 401 then
        print("Refresh the Graph access token or authorize again.")
    end

    return
end

success = result:load(resp.body_str)
if not success then
    print("Expected a well-formed JSON response.")
    return
end

if (result:json_type_of("id") ~= 1) or (result:string_of_equals("id", "", true)) then
    print("Expected a nonempty id in the JSON.")
    return
end

if result:json_type_of("isDefaultCalendar") ~= 5 then
    print("Expected isDefaultCalendar in the calendar response.")
    return
end

if result:bool_of("isDefaultCalendar") then
    print("This example operates only on secondary calendars.")
    return
end

if action == "rename" then
    body:update_string("name", "Renamed calendar")
    success = http:http_json("PATCH", endpoint:get_as_string(), body, "application/json", resp)
    -- A false result can still include an HTTP error response.
    if (not success) and (resp.status_code == 0) then
        print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
        return
    end

    if resp.status_code ~= 200 then
        print("Unexpected HTTP status: " .. resp.status_code)
        print("Request ID: " .. resp:get_header_field("request-id"))
        if resp.status_code == 429 then
            print("Retry-After: " .. resp:get_header_field("Retry-After"))
        end

        if resp.status_code == 401 then
            print("Refresh the Graph access token or authorize again.")
        end

        return
    end

    success = result:load(resp.body_str)
    if not success then
        print("Expected a well-formed JSON response.")
        return
    end

    if (result:json_type_of("id") ~= 1) or (result:string_of_equals("id", "", true)) then
        print("Expected a nonempty id in the JSON.")
        return
    end

    print("Renamed calendar ID: " .. result:string_of("id"))
else
    -- Live deletion removes this secondary calendar and its events.
    success = http:http_no_body("DELETE", endpoint:get_as_string(), resp)
    -- A false result can still include an HTTP error response.
    if (not success) and (resp.status_code == 0) then
        print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
        return
    end

    if resp.status_code ~= 204 then
        print("Unexpected HTTP status: " .. resp.status_code)
        print("Request ID: " .. resp:get_header_field("request-id"))
        if resp.status_code == 429 then
            print("Retry-After: " .. resp:get_header_field("Retry-After"))
        end

        if resp.status_code == 401 then
            print("Refresh the Graph access token or authorize again.")
        end

        return
    end

    print("Secondary calendar deleted (HTTP 204).")
end