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

OneDrive: Use Application Credentials for Microsoft 365

See more OneDrive Examples

Retains Chilkat.Http's automatic OAuth2 client-credentials support: AuthToken can contain the credential JSON, and Http obtains and caches tokens internally. Load tenant_id, client_id, client_secret, and user_id from private onedrive-app.json. Keep this file outside public web content and source control; use protected configuration in production. Reuse the Http object to benefit from its token cache.

This is for a controlled application accessing Microsoft 365 OneDrive for Business or SharePoint. It is not personal OneDrive authentication and must not embed an application secret in software distributed to the public. Grant application Files.Read.All and administrator consent for this listing request, or use an appropriate supported restricted-access design. A consented permission does not provision a user's OneDrive. Use a tenant-specific authority and explicitly address the user, site, or drive; never /me. App-only tokens have no refresh token.

Follows complete @odata.nextLink URLs, including after empty pages. It validates the Graph host/API path, rejects repeated links, and reports a stop at the demonstration bound of 100 pages. $top is page size, not the total result count. Enumeration is not a transactionally consistent snapshot during concurrent changes.

Permission: Application Files.Read.All for this request.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
set success 0
#  Private file: tenant_id, client_id, client_secret, and user_id (object ID or UPN).
#  The secret VALUE is required, not its secret identifier.
set config [new_CkJsonObject]

CkJsonObject_put_Strict $config 1
set success [CkJsonObject_LoadFile $config "onedrive-app.json"]
if {$success != 1} then {
    puts "Could not load the private application configuration."
    delete_CkJsonObject $config
    exit
}

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

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

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

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

set http [new_CkHttp]

set credentials [new_CkJsonObject]

CkJsonObject_UpdateString $credentials "client_id" [CkJsonObject_stringOf $config "client_id"]
CkJsonObject_UpdateString $credentials "client_secret" [CkJsonObject_stringOf $config "client_secret"]
CkJsonObject_UpdateString $credentials "scope" "https://graph.microsoft.com/.default"
set tokenEndpoint [new_CkStringBuilder]

CkStringBuilder_Append $tokenEndpoint "https://login.microsoftonline.com/"
CkStringBuilder_Append $tokenEndpoint [CkHttp_urlEncode $http [CkJsonObject_stringOf $config "tenant_id"]]
CkStringBuilder_Append $tokenEndpoint "/oauth2/v2.0/token"
CkJsonObject_UpdateString $credentials "token_endpoint" [CkStringBuilder_getAsString $tokenEndpoint]
#  Http recognizes this credential JSON and acquires/caches application tokens internally.
#  Reuse the Http object for subsequent requests; never print the credential JSON.
CkHttp_put_AuthToken $http [CkJsonObject_emit $credentials]
CkHttp_put_RequireSslCertVerify $http 1
CkHttp_put_FollowRedirects $http 0
CkHttp_put_ConnectTimeout $http 20
CkHttp_put_ReadTimeout $http 120
CkHttp_SetRequestHeader $http "Accept" "application/json"
set resp [new_CkHttpResponse]

set result [new_CkJsonObject]

CkJsonObject_put_Strict $result 1
set endpoint [new_CkStringBuilder]

CkStringBuilder_Append $endpoint "https://graph.microsoft.com/v1.0/users/"
CkStringBuilder_Append $endpoint [CkHttp_urlEncode $http [CkJsonObject_stringOf $config "user_id"]]
CkStringBuilder_Append $endpoint "/drives?$select=id,name,driveType,quota&$top=50"
set url [CkStringBuilder_getAsString $endpoint]
set nextLink [new_CkStringBuilder]

set seenLinks [new_CkHashtable]

set pageCount 0
while {expr [$url != ""]  &&  [$pageCount < 100]} {
    CkStringBuilder_SetString $nextLink $url
    if {[CkStringBuilder_StartsWith $nextLink "https://graph.microsoft.com/v1.0/" 1] != 1} then {
        puts "Unexpected pagination host or API version; no request sent."
        delete_CkJsonObject $config
        delete_CkHttp $http
        delete_CkJsonObject $credentials
        delete_CkStringBuilder $tokenEndpoint
        delete_CkHttpResponse $resp
        delete_CkJsonObject $result
        delete_CkStringBuilder $endpoint
        delete_CkStringBuilder $nextLink
        delete_CkHashtable $seenLinks
        exit
    }

    if {[CkHashtable_Contains $seenLinks $url] == 1} then {
        puts "Repeated pagination URL; stopping."
        delete_CkJsonObject $config
        delete_CkHttp $http
        delete_CkJsonObject $credentials
        delete_CkStringBuilder $tokenEndpoint
        delete_CkHttpResponse $resp
        delete_CkJsonObject $result
        delete_CkStringBuilder $endpoint
        delete_CkStringBuilder $nextLink
        delete_CkHashtable $seenLinks
        exit
    }

    CkHashtable_AddInt $seenLinks $url 1
    set success [CkHttp_HttpNoBody $http "GET" $url $resp]
    if {expr [$success != 1]  &&  [[CkHttpResponse_get_StatusCode $resp] == 0]} then {
        puts "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
        delete_CkJsonObject $config
        delete_CkHttp $http
        delete_CkJsonObject $credentials
        delete_CkStringBuilder $tokenEndpoint
        delete_CkHttpResponse $resp
        delete_CkJsonObject $result
        delete_CkStringBuilder $endpoint
        delete_CkStringBuilder $nextLink
        delete_CkHashtable $seenLinks
        exit
    }

    if {[CkHttpResponse_get_StatusCode $resp] != 200} 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]"
        }

        delete_CkJsonObject $config
        delete_CkHttp $http
        delete_CkJsonObject $credentials
        delete_CkStringBuilder $tokenEndpoint
        delete_CkHttpResponse $resp
        delete_CkJsonObject $result
        delete_CkStringBuilder $endpoint
        delete_CkStringBuilder $nextLink
        delete_CkHashtable $seenLinks
        exit
    }

    set success [CkJsonObject_Load $result [CkHttpResponse_bodyStr $resp]]
    if {$success != 1} then {
        puts "Expected a well-formed JSON response."
        delete_CkJsonObject $config
        delete_CkHttp $http
        delete_CkJsonObject $credentials
        delete_CkStringBuilder $tokenEndpoint
        delete_CkHttpResponse $resp
        delete_CkJsonObject $result
        delete_CkStringBuilder $endpoint
        delete_CkStringBuilder $nextLink
        delete_CkHashtable $seenLinks
        exit
    }

    if {[CkJsonObject_JsonTypeOf $result "value"] != 4} then {
        puts "Expected a value array."
        delete_CkJsonObject $config
        delete_CkHttp $http
        delete_CkJsonObject $credentials
        delete_CkStringBuilder $tokenEndpoint
        delete_CkHttpResponse $resp
        delete_CkJsonObject $result
        delete_CkStringBuilder $endpoint
        delete_CkStringBuilder $nextLink
        delete_CkHashtable $seenLinks
        exit
    }

    set i 0
    while {$i < [CkJsonObject_SizeOfArray $result "value"]} {
        CkJsonObject_put_I $result $i
        if {expr [[CkJsonObject_JsonTypeOf $result "value[i].id"] != 1]  ||  [[CkJsonObject_StringOfEquals $result "value[i].id" "" 1] == 1]} then {
            puts "{Expected a nonempty value[i].id in the JSON.}"
            delete_CkJsonObject $config
            delete_CkHttp $http
            delete_CkJsonObject $credentials
            delete_CkStringBuilder $tokenEndpoint
            delete_CkHttpResponse $resp
            delete_CkJsonObject $result
            delete_CkStringBuilder $endpoint
            delete_CkStringBuilder $nextLink
            delete_CkHashtable $seenLinks
            exit
        }

        puts "Drive ID: [CkJsonObject_stringOf $result {value[i].id}]"
        puts "Name: [CkJsonObject_stringOf $result {value[i].name}]"
        puts "Drive type: [CkJsonObject_stringOf $result {value[i].driveType}]"
        #  Quota values can be larger than int. Missing quota fields are not zero.
        if {[CkJsonObject_HasMember $result "value[i].quota.total"] == 1} then {
            puts "Total bytes: [CkJsonObject_stringOf $result {value[i].quota.total}]"
            puts "Remaining bytes: [CkJsonObject_stringOf $result {value[i].quota.remaining}]"
        }

        set i [expr $i + 1]
    }
    set pageCount [expr $pageCount + 1]
    #  A quoted JSON path treats the period in @odata.nextLink literally.
    set nextType [CkJsonObject_JsonTypeOf $result "\"@odata.nextLink\""]
    if {expr [$nextType == -1]  ||  [$nextType == 6]} then {
        set url ""
    }     else {
        if {expr [$nextType != 1]  ||  [[CkJsonObject_StringOfEquals $result "\"@odata.nextLink\"" "" 1] == 1]} then {
            puts "Invalid continuation link; cannot establish completeness."
            delete_CkJsonObject $config
            delete_CkHttp $http
            delete_CkJsonObject $credentials
            delete_CkStringBuilder $tokenEndpoint
            delete_CkHttpResponse $resp
            delete_CkJsonObject $result
            delete_CkStringBuilder $endpoint
            delete_CkStringBuilder $nextLink
            delete_CkHashtable $seenLinks
            exit
        }

        set url [CkJsonObject_stringOf $result "\"@odata.nextLink\""]
    }

}
if {$url != ""} then {
    puts "Stopped at the example's 100-page limit; save the continuation privately to resume."
    delete_CkJsonObject $config
    delete_CkHttp $http
    delete_CkJsonObject $credentials
    delete_CkStringBuilder $tokenEndpoint
    delete_CkHttpResponse $resp
    delete_CkJsonObject $result
    delete_CkStringBuilder $endpoint
    delete_CkStringBuilder $nextLink
    delete_CkHashtable $seenLinks
    exit
}

puts "Completed pages: $pageCount"

delete_CkJsonObject $config
delete_CkHttp $http
delete_CkJsonObject $credentials
delete_CkStringBuilder $tokenEndpoint
delete_CkHttpResponse $resp
delete_CkJsonObject $result
delete_CkStringBuilder $endpoint
delete_CkStringBuilder $nextLink
delete_CkHashtable $seenLinks