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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoToken
    Handle hoHttp
    Variant vResp
    Handle hoResp
    Handle hoResult
    Variant vBody
    Handle hoBody
    Handle hoFac
    String sOperationFile
    Handle hoOperation
    String sTemp1
    Integer iTemp1
    Boolean bTemp1

    Move False To iSuccess

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    Move False To iSuccess
    //  Obtain a delegated Microsoft Graph token using the contacts authorization example.
    //  See Authorize Outlook Contacts with OAuth2 and PKCE.
    Get Create (RefClass(cComChilkatJsonObject)) To hoToken
    If (Not(IsComObjectCreated(hoToken))) Begin
        Send CreateComObject of hoToken
    End
    Set ComStrict Of hoToken To True
    Get ComLoadFile Of hoToken "qa_data/tokens/outlookContacts.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not read the private contacts token cache."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoToken "access_token" To iTemp1
    Get ComStringOfEquals Of hoToken "access_token" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Showln "Expected a nonempty access_token in the JSON."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatHttp)) To hoHttp
    If (Not(IsComObjectCreated(hoHttp))) Begin
        Send CreateComObject of hoHttp
    End
    Get ComStringOf Of hoToken "access_token" To sTemp1
    Set ComAuthToken Of hoHttp To sTemp1
    Set ComRequireSslCertVerify Of hoHttp To True
    Set ComFollowRedirects Of hoHttp To False
    Set ComConnectTimeout Of hoHttp To 20
    Set ComReadTimeout Of hoHttp To 30
    Send ComSetRequestHeader To hoHttp "Accept" "application/json"
    Get Create (RefClass(cComChilkatHttpResponse)) To hoResp
    If (Not(IsComObjectCreated(hoResp))) Begin
        Send CreateComObject of hoResp
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoResult
    If (Not(IsComObjectCreated(hoResult))) Begin
        Send CreateComObject of hoResult
    End
    Set ComStrict Of hoResult To True
    Send ComSetRequestHeader To hoHttp "Prefer" 'IdType="ImmutableId"'
    //  Live creation in the default Contacts folder. This does not send an email or invitation.
    Get Create (RefClass(cComChilkatJsonObject)) To hoBody
    If (Not(IsComObjectCreated(hoBody))) Begin
        Send CreateComObject of hoBody
    End
    Get ComUpdateString Of hoBody "givenName" "Alex" To iSuccess
    Get ComUpdateString Of hoBody "surname" "Example" To iSuccess
    Get ComUpdateString Of hoBody "displayName" "Alex Example" To iSuccess
    Get ComUpdateString Of hoBody "emailAddresses[0].address" "alex@example.com" To iSuccess
    Get ComUpdateString Of hoBody "emailAddresses[0].name" "Alex Example" To iSuccess
    Get ComUpdateString Of hoBody "businessPhones[0]" "+1 202 555 0100" To iSuccess
    Get Create (RefClass(cComCkFileAccess)) To hoFac
    If (Not(IsComObjectCreated(hoFac))) Begin
        Send CreateComObject of hoFac
    End
    Get ComDirEnsureExists Of hoFac "qa_data/outlookContacts" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not create the private operation directory."
        Procedure_Return
    End

    Move "qa_data/outlookContacts/create-contact.json" To sOperationFile
    Get Create (RefClass(cComChilkatJsonObject)) To hoOperation
    If (Not(IsComObjectCreated(hoOperation))) Begin
        Send CreateComObject of hoOperation
    End
    Set ComStrict Of hoOperation To True
    Get ComFileExists Of hoFac sOperationFile To bTemp1
    If (bTemp1 = True) Begin
        Get ComLoadFile Of hoOperation sOperationFile To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not read the previous operation. Reconcile before another attempt."
            Procedure_Return
        End

        Get ComStringOfEquals Of hoOperation "status" "created" True To bTemp1
        If (bTemp1 = True) Begin
            Get ComJsonTypeOf Of hoOperation "id" To iTemp1
            Get ComStringOfEquals Of hoOperation "id" "" True To bTemp1
            If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
                Showln "Expected a nonempty id in the JSON."
                Procedure_Return
            End

            Get ComStringOf Of hoOperation "id" To sTemp1
            Showln "Already created contact ID: " sTemp1
        End
        Else Begin
            Showln "A previous creation may have succeeded. Inspect the contact list and reconcile before retrying."
        End

        Procedure_Return
    End

    //  Contacts have no event-style transactionId. A pending record prevents blind POST retries.
    Get ComUpdateString Of hoOperation "status" "pending" To iSuccess
    Get ComStringOf Of hoBody "displayName" To sTemp1
    Get ComUpdateString Of hoOperation "displayName" sTemp1 To iSuccess
    Get ComStringOf Of hoBody "emailAddresses[0].address" To sTemp1
    Get ComUpdateString Of hoOperation "emailAddress" sTemp1 To iSuccess
    Get ComWriteFile Of hoOperation sOperationFile To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not record the attempt; no request sent."
        Procedure_Return
    End

    Get pvComObject of hoBody to vBody
    Get pvComObject of hoResp to vResp
    Get ComHttpJson Of hoHttp "POST" "https://graph.microsoft.com/v1.0/me/contacts" vBody "application/json" vResp To iSuccess
    //  A false result can still include an HTTP error response.
    Get ComStatusCode Of hoResp To iTemp1
    If ((iSuccess <> True) And (iTemp1 = 0)) Begin
        Showln "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying."
        Procedure_Return
    End

    Get ComStatusCode Of hoResp To iTemp1
    If (iTemp1 <> 201) Begin
        Get ComStatusCode Of hoResp To iTemp1
        Showln "Unexpected HTTP status: " iTemp1
        Get ComGetHeaderField Of hoResp "request-id" To sTemp1
        Showln "Request ID: " sTemp1
        Get ComStatusCode Of hoResp To iTemp1
        If (iTemp1 = 429) Begin
            Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
            Showln "Retry-After: " sTemp1
        End

        Get ComStatusCode Of hoResp To iTemp1
        If (iTemp1 = 401) Begin
            Showln "Refresh the Graph access token or authorize again."
        End

        Procedure_Return
    End

    Get ComBodyStr Of hoResp To sTemp1
    Get ComLoad Of hoResult sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Expected a well-formed JSON response."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "id" To iTemp1
    Get ComStringOfEquals Of hoResult "id" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Showln "Expected a nonempty id in the JSON."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "id" To sTemp1
    Get ComUpdateString Of hoOperation "id" sTemp1 To iSuccess
    Get ComUpdateString Of hoOperation "status" "created" To iSuccess
    //  The contact exists even if saving this receipt fails. Keep this ID for reconciliation.
    Get ComStringOf Of hoResult "id" To sTemp1
    Showln "Created contact ID: " sTemp1
    Get ComWriteFile Of hoOperation sOperationFile To iSuccess
    If (iSuccess <> True) Begin
        Showln "Contact created, but the receipt could not be saved. Reconcile the pending attempt before retrying."
        Procedure_Return
    End

    Showln "Contact receipt saved."


End_Procedure