Sample code for 30+ languages & platforms
Swift

curl with OAuth2 Client Credentials

See more CURL Examples

This example shows how to run a simple CURL command with an OAuth2 access token for authorization. We use CURL to retrieve a SharePoint site ID, and Chilkat automatically fetches the OAuth2 access token using the provided credentials.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example will run the following curl command

    // curl -X GET "https://graph.microsoft.com/v1.0/sites/{{sharepoint_hostname}}:/sites/{{site_name}}" \
    //   -H "Authorization: Bearer ACCESS_TOKEN" \
    //   -H "Accept: application/json"

    let sb = CkoStringBuilder()!
    sb.appendLn(str: "curl -X GET \"https://graph.microsoft.com/v1.0/sites/{{sharepoint_hostname}}:/sites/{{site_name}}\" \\")
    sb.appendLn(str: "  -H \"Authorization: Bearer ACCESS_TOKEN\" \\")
    sb.appendLn(str: "  -H \"Accept: application/json\"")

    // Build the JSON that provides information for getting the OAuth2 access token using the OAuth2 client credentials flow.
    let jsonOAuth2 = CkoJsonObject()!

    jsonOAuth2.updateString(jsonPath: "oauth2.client_id", value: "CLIENT_ID")
    jsonOAuth2.updateString(jsonPath: "oauth2.client_secret", value: "CLIENT_SECRET")
    jsonOAuth2.updateString(jsonPath: "oauth2.scope", value: "https://graph.microsoft.com/.default")
    jsonOAuth2.updateString(jsonPath: "oauth2.token_endpoint", value: "https://login.microsoftonline.com/TENANT_ID/oauth2/v2.0/token")

    let httpCurl = CkoHttpCurl()!

    // Provide the information for getting the OAuth2 access token from the token endpoint
    // Note: The Authorization header specified in the curl command will be ignored and replaced using the OAuth2 access token obtained at runtime from the token endpoint.
    httpCurl.setAuth(json: jsonOAuth2)

    // The placeholders {{sharepoint_hostname}} and {{site_name}} represent variables that must be defined before execution.
    // When DoYourThing runs the curl command, it automatically substitutes these placeholders with their corresponding values.
    // Below are the values assigned to these variables:
    httpCurl.setVar(varName: "sharepoint_hostname", varValue: "example.sharepoint.com")
    httpCurl.setVar(varName: "site_name", varValue: "test")

    // Run the curl command.
    success = httpCurl.doYourThing(targetCurl: sb.getAsString())
    if success == false {
        print("\(httpCurl.lastErrorText!)")
        return
    }

    let responseJson = CkoJsonObject()!
    responseJson.emitCompact = false

    httpCurl.getResponseJson(json: responseJson)

    var statusCode: Int = httpCurl.statusCode.intValue
    print("response status code: \(statusCode)")

    print("\(responseJson.emit()!)")

}