Sample code for 30+ languages & platforms
Swift

Download a File from a SharePoint Documents Library

See more SharePoint Examples

This example shows how to use Chilkat's HttpCurl class to download a file from the root of a SharePoint Documents document library. The example demonstrates how HttpCurl automatically resolves the SharePoint site name to a site ID, finds the drive ID for the Documents library, locates the file by name, and then downloads the file content using Microsoft Graph.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example downloads a file named "hamlet.json" from the root of the SharePoint
    // Documents document library.
    // 
    // The example demonstrates how HttpCurl can automatically resolve all of the
    // information needed to locate and download a file:
    // 
    //   site_name            -> site_id
    //   site_id              -> document_library_id
    //   document_library_id  -> file_id
    //   file_id              -> file content
    // 
    // The application only provides the SharePoint site name and the desired
    // filename.  HttpCurl automatically executes the required Microsoft Graph
    // requests to obtain the remaining values.

    success = false

    // --------------------------------------------------------------------------------------------------------
    // Before running this example, create an Azure App Registration and grant it
    // the Microsoft Graph permissions required to access SharePoint.
    // 
    // The application will authenticate using OAuth2 Client Credentials.
    // See:
    // How to Create SharePoint App Registration for OAuth 2.0 Client Credentials
    // --------------------------------------------------------------------------------------------------------

    // Build a JSON authentication configuration.
    // HttpCurl will use this information to automatically obtain OAuth2 access tokens.
    let jsonAuth = CkoJsonObject()!

    // Enable secret lookup.
    // 
    // Instead of hard-coding sensitive values such as the client ID,
    // client secret, and token endpoint, secret specification strings
    // are used.  Chilkat automatically retrieves the actual values from
    // Windows Credential Manager (Windows) or Apple Keychain (macOS).
    // 
    // See:
    // Secret Specification Strings
    jsonAuth.enableSecrets = true

    success = jsonAuth.updateString(jsonPath: "oauth2.client_id", value: "!!sharepoint|oauth2|client_id")
    if success == true {
        success = jsonAuth.updateString(jsonPath: "oauth2.client_secret", value: "!!sharepoint|oauth2|client_secret")
    }

    if success == true {
        success = jsonAuth.updateString(jsonPath: "oauth2.token_endpoint", value: "!!sharepoint|oauth2|token_endpoint")
    }

    if success == false {
        print("\(jsonAuth.lastErrorText!)")
        return
    }

    // Request Microsoft Graph permissions that were granted to the application.
    jsonAuth.updateString(jsonPath: "oauth2.scope", value: "https://graph.microsoft.com/.default")

    // ---------------------------------------------------------------------------------------------------

    let curl = CkoHttpCurl()!

    // Associate the OAuth2 configuration with HttpCurl.
    // 
    // When the request is executed, Chilkat automatically obtains an access token
    // if needed and adds the Authorization: Bearer header to the HTTP request.
    curl.setAuth(json: jsonAuth)

    // Define values that are already known.
    // 
    // These variables are referenced in curl commands using
    // {{variable_name}} substitution syntax.
    curl.setVar(varName: "sharepoint_hostname", varValue: "example.sharepoint.com")
    curl.setVar(varName: "site_name", varValue: "test")

    // The first step is to obtain the Microsoft Graph site ID.
    // 
    // The application only knows the SharePoint site name, so define
    // a function that can retrieve the site information.
    curl.addFunction(funcName: "getSite", curl: "GET https://graph.microsoft.com/v1.0/sites/root:/sites/{{site_name}}")

    // Extract the site's ID and store it in the HttpCurl variable named site_id.
    curl.addOutput(funcName: "getSite", jsonPath: "id", varName: "site_id")

    // The next step is to find the Documents document library.
    // 
    // Microsoft Graph refers to document libraries as "drives".
    curl.addFunction(funcName: "getDrives", curl: "GET https://graph.microsoft.com/v1.0/sites/{{site_id}}/drives")

    // Search the returned drives for the one named "Documents"
    // and save its drive ID in the document_library_id variable.
    curl.addOutput2(funcName: "getDrives", arrayPath: "value", wherePath: "name", whereValue: "Documents", caseSensitive: true, subPath: "id", varName: "document_library_id")

    // Now list the contents of the Documents document library.
    curl.addFunction(funcName: "getFiles", curl: "GET https://graph.microsoft.com/v1.0/sites/{{site_id}}/drives/{{document_library_id}}/root/children")

    // Search the returned files for an item named "hamlet.json"
    // and save its Microsoft Graph item ID in the file_id variable.
    curl.addOutput2(funcName: "getFiles", arrayPath: "value", wherePath: "name", whereValue: "hamlet.json", caseSensitive: true, subPath: "id", varName: "file_id")

    // This is the target request.
    // 
    // GET -L https://graph.microsoft.com/v1.0/drives/{{document_library_id}}/items/{{file_id}}/content
    // 
    // The /content endpoint returns the actual contents of the file.
    // 
    // The -L option instructs HttpCurl to follow the redirect returned by
    // Microsoft Graph.  The Graph API typically responds with a redirect
    // to the actual file download URL.
    var curlCommand: String? = "GET -L https://graph.microsoft.com/v1.0/drives/{{document_library_id}}/items/{{file_id}}/content"

    // Execute the request.
    // 
    // HttpCurl examines the target request and determines that both
    // document_library_id and file_id are required.
    // 
    // To obtain these values, it automatically builds and executes
    // the following dependency chain:
    // 
    //   1) getSite      -> site_id
    //   2) getDrives    -> document_library_id
    //   3) getFiles     -> file_id
    //   4) download     -> file content
    // 
    // The final response returned by DoYourThing is the downloaded
    // file content from the target request.
    success = curl.doYourThing(targetCurl: curlCommand)
    if success == false {
        print("\(curl.lastErrorText!)")
        return
    }

    // A successful Graph response should return HTTP 200.
    // Any other status code typically indicates an authentication,
    // permission, site lookup, document library lookup, or file lookup error.
    var statusCode: Int = curl.statusCode.intValue
    if statusCode != 200 {
        print("\(curl.responseBodyStr!)")
        print("status code = \(statusCode)")
        return
    }

    // The response body contains the contents of the downloaded file.
    let sbFileContents = CkoStringBuilder()!
    curl.getResponseSb(sb: sbFileContents)

    // Optionally save the downloaded content to a local file.
    // 
    // The third argument controls whether the file is appended.
    // Passing ckfalse causes the file to be overwritten if it already exists.
    success = sbFileContents.writeFile(path: "c:/temp/hamlet.json", charset: "utf-8", emitBom: false)
    if success == false {
        print("\(sbFileContents.lastErrorText!)")
        return
    }

    print("Success.")

}