Start a new topic

Using REST API with PHP (some samples)

I wanted to use my hosted server accessing Kinveys backend service by PHP. REST API access is a general usage type so I didn't expect some specific explanation. 


I started from scratch and want to give to anyone in the same situation all the information you need to access Kinvey's backend service by REST API and PHP.


The key to use REST API by PHP is the powerful command cURL and therefore supported in PHP. There are many commands but you need only a few for any CRUD operations.


Use these samples to complete your code. Something in red means you have to replace the red part by your own credentials. The example expects you are already registered and have access to Kinvey's backend console. Make also sure that the user has the required permission for the specific CRUD operation.


In the end you will find some very important notes you have to consider working wit cURL/Kinvey's backend service.


Handshake to test proper connection

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, "https://baas.kinvey.com/appdata/yourAppKey");
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: Basic ".base64_encode(yourAppKey. ":" yourAppSecret), "X-Kinvey-API-Version: 3"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec ($ch);
curl_close ($ch);

You always need the curl_init() command before doing a cURL operation. You should close it by curl_close() in the end.


Login with AppKey user

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, "https://baas.kinvey.com/user/yourAppKey/login");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: Basic ".base64_encode(yourAppKey . ":" . yourAppSecret), "X-Kinvey-API-Version: 3" ));
curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($newuser) );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Put return result into array to see/check output
$resultarray = json_decode($result, true);
$authtoken = $resultarray['_kmd']['authtoken'];
print $authtoken;
curl_close ($ch);


Create/register new user in backend service

// Define new user (minimum: username and password)
$newuser = array (
'username' => 'username',
'password' => 'passord',
'anyotherattribute' => 'somevalue'
);
// Create user in cloud defined by $newuser
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, "https://baas.kinvey.com/user/yourAppKey");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: Basic ".base64_encode(yourAppKey. ":" . yourAppSecret), "X-Kinvey-API-Version: 3" ));
curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($newuser) );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec ($ch), true);
// See/check return value(s)
$authtoken = $result['_kmd']['authtoken'];
$cloudid = $result['_id'];
print_r ($usertoken);
print_r ($cloudid);
curl_close ($ch);

This action is equal to a INSERT statement. You can do the same on any other collection than the mentioned user collection here.


Query collection 

// Define query as JSON object
$query = '{"username":"nametofind"};
// Check if start is too close (< 10m) to any other game start
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'https://baas.kinvey.com/appdata/yourAppKey/CollectionToSearchIn/?query='.$query.'&tls=true');
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt ($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: Kinvey authtoken_of_processing_user", "X-Kinvey-API-Version: 3" ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec ($ch), true);
print_r ($result);
curl_close ($ch);

Consider that a search result can consist of more than one record. Each found record will be stored in the array $result.

&tls=true: this is optional, enforcing secure transfer (HTTPS)


Working with queries:

  • Since the query is defined in a JSON object: DON'T use single quotes (') but use double quotes ("). Otherwise the return ($result) is just empty or in best case you get an error message.
  • DON'T use (white) spaces in queries. This will lead into an error message or no returned result  (this may differ in other Kinvey APIs)

Update (replace) record

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'https://baas.kinvey.com/collectionname/yourAppKey/'._id_from_backend);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt ($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: Kinvey authtoken_of_processing_user", "X-Kinvey-API-Version: 3" ));
curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($attribute) );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec ($ch), true);
curl_close ($ch);

If you don't know the unique _id of the record you want to update you may read it first from the collection before updating it.
On updating you always have to send the whole record (all columns) even though you only want to update a singe column. 

Delete record

// Delete record by its _id (can also be some other identifier)
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'https://baas.kinvey.com/appdata/yourAppKey/collectionname/?query={"_id":"'._id_of_record.'"}');
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt ($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: Kinvey authtoken_of_processing_user", "X-Kinvey-API-Version: 3" ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec ($ch);
curl_close ($ch);

Multi delete (delete key identifier in query is not unique) is also possible that way.

Upload file
To upload a file into Kinvey's you need to process two steps:
  1. Request upload
  2. Upload file to file storage

// Request file upload path
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'https://baas.kinvey.com/blob/yourAppKey');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: Kinvey authtoken_of_processing_user", "X-Kinvey-API-Version: 3" ));
curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode(array("_id" => "optional_id", "gameid" => $publicid, "_filename" => "optional_filename",  "mimeType" => "mimeType_of_file", "size" => file_size"somemore" => "anything_else_you_want_to_store_with_the_file", )));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Store return values (_uploadUrl is required for upcoming upload)
$cloud = json_decode(curl_exec ($ch), true);

// Upload file
curl_setopt($ch, CURLOPT_POST, null);
curl_setopt($ch, CURLOPT_PUT,

Tayger,


Thanks for posting this. Indeed, this information is going to be really helpful to everyone exploring Kinvey using REST API and PHP. We appreciate your efforts.


Thanks,

Pranav

Kinvey

Hope I can help others with it. Sadly the lower part is cut off.


Regards

Login or Signup to post a comment