PHP code example of pstaender / silverstripe-restful-api
1. Go to this page and download the library: Download pstaender/silverstripe-restful-api library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
pstaender / silverstripe-restful-api example snippets
class Client extends DataObject {
private static $db = [
"Email" => "Varchar",
"FirstName" => "Varchar",
"Surname" => "Varchar",
"Note" => "Text",
];
// these fields be made available by default through `forApi`
private static $api_fields = [
"Email", "Name",
];
// example method
function Name() {
return trim($this->FirstName. " " .$this->Surname);
}
// can be defined optional
function forApi() {
$data = parent::forApi(); // will contain s.th. like [ "Email" => "…", "Name" => "…" ]
// do s.th. with the data if you want to …
return $data;
}
}
class ClientController extends APIController {
private static $api_parameters = [
"GET:client" => [
'$ID' => "int",
],
"POST:client" => [
'email' => "/^[^@]+@[^@]+$/",
],
];
private static $api_allowed_actions = [
"GET:client" => true, // everyone can read here
"DELETE:client" => 'ADMIN', // only admins can delete
"POST:client" => '->isBasicApiUser', // method `isBasicApiUser` checks permission
];
private static $api_model = "Client"; // this is to connect this controller to a specific model (important for field matching)
/**
* Will respond with a JSON object and 200 if found
* with a 404 and a JSON msg object otherwise
*/
function clientGET() {
return $this->sendData(
Client::get()->byID($this->request->param("ID"))
);
}
function clientPOST() {
$client = Client::create();
$data = $this->requestDataAsArray('Client');
$populateOnlyTheseseFields = [ "Email", "FirstName", "Surname" ];
$country->populateWithData($data, $populateOnlyTheseseFields);
$country->write();
return $this->sendSuccesfulPost($country->URL());
}
function clientDELETE() {
$client = Client::get()->byID($this->request->param("ID");
if (!$client)
return $this->sendNotFound();
$client->delete();
return $this->sendSuccessfulDelete();
}
protected function isBasicApiUser() {
return Permission::check('BASIC_API') || Permission::check('EXTERNAL_API');
}
}