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

Outlook Contacts: Create, Rename, or Delete a Contact Folder

See more Outlook Contact Examples

Choose one operation per run. Create (the default) posts a custom folder; an optional parentFolderId creates a child folder. Save the returned ID and use it explicitly for later rename or delete. These are alternatives, not an automatic create-and-delete sequence.

Live changes: rename changes the display name; deleting a folder affects its contacts and child folders. Inspect the selected custom folder and its contents before choosing delete. Do not target the default Contacts folder. The example reads the selected folder before changing it; this GET is not a confirmation dialog or a lock. The ordinary DELETE action returns HTTP 204 without JSON.

Creation records a pending attempt before POST, then saves the returned ID. There is no server idempotency key in this request. An uncertain result blocks a blind retry; reconcile the folder list first. Use private operation files per account and logical operation, and a single writer. Folder names are not unique.

Delegated permission: Contacts.ReadWrite.

Uses Microsoft Graph v1.0 for contacts stored in an Outlook.com or Microsoft 365 mailbox. These are personal mailbox contacts, not Microsoft Entra directory users, organizational contacts (/contacts), or the People API. Obtain a delegated token with the contacts OAuth2 example; the cache is qa_data/tokens/outlookContacts.json. A token for Calendar, SMTP, or another resource without the needed Graph contacts permission is insufficient.

/me requires a signed-in user. An authorized unattended Microsoft 365 application instead needs application permissions and administrator consent, and targets /users/{id-or-UPN}. App-only access does not apply to personal Outlook.com mailboxes. Shared folders require actual sharing rights and Contacts.Read.Shared or Contacts.ReadWrite.Shared delegated consent. The examples target the global cloud.

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 contact 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 contacts authorization example.
-- See Authorize Outlook Contacts with OAuth2 and PKCE.
local token = chilkat.JsonObject.new()
token.strict = true
success = token:load_file("qa_data/tokens/outlookContacts.json")
if not success then
    print("Could not read the private contacts 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 folderId = "YOUR_CUSTOM_CONTACT_FOLDER_ID"
local parentFolderId = ""   -- Optional parent for creating a child folder.
if (action ~= "create") and ((action ~= "rename") and (action ~= "delete")) then
    print("Choose create, rename, or delete.")
    return
end

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

    local receiptPath = "qa_data/outlookContacts/create-folder.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; reconcile 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 folder ID: " .. operation:string_of("id"))
        else
            print("A previous folder creation may have succeeded. Reconcile the folder list before retrying.")
        end

        return
    end

    endpoint:append("https://graph.microsoft.com/v1.0/me/contactFolders")
    if parentFolderId ~= "" then
        endpoint:append("/")
        endpoint:append(http:url_encode(parentFolderId))
        endpoint:append("/childFolders")
    end

    body:update_string("displayName", "Additional contacts")
    operation:update_string("status", "pending")
    operation:update_string("displayName", body:string_of("displayName"))
    operation:update_string("parentFolderId", parentFolderId)
    success = operation:write_file(receiptPath)
    if not success then
        print("Could not record the attempt; no request sent.")
        return
    end

    success = http:http_json("POST", 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 ~= 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")
    print("Created folder ID: " .. result:string_of("id"))
    success = operation:write_file(receiptPath)
    if not success then
        print("Folder created, but receipt save failed. Reconcile the pending attempt before retrying.")
        return
    end

    return
end

-- Supply an explicitly selected custom folder ID. Do not target the default Contacts folder.
endpoint:append("https://graph.microsoft.com/v1.0/me/contactFolders/")
endpoint:append(http:url_encode(folderId))
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

print("Selected folder: " .. result:string_of("displayName"))
if action == "rename" then
    body:update_string("displayName", "Renamed contacts")
    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 folder ID: " .. result:string_of("id"))
else
    -- Live deletion also affects contacts and child folders contained here.
    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("Contact folder deleted (HTTP 204).")
end