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

PureBasic
IncludeFile "CkHttpResponse.pb"
IncludeFile "CkHttp.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkHashtable.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.
    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.
    config.i = CkJsonObject::ckCreate()
    If config.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkStrict(config, 1)
    success = CkJsonObject::ckLoadFile(config,"onedrive-app.json")
    If success <> 1
        Debug "Could not load the private application configuration."
        CkJsonObject::ckDispose(config)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(config,"tenant_id") <> 1) OR (CkJsonObject::ckStringOfEquals(config,"tenant_id","",1) = 1)
        Debug "Expected a nonempty tenant_id in the JSON."
        CkJsonObject::ckDispose(config)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(config,"client_id") <> 1) OR (CkJsonObject::ckStringOfEquals(config,"client_id","",1) = 1)
        Debug "Expected a nonempty client_id in the JSON."
        CkJsonObject::ckDispose(config)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(config,"client_secret") <> 1) OR (CkJsonObject::ckStringOfEquals(config,"client_secret","",1) = 1)
        Debug "Expected a nonempty client_secret in the JSON."
        CkJsonObject::ckDispose(config)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(config,"user_id") <> 1) OR (CkJsonObject::ckStringOfEquals(config,"user_id","",1) = 1)
        Debug "Expected a nonempty user_id in the JSON."
        CkJsonObject::ckDispose(config)
        ProcedureReturn
    EndIf

    http.i = CkHttp::ckCreate()
    If http.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    credentials.i = CkJsonObject::ckCreate()
    If credentials.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::ckUpdateString(credentials,"client_id",CkJsonObject::ckStringOf(config,"client_id"))
    CkJsonObject::ckUpdateString(credentials,"client_secret",CkJsonObject::ckStringOf(config,"client_secret"))
    CkJsonObject::ckUpdateString(credentials,"scope","https://graph.microsoft.com/.default")
    tokenEndpoint.i = CkStringBuilder::ckCreate()
    If tokenEndpoint.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(tokenEndpoint,"https://login.microsoftonline.com/")
    CkStringBuilder::ckAppend(tokenEndpoint,CkHttp::ckUrlEncode(http,CkJsonObject::ckStringOf(config,"tenant_id")))
    CkStringBuilder::ckAppend(tokenEndpoint,"/oauth2/v2.0/token")
    CkJsonObject::ckUpdateString(credentials,"token_endpoint",CkStringBuilder::ckGetAsString(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::setCkAuthToken(http, CkJsonObject::ckEmit(credentials))
    CkHttp::setCkRequireSslCertVerify(http, 1)
    CkHttp::setCkFollowRedirects(http, 0)
    CkHttp::setCkConnectTimeout(http, 20)
    CkHttp::setCkReadTimeout(http, 120)
    CkHttp::ckSetRequestHeader(http,"Accept","application/json")
    resp.i = CkHttpResponse::ckCreate()
    If resp.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    result.i = CkJsonObject::ckCreate()
    If result.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkStrict(result, 1)
    endpoint.i = CkStringBuilder::ckCreate()
    If endpoint.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(endpoint,"https://graph.microsoft.com/v1.0/users/")
    CkStringBuilder::ckAppend(endpoint,CkHttp::ckUrlEncode(http,CkJsonObject::ckStringOf(config,"user_id")))
    CkStringBuilder::ckAppend(endpoint,"/drives?$select=id,name,driveType,quota&$top=50")
    url.s = CkStringBuilder::ckGetAsString(endpoint)
    nextLink.i = CkStringBuilder::ckCreate()
    If nextLink.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    seenLinks.i = CkHashtable::ckCreate()
    If seenLinks.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    pageCount.i = 0
    While ((url <> "") AND (pageCount < 100))
        CkStringBuilder::ckSetString(nextLink,url)
        If CkStringBuilder::ckStartsWith(nextLink,"https://graph.microsoft.com/v1.0/",1) <> 1
            Debug "Unexpected pagination host or API version; no request sent."
            CkJsonObject::ckDispose(config)
            CkHttp::ckDispose(http)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(tokenEndpoint)
            CkHttpResponse::ckDispose(resp)
            CkJsonObject::ckDispose(result)
            CkStringBuilder::ckDispose(endpoint)
            CkStringBuilder::ckDispose(nextLink)
            CkHashtable::ckDispose(seenLinks)
            ProcedureReturn
        EndIf

        If CkHashtable::ckContains(seenLinks,url) = 1
            Debug "Repeated pagination URL; stopping."
            CkJsonObject::ckDispose(config)
            CkHttp::ckDispose(http)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(tokenEndpoint)
            CkHttpResponse::ckDispose(resp)
            CkJsonObject::ckDispose(result)
            CkStringBuilder::ckDispose(endpoint)
            CkStringBuilder::ckDispose(nextLink)
            CkHashtable::ckDispose(seenLinks)
            ProcedureReturn
        EndIf

        CkHashtable::ckAddInt(seenLinks,url,1)
        success = CkHttp::ckHttpNoBody(http,"GET",url,resp)
        If (success <> 1) AND (CkHttpResponse::ckStatusCode(resp) = 0)
            Debug "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
            CkJsonObject::ckDispose(config)
            CkHttp::ckDispose(http)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(tokenEndpoint)
            CkHttpResponse::ckDispose(resp)
            CkJsonObject::ckDispose(result)
            CkStringBuilder::ckDispose(endpoint)
            CkStringBuilder::ckDispose(nextLink)
            CkHashtable::ckDispose(seenLinks)
            ProcedureReturn
        EndIf

        If (CkHttpResponse::ckStatusCode(resp) <> 200)
            Debug "Unexpected HTTP status: " + Str(CkHttpResponse::ckStatusCode(resp))
            Debug "Request ID: " + CkHttpResponse::ckGetHeaderField(resp,"request-id")
            If CkHttpResponse::ckStatusCode(resp) = 429
                Debug "Retry-After: " + CkHttpResponse::ckGetHeaderField(resp,"Retry-After")
            EndIf

            CkJsonObject::ckDispose(config)
            CkHttp::ckDispose(http)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(tokenEndpoint)
            CkHttpResponse::ckDispose(resp)
            CkJsonObject::ckDispose(result)
            CkStringBuilder::ckDispose(endpoint)
            CkStringBuilder::ckDispose(nextLink)
            CkHashtable::ckDispose(seenLinks)
            ProcedureReturn
        EndIf

        success = CkJsonObject::ckLoad(result,CkHttpResponse::ckBodyStr(resp))
        If success <> 1
            Debug "Expected a well-formed JSON response."
            CkJsonObject::ckDispose(config)
            CkHttp::ckDispose(http)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(tokenEndpoint)
            CkHttpResponse::ckDispose(resp)
            CkJsonObject::ckDispose(result)
            CkStringBuilder::ckDispose(endpoint)
            CkStringBuilder::ckDispose(nextLink)
            CkHashtable::ckDispose(seenLinks)
            ProcedureReturn
        EndIf

        If CkJsonObject::ckJsonTypeOf(result,"value") <> 4
            Debug "Expected a value array."
            CkJsonObject::ckDispose(config)
            CkHttp::ckDispose(http)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(tokenEndpoint)
            CkHttpResponse::ckDispose(resp)
            CkJsonObject::ckDispose(result)
            CkStringBuilder::ckDispose(endpoint)
            CkStringBuilder::ckDispose(nextLink)
            CkHashtable::ckDispose(seenLinks)
            ProcedureReturn
        EndIf

        i.i = 0
        While (i < CkJsonObject::ckSizeOfArray(result,"value"))
            CkJsonObject::setCkI(result, i)
            If (CkJsonObject::ckJsonTypeOf(result,"value[i].id") <> 1) OR (CkJsonObject::ckStringOfEquals(result,"value[i].id","",1) = 1)
                Debug "Expected a nonempty value[i].id in the JSON."
                CkJsonObject::ckDispose(config)
                CkHttp::ckDispose(http)
                CkJsonObject::ckDispose(credentials)
                CkStringBuilder::ckDispose(tokenEndpoint)
                CkHttpResponse::ckDispose(resp)
                CkJsonObject::ckDispose(result)
                CkStringBuilder::ckDispose(endpoint)
                CkStringBuilder::ckDispose(nextLink)
                CkHashtable::ckDispose(seenLinks)
                ProcedureReturn
            EndIf

            Debug "Drive ID: " + CkJsonObject::ckStringOf(result,"value[i].id")
            Debug "Name: " + CkJsonObject::ckStringOf(result,"value[i].name")
            Debug "Drive type: " + CkJsonObject::ckStringOf(result,"value[i].driveType")
            ;  Quota values can be larger than int. Missing quota fields are not zero.
            If CkJsonObject::ckHasMember(result,"value[i].quota.total") = 1
                Debug "Total bytes: " + CkJsonObject::ckStringOf(result,"value[i].quota.total")
                Debug "Remaining bytes: " + CkJsonObject::ckStringOf(result,"value[i].quota.remaining")
            EndIf

            i = i + 1
        Wend
        pageCount = pageCount + 1
        ;  A quoted JSON path treats the period in @odata.nextLink literally.
        nextType.i = CkJsonObject::ckJsonTypeOf(result,Chr(34) + "@odata.nextLink" + Chr(34))
        If (nextType = -1) OR (nextType = 6)
            url = ""
        Else
            If (nextType <> 1) OR (CkJsonObject::ckStringOfEquals(result,Chr(34) + "@odata.nextLink" + Chr(34),"",1) = 1)
                Debug "Invalid continuation link; cannot establish completeness."
                CkJsonObject::ckDispose(config)
                CkHttp::ckDispose(http)
                CkJsonObject::ckDispose(credentials)
                CkStringBuilder::ckDispose(tokenEndpoint)
                CkHttpResponse::ckDispose(resp)
                CkJsonObject::ckDispose(result)
                CkStringBuilder::ckDispose(endpoint)
                CkStringBuilder::ckDispose(nextLink)
                CkHashtable::ckDispose(seenLinks)
                ProcedureReturn
            EndIf

            url = CkJsonObject::ckStringOf(result,Chr(34) + "@odata.nextLink" + Chr(34))
        EndIf

    Wend
    If url <> ""
        Debug "Stopped at the example's 100-page limit; save the continuation privately to resume."
        CkJsonObject::ckDispose(config)
        CkHttp::ckDispose(http)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(tokenEndpoint)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(result)
        CkStringBuilder::ckDispose(endpoint)
        CkStringBuilder::ckDispose(nextLink)
        CkHashtable::ckDispose(seenLinks)
        ProcedureReturn
    EndIf

    Debug "Completed pages: " + Str(pageCount)


    CkJsonObject::ckDispose(config)
    CkHttp::ckDispose(http)
    CkJsonObject::ckDispose(credentials)
    CkStringBuilder::ckDispose(tokenEndpoint)
    CkHttpResponse::ckDispose(resp)
    CkJsonObject::ckDispose(result)
    CkStringBuilder::ckDispose(endpoint)
    CkStringBuilder::ckDispose(nextLink)
    CkHashtable::ckDispose(seenLinks)


    ProcedureReturn
EndProcedure