Sample code for 30+ languages & platforms
DataFlex

SharePoint -- Get Server Form Digest Value

Demonstrates how to get a server form digest value to be placed in the X-RequestDigest HTTP request header for POST, PUT, MERGE, and DELETE requests. A form digest value is typically valid for 1800 seconds (i.e. 30 minutes). This example persists the value to a file, and only requests a new form digest value if the existing one is near expiration.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoFac
    Handle hoXml
    Handle hoDtExpire
    Handle hoDtNow
    String sFormDigestXmlFile
    Integer iTNow
    Integer iTExpire
    Handle hoHttp
    String sSavedAccept
    Variant vResp
    Handle hoResp
    Handle hoXml2
    Integer iTimeoutInSec
    String sTemp1
    Integer iTemp1
    Boolean bTemp1

    Move False To iSuccess

    // This requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // First, let's see if we already have a persisted form digest value
    // that hasn't yet expired.
    Get Create (RefClass(cComCkFileAccess)) To hoFac
    If (Not(IsComObjectCreated(hoFac))) Begin
        Send CreateComObject of hoFac
    End
    Get Create (RefClass(cComChilkatXml)) To hoXml
    If (Not(IsComObjectCreated(hoXml))) Begin
        Send CreateComObject of hoXml
    End

    // My example code (below) persists the form digest XML in this format:
    // 
    // 	<savedFormDigestValue>
    // 	<d:ExpireDateTime>2017-04-12T20:46:39Z</d:ExpireDateTime>
    // 	<d:FormDigestValue>0x3059FFB920651834540F3E6792EA73F5746B302E953FF4E808E485DB1E6C2836C7CF924644995F092453B02A94DE14A7962674B7B16780AF16EAFB8C246BCDC7,12 Apr 2017 17:08:22 -0000</d:FormDigestValue>
    // 	</savedFormDigestValue>
    // 

    Get Create (RefClass(cComCkDateTime)) To hoDtExpire
    If (Not(IsComObjectCreated(hoDtExpire))) Begin
        Send CreateComObject of hoDtExpire
    End
    Get Create (RefClass(cComCkDateTime)) To hoDtNow
    If (Not(IsComObjectCreated(hoDtNow))) Begin
        Send CreateComObject of hoDtNow
    End

    Move "qa_data/sharepoint/savedFormDigestValue.xml" To sFormDigestXmlFile
    Get ComFileExists Of hoFac sFormDigestXmlFile To bTemp1
    If (bTemp1 = True) Begin

        Get ComLoadXmlFile Of hoXml sFormDigestXmlFile To iSuccess

        // Get the expire date/time
        Get ComGetChildContent Of hoXml "d:ExpireDateTime" To sTemp1
        Get ComSetFromTimestamp Of hoDtExpire sTemp1 To iSuccess

        // Get the current date/time
        Get ComSetFromCurrentSystemTime Of hoDtNow To iSuccess

        // Get both times as Unix time values
        Get ComGetAsUnixTime Of hoDtNow False To iTNow
        Get ComGetAsUnixTime Of hoDtExpire False To iTExpire

        // If tNow >= tExpire, then fall through.
        // Otherwise, just use the cached digest value.
        If (iTNow < iTExpire) Begin
            Showln "Cached digest value is not yet expired."
            Get ComGetChildContent Of hoXml "d:FormDigestValue" To sTemp1
            Showln "X-RequestDigest: " sTemp1
            Procedure_Return
        End

    End

    // If we got to this point, the cached digest value either does not exist, or expired.

    Get Create (RefClass(cComChilkatHttp)) To hoHttp
    If (Not(IsComObjectCreated(hoHttp))) Begin
        Send CreateComObject of hoHttp
    End

    // If SharePoint Windows classic authentication is used, then set the 
    // Login, Password, LoginDomain, and NtlmAuth properties.
    Set ComLogin Of hoHttp To "SHAREPOINT_USERNAME"
    Set ComPassword Of hoHttp To "SHAREPOINT_PASSWORD"
    Set ComLoginDomain Of hoHttp To "SHAREPOINT_NTLM_DOMAIN"
    Set ComNtlmAuth Of hoHttp To True

    // The more common case is to use SharePoint Online authentication (via the SPOIDCRL cookie).
    // If so, do not set Login, Password, LoginDomain, and NtlmAuth, and instead
    // establish the cookie as shown at SharePoint Online Authentication

    // When creating, updating, and deleting SharePoint entities, we'll need
    // to first get the server's form digest value to send in the X-RequestDigest header.
    // This can be retrieved by making a POST request with an empty body to
    // http://<site url>/_api/contextinfo and extracting the value of the
    // d:FormDigestValue node in the XML that the contextinfo endpoint returns.

    // Apparently, SharePoint needs an "Accept" request header equal to "application/xml",
    // otherwise SharePoint will return an utterly incomprehensible and useless error message.
    Get ComAccept Of hoHttp To sSavedAccept
    Set ComAccept Of hoHttp To "application/xml"

    // Note: The last argument ("utf-8") is meaningless here because the body is empty.
    Get Create (RefClass(cComChilkatHttpResponse)) To hoResp
    If (Not(IsComObjectCreated(hoResp))) Begin
        Send CreateComObject of hoResp
    End
    Get pvComObject of hoResp to vResp
    Get ComHttpStr Of hoHttp "POST" "https://SHAREPOINT_HTTPS_DOMAIN/_api/contextinfo" "" "utf-8" "application/xml" vResp To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoHttp To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // Restore the default Accept header
    Set ComAccept Of hoHttp To sSavedAccept

    Get ComStatusCode Of hoResp To iTemp1
    If (iTemp1 <> 200) Begin
        // A response status code not equal to 200 indicates failure.
        Get ComStatusCode Of hoResp To iTemp1
        Showln "Response status code = " iTemp1
        Showln "Response body:"
        Get ComBodyStr Of hoResp To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComBodyStr Of hoResp To sTemp1
    Get ComLoadXml Of hoXml sTemp1 To iSuccess

    // The response XML looks like this:

    // <?xml version="1.0" encoding="utf-8" ?>
    // <d:GetContextWebInformation xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml" m:type="SP.ContextWebInformation">
    //     <d:FormDigestTimeoutSeconds m:type="Edm.Int32">1800</d:FormDigestTimeoutSeconds>
    //     <d:FormDigestValue>0x3059FFB920651834540F3E6792EA73F5746B302E953FF4E808E485DB1E6C2836C7CF924644995F092453B02A94DE14A7962674B7B16780AF16EAFB8C246BCDC7,12 Apr 2017 17:08:22 -0000</d:FormDigestValue>
    //     <d:LibraryVersion>15.0.4569.1000</d:LibraryVersion>
    //     <d:SiteFullUrl>https://SHAREPOINT_HTTPS_DOMAIN</d:SiteFullUrl>
    //     <d:SupportedSchemaVersions m:type="Collection(Edm.String)">
    //         <d:element>14.0.0.0</d:element>
    //         <d:element>15.0.0.0</d:element>
    //     </d:SupportedSchemaVersions>
    //     <d:WebFullUrl>https://SHAREPOINT_HTTPS_DOMAIN</d:WebFullUrl>
    // </d:GetContextWebInformation>
    // 

    // Cache the digest value, and also an expiration time.  If this code is run again
    // before the digest expires, we'll just get it from the file.
    Get Create (RefClass(cComChilkatXml)) To hoXml2
    If (Not(IsComObjectCreated(hoXml2))) Begin
        Send CreateComObject of hoXml2
    End

    Set ComTag Of hoXml2 To "savedFormDigestValue"
    Get ComGetChildContent Of hoXml "d:FormDigestValue" To sTemp1
    Send ComNewChild2 To hoXml2 "d:FormDigestValue" sTemp1

    Get ComGetChildIntValue Of hoXml "d:FormDigestTimeoutSeconds" To iTimeoutInSec
    Showln "Timeout in seconds = " iTimeoutInSec

    // Convert this to an expire timestamp.
    // Let's make it expire 30 seconds prior to the actual timeout, just to be safe.
    If (iTimeoutInSec > 30) Begin
        Move (iTimeoutInSec - 30) To iTimeoutInSec
    End

    Get ComSetFromCurrentSystemTime Of hoDtExpire To iSuccess
    Get ComAddSeconds Of hoDtExpire iTimeoutInSec To iSuccess
    Get ComGetAsTimestamp Of hoDtExpire False To sTemp1
    Send ComNewChild2 To hoXml2 "d:ExpireDateTime" sTemp1

    // Persist the digest and expire time to a file.
    Get ComSaveXml Of hoXml2 sFormDigestXmlFile To iSuccess

    Showln "Here is the new form digest value:"
    Get ComGetChildContent Of hoXml "d:FormDigestValue" To sTemp1
    Showln "X-RequestDigest: " sTemp1


End_Procedure