cloudkitcloudkit-web-services

Fetching CloudKit Records By Name and Query in PHP


I've got an app using CloudKit and I'm trying to build a simple web interface to pull the data out of CloudKit so users can view the information. The login is working perfectly, but I can't find any samples on how to structure the requests for records/query and records/lookup.

For records/lookup, I'm POSTing to a similar URL:

https://api.apple-cloudkit.com/database/1/iCloud.com.[mycontainer]/development/private/records/lookup?ckAPIToken=[myToken]&ckSession=[myAuthenticatedSession]

However, using cURL and PHP, I can't seem to get the "records" POST right. The error messages don't provide enough detail Apple hasn't provided any samples in the documentation. What is the proper way to POST records to get a valid response from CloudKit?


Solution

  • You can see a lot of examples and a clear explanation Here.

    The Post request should be in JSON for example:

    { 
        "operationType":"update",
        "record" : {
            "recordType":"Artist",
            "fields": {
                 "firstname" : {"value" : "Chen"},
            }
            "recordName" : "Mei Chen"
        },
    }
    

    this is a JSON object to do an operation. What you are looking for is a lookup, this requires recordName and optionally desiredKeys, leaving desiredKeys empty will give them all. So your json would look like:

    { 
        "recordName":"Mei Chen"
    }
    

    in PHP you can do that with an array easily

    $request = array();
    $request['recordName'] = "Mei Chen";
    $request_json = json_encode($request);
    

    Using your $request_json you can than post this using PHP curl for example like:

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request_json);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($request_json))                                                                       
    );