Sample code for 30+ languages & platforms
Tcl 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 Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
set success 0
#  Obtain a delegated Microsoft Graph token using the contacts authorization example.
#  See Authorize Outlook Contacts with OAuth2 and PKCE.
set token [new_CkJsonObject]

CkJsonObject_put_Strict $token 1
set success [CkJsonObject_LoadFile $token "qa_data/tokens/outlookContacts.json"]
if {$success != 1} then {
    puts "Could not read the private contacts token cache."
    delete_CkJsonObject $token
    exit
}

if {expr [[CkJsonObject_JsonTypeOf $token "access_token"] != 1]  ||  [[CkJsonObject_StringOfEquals $token "access_token" "" 1] == 1]} then {
    puts "Expected a nonempty access_token in the JSON."
    delete_CkJsonObject $token
    exit
}

set http [new_CkHttp]

CkHttp_put_AuthToken $http [CkJsonObject_stringOf $token "access_token"]
CkHttp_put_RequireSslCertVerify $http 1
CkHttp_put_FollowRedirects $http 0
CkHttp_put_ConnectTimeout $http 20
CkHttp_put_ReadTimeout $http 30
CkHttp_SetRequestHeader $http "Accept" "application/json"
set resp [new_CkHttpResponse]

set result [new_CkJsonObject]

CkJsonObject_put_Strict $result 1
CkHttp_SetRequestHeader $http "Prefer" "IdType=\"ImmutableId\""
#  Live creation in the default Contacts folder. This does not send an email or invitation.
set body [new_CkJsonObject]

CkJsonObject_UpdateString $body "givenName" "Alex"
CkJsonObject_UpdateString $body "surname" "Example"
CkJsonObject_UpdateString $body "displayName" "Alex Example"
CkJsonObject_UpdateString $body "emailAddresses[0].address" "alex@example.com"
CkJsonObject_UpdateString $body "emailAddresses[0].name" "Alex Example"
CkJsonObject_UpdateString $body "businessPhones[0]" "+1 202 555 0100"
set fac [new_CkFileAccess]

set success [CkFileAccess_DirEnsureExists $fac "qa_data/outlookContacts"]
if {$success != 1} then {
    puts "Could not create the private operation directory."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkJsonObject $body
    delete_CkFileAccess $fac
    exit
}

set operationFile "qa_data/outlookContacts/create-contact.json"
set operation [new_CkJsonObject]

CkJsonObject_put_Strict $operation 1
if {[CkFileAccess_FileExists $fac $operationFile] == 1} then {
    set success [CkJsonObject_LoadFile $operation $operationFile]
    if {$success != 1} then {
        puts "Could not read the previous operation. Reconcile before another attempt."
        delete_CkJsonObject $token
        delete_CkHttp $http
        delete_CkHttpResponse $resp
        delete_CkJsonObject $result
        delete_CkJsonObject $body
        delete_CkFileAccess $fac
        delete_CkJsonObject $operation
        exit
    }

    if {[CkJsonObject_StringOfEquals $operation "status" "created" 1] == 1} then {
        if {expr [[CkJsonObject_JsonTypeOf $operation "id"] != 1]  ||  [[CkJsonObject_StringOfEquals $operation "id" "" 1] == 1]} then {
            puts "Expected a nonempty id in the JSON."
            delete_CkJsonObject $token
            delete_CkHttp $http
            delete_CkHttpResponse $resp
            delete_CkJsonObject $result
            delete_CkJsonObject $body
            delete_CkFileAccess $fac
            delete_CkJsonObject $operation
            exit
        }

        puts "Already created contact ID: [CkJsonObject_stringOf $operation id]"
    }     else {
        puts "A previous creation may have succeeded. Inspect the contact list and reconcile before retrying."
    }

    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkJsonObject $body
    delete_CkFileAccess $fac
    delete_CkJsonObject $operation
    exit
}

#  Contacts have no event-style transactionId. A pending record prevents blind POST retries.
CkJsonObject_UpdateString $operation "status" "pending"
CkJsonObject_UpdateString $operation "displayName" [CkJsonObject_stringOf $body "displayName"]
CkJsonObject_UpdateString $operation "emailAddress" [CkJsonObject_stringOf $body "emailAddresses[0].address"]
set success [CkJsonObject_WriteFile $operation $operationFile]
if {$success != 1} then {
    puts "Could not record the attempt; no request sent."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkJsonObject $body
    delete_CkFileAccess $fac
    delete_CkJsonObject $operation
    exit
}

set success [CkHttp_HttpJson $http "POST" "https://graph.microsoft.com/v1.0/me/contacts" $body "application/json" $resp]
#  A false result can still include an HTTP error response.
if {expr [$success != 1]  &&  [[CkHttpResponse_get_StatusCode $resp] == 0]} then {
    puts "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkJsonObject $body
    delete_CkFileAccess $fac
    delete_CkJsonObject $operation
    exit
}

if {[CkHttpResponse_get_StatusCode $resp] != 201} then {
    puts "Unexpected HTTP status: [CkHttpResponse_get_StatusCode $resp]"
    puts "Request ID: [CkHttpResponse_getHeaderField $resp request-id]"
    if {[CkHttpResponse_get_StatusCode $resp] == 429} then {
        puts "Retry-After: [CkHttpResponse_getHeaderField $resp Retry-After]"
    }

    if {[CkHttpResponse_get_StatusCode $resp] == 401} then {
        puts "Refresh the Graph access token or authorize again."
    }

    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkJsonObject $body
    delete_CkFileAccess $fac
    delete_CkJsonObject $operation
    exit
}

set success [CkJsonObject_Load $result [CkHttpResponse_bodyStr $resp]]
if {$success != 1} then {
    puts "Expected a well-formed JSON response."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkJsonObject $body
    delete_CkFileAccess $fac
    delete_CkJsonObject $operation
    exit
}

if {expr [[CkJsonObject_JsonTypeOf $result "id"] != 1]  ||  [[CkJsonObject_StringOfEquals $result "id" "" 1] == 1]} then {
    puts "Expected a nonempty id in the JSON."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkJsonObject $body
    delete_CkFileAccess $fac
    delete_CkJsonObject $operation
    exit
}

CkJsonObject_UpdateString $operation "id" [CkJsonObject_stringOf $result "id"]
CkJsonObject_UpdateString $operation "status" "created"
#  The contact exists even if saving this receipt fails. Keep this ID for reconciliation.
puts "Created contact ID: [CkJsonObject_stringOf $result id]"
set success [CkJsonObject_WriteFile $operation $operationFile]
if {$success != 1} then {
    puts "Contact created, but the receipt could not be saved. Reconcile the pending attempt before retrying."
    delete_CkJsonObject $token
    delete_CkHttp $http
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkJsonObject $body
    delete_CkFileAccess $fac
    delete_CkJsonObject $operation
    exit
}

puts "Contact receipt saved."

delete_CkJsonObject $token
delete_CkHttp $http
delete_CkHttpResponse $resp
delete_CkJsonObject $result
delete_CkJsonObject $body
delete_CkFileAccess $fac
delete_CkJsonObject $operation