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

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
#  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 = Chilkat::CkJsonObject.new()
config.put_Strict(true)
success = config.LoadFile("onedrive-app.json")
if (success != true)
    print "Could not load the private application configuration." + "\n";
    exit
end

if ((config.JsonTypeOf("tenant_id") != 1) or (config.StringOfEquals("tenant_id","",true) == true))
    print "Expected a nonempty tenant_id in the JSON." + "\n";
    exit
end

if ((config.JsonTypeOf("client_id") != 1) or (config.StringOfEquals("client_id","",true) == true))
    print "Expected a nonempty client_id in the JSON." + "\n";
    exit
end

if ((config.JsonTypeOf("client_secret") != 1) or (config.StringOfEquals("client_secret","",true) == true))
    print "Expected a nonempty client_secret in the JSON." + "\n";
    exit
end

if ((config.JsonTypeOf("user_id") != 1) or (config.StringOfEquals("user_id","",true) == true))
    print "Expected a nonempty user_id in the JSON." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
credentials = Chilkat::CkJsonObject.new()
credentials.UpdateString("client_id",config.stringOf("client_id"))
credentials.UpdateString("client_secret",config.stringOf("client_secret"))
credentials.UpdateString("scope","https://graph.microsoft.com/.default")
tokenEndpoint = Chilkat::CkStringBuilder.new()
tokenEndpoint.Append("https://login.microsoftonline.com/")
tokenEndpoint.Append(http.urlEncode(config.stringOf("tenant_id")))
tokenEndpoint.Append("/oauth2/v2.0/token")
credentials.UpdateString("token_endpoint",tokenEndpoint.getAsString())
#  Http recognizes this credential JSON and acquires/caches application tokens internally.
#  Reuse the Http object for subsequent requests; never print the credential JSON.
http.put_AuthToken(credentials.emit())
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
http.put_ConnectTimeout(20)
http.put_ReadTimeout(120)
http.SetRequestHeader("Accept","application/json")
resp = Chilkat::CkHttpResponse.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("https://graph.microsoft.com/v1.0/users/")
endpoint.Append(http.urlEncode(config.stringOf("user_id")))
endpoint.Append("/drives?$select=id,name,driveType,quota&$top=50")
url = endpoint.getAsString()
nextLink = Chilkat::CkStringBuilder.new()
seenLinks = Chilkat::CkHashtable.new()
pageCount = 0
while ((url != "") and (pageCount < 100))
    nextLink.SetString(url)
    if (nextLink.StartsWith("https://graph.microsoft.com/v1.0/",true) != true)
        print "Unexpected pagination host or API version; no request sent." + "\n";
        exit
    end

    if (seenLinks.Contains(url) == true)
        print "Repeated pagination URL; stopping." + "\n";
        exit
    end

    seenLinks.AddInt(url,1)
    success = http.HttpNoBody("GET",url,resp)
    if ((success != true) and (resp.get_StatusCode() == 0))
        print "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying." + "\n";
        exit
    end

    if ((resp.get_StatusCode() != 200))
        print "Unexpected HTTP status: " + resp.get_StatusCode().to_s() + "\n";
        print "Request ID: " + resp.getHeaderField("request-id") + "\n";
        if (resp.get_StatusCode() == 429)
            print "Retry-After: " + resp.getHeaderField("Retry-After") + "\n";
        end

        exit
    end

    success = result.Load(resp.bodyStr())
    if (success != true)
        print "Expected a well-formed JSON response." + "\n";
        exit
    end

    if (result.JsonTypeOf("value") != 4)
        print "Expected a value array." + "\n";
        exit
    end

    i = 0
    while (i < result.SizeOfArray("value"))
        result.put_I(i)
        if ((result.JsonTypeOf("value[i].id") != 1) or (result.StringOfEquals("value[i].id","",true) == true))
            print "Expected a nonempty value[i].id in the JSON." + "\n";
            exit
        end

        print "Drive ID: " + result.stringOf("value[i].id") + "\n";
        print "Name: " + result.stringOf("value[i].name") + "\n";
        print "Drive type: " + result.stringOf("value[i].driveType") + "\n";
        #  Quota values can be larger than int. Missing quota fields are not zero.
        if (result.HasMember("value[i].quota.total") == true)
            print "Total bytes: " + result.stringOf("value[i].quota.total") + "\n";
            print "Remaining bytes: " + result.stringOf("value[i].quota.remaining") + "\n";
        end

        i = i + 1
    end
    pageCount = pageCount + 1
    #  A quoted JSON path treats the period in @odata.nextLink literally.
    nextType = result.JsonTypeOf("\"@odata.nextLink\"")
    if ((nextType == -1) or (nextType == 6))
        url = ""
    else
        if ((nextType != 1) or (result.StringOfEquals("\"@odata.nextLink\"","",true) == true))
            print "Invalid continuation link; cannot establish completeness." + "\n";
            exit
        end

        url = result.stringOf("\"@odata.nextLink\"")
    end

end
if (url != "")
    print "Stopped at the example's 100-page limit; save the continuation privately to resume." + "\n";
    exit
end

print "Completed pages: " + pageCount.to_s() + "\n";