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

Outlook Contacts: Create a Contact

See more Outlook Contact Examples

Create a contact in the default Contacts folder using delegated Contacts.ReadWrite. The JSON demonstrates names, a display name, an email-address object, and a phone-number array. HTTP 201 confirms creation; save the returned string ID for later reads and updates. Creating a contact does not send a message or invitation.

Live creation: this adds a real mailbox contact. Contacts do not have the event resource's transactionId deduplication feature. The sample records a pending attempt before POST and a receipt after success. Rerunning a completed operation prints the saved ID; an uncertain outcome blocks an automatic repeat POST. Reconcile the contact list first, since a matching name or email does not prove uniqueness. Even a failed local receipt write does not undo server creation. Use a new operation filename only for a deliberately new contact; protect these files per account and use one writer. Production code needs durable operation storage.

To create in a specific folder, use /me/contactFolders/{folderId}/contacts. The folder ID is different from the new contact's ID. Read-only fields such as id, parentFolderId, and changeKey are not included in the request.

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.

Keep contact and folder IDs as case-sensitive strings, together with their mailbox context. These examples request Prefer: IdType="ImmutableId" consistently; such contact IDs remain stable when moved within the same mailbox. Older stored default-format IDs need an intentional migration or fresh retrieval, not string manipulation. URL-encode each ID as a path segment. Display names and email addresses are not unique IDs.

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 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
http:set_request_header("Prefer", "IdType=\"ImmutableId\"")
-- Live creation in the default Contacts folder. This does not send an email or invitation.
local body = chilkat.JsonObject.new()
body:update_string("givenName", "Alex")
body:update_string("surname", "Example")
body:update_string("displayName", "Alex Example")
body:update_string("emailAddresses[0].address", "alex@example.com")
body:update_string("emailAddresses[0].name", "Alex Example")
body:update_string("businessPhones[0]", "+1 202 555 0100")
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 operationFile = "qa_data/outlookContacts/create-contact.json"
local operation = chilkat.JsonObject.new()
operation.strict = true
if fac:file_exists(operationFile) then
    success = operation:load_file(operationFile)
    if not success then
        print("Could not read the previous operation. Reconcile before another attempt.")
        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 contact ID: " .. operation:string_of("id"))
    else
        print("A previous creation may have succeeded. Inspect the contact list and reconcile before retrying.")
    end

    return
end

-- Contacts have no event-style transactionId. A pending record prevents blind POST retries.
operation:update_string("status", "pending")
operation:update_string("displayName", body:string_of("displayName"))
operation:update_string("emailAddress", body:string_of("emailAddresses[0].address"))
success = operation:write_file(operationFile)
if not success then
    print("Could not record the attempt; no request sent.")
    return
end

success = http:http_json("POST", "https://graph.microsoft.com/v1.0/me/contacts", 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")
-- The contact exists even if saving this receipt fails. Keep this ID for reconciliation.
print("Created contact ID: " .. result:string_of("id"))
success = operation:write_file(operationFile)
if not success then
    print("Contact created, but the receipt could not be saved. Reconcile the pending attempt before retrying.")
    return
end

print("Contact receipt saved.")