Skip to content

Instantly share code, notes, and snippets.

@karloscarweber
Last active July 29, 2016 21:55
Show Gist options
  • Save karloscarweber/5261864 to your computer and use it in GitHub Desktop.
Save karloscarweber/5261864 to your computer and use it in GitHub Desktop.
A simple Base REST api connector thingy.

Base CRM PHP REST API thingy

So, this is a collection of classes tha makes it way easier to work with most of the base api, getbase.com.

It's organized as follows

index.php

obviously the controller. it uses simple GET urls to determine get, post, put, and delete requests, as well as which resource is being requested.

curlClass.php

This is a curl helper that makes interacting with REST APi's really easy.

user.php, contacts.php, sources.php, notes.php

These are seperate classes that contain the specific methods needed to manipulate each type of data. I kept them seperate like this to make them easier to maintain, and modify.

questions?

please email me@karloscarweber.com

Sincerely, Karl Oscar Weber

<?php
class Contacts
{
protected $requestBody;
protected $accessToken;
public function __construct ($accessToken = null, $requestBody = null)
{
$this->requestBody = $requestBody;
$this->accessToken = null;
}
// GET, POST, PUT, DELETE /contacts
// obviously gets a contact
public function get($id = null)
{
if($id != null){
// this url gets just a single contact
$request = new RestRequest('https://sales.futuresimple.com/api/v1/contacts/'.$id.'.json', 'GET');
$request->execute();
} else {
// this url gets all of the contacts
$request = new RestRequest('https://sales.futuresimple.com/api/v1/contacts.json', 'GET');
$request->execute();
}
// Lets store this data for future use.
$responseObject = json_decode($request->getResponseBody());
// echo the response for debuggin purposes ofcourse.
//echo '<pre>' . print_r($request, true) . '</pre>';
// check if this puppy is an array, if so throw it back.
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
// creates a new contact
public function post($interestingArrayOfData = null)
{
// ideally the interesting array of data would be filled with whatever you want to post to the api
// make sure it's in an array though, in the following format:
/*$interestingArrayOfData = array(
"last_name" => "$last_name",
"first_name" => "$first_name"
);*/
$request = new RestRequest('https://sales.futuresimple.com/api/v1/contacts.json', 'POST', $interestingArrayOfData);
$request->execute();
$responseObject = json_decode($request->getResponseBody());
// echo the response for debuggin purposes ofcourse.
//echo '<pre>' . print_r($request, true) . '</pre>';
// Check for success
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
// updates a contact
public function put($id = null, $interestingArrayOfData = null)
{
// ideally the interesting array of data would be filled with whatever you want to put to the api
// make sure it's in an array though, in the following format:
/*$interestingArrayOfData = array(
"last_name" => "$last_name",
"first_name" => "$first_name"
);*/
$request = new RestRequest('https://sales.futuresimple.com/api/v1/contacts/'.$id.'.json', 'PUT', $interestingArrayOfData);
$request->execute();
$responseObject = json_decode($request->getResponseBody());
//echo '<pre>' . print_r($request, true) . '</pre>';
// Check for success
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
// obviously deletes a contact.
public function delete($id = null)
{
if($id != null){
// this url gets just a single contact
$request = new RestRequest('https://sales.futuresimple.com/api/v1/contacts/'.$id.'.json', 'DELETE');
$request->execute();
}
$responseObject = json_decode($request->getResponseBody());
//echo '<pre>' . print_r($request, true) . '</pre>';
// Check for success
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
}
<?php
// shamelessly lifted from: http://www.gen-x-design.com/archives/making-restful-requests-in-php/
class RestRequest
{
protected $url;
protected $verb;
protected $requestBody;
protected $requestLength;
protected $username;
protected $password;
protected $acceptType;
protected $responseBody;
protected $responseInfo;
public function __construct ($url = null, $verb = 'GET', $requestBody = null)
{
$this->url = $url;
$this->verb = $verb;
$this->requestBody = $requestBody;
$this->requestLength = 0;
$this->username = null;
$this->password = null;
$this->acceptType = 'application/json';
$this->responseBody = null;
$this->responseInfo = null;
if ($this->requestBody !== null)
{
$this->buildPostBody();
}
}
public function flush ()
{
$this->requestBody = null;
$this->requestLength = 0;
$this->verb = 'GET';
$this->responseBody = null;
$this->responseInfo = null;
}
public function execute ()
{
$ch = curl_init();
$this->setAuth($ch);
try
{
switch (strtoupper($this->verb))
{
case 'GET':
$this->executeGet($ch);
break;
case 'POST':
$this->executePost($ch);
break;
case 'PUT':
$this->executePut($ch);
break;
case 'DELETE':
$this->executeDelete($ch);
break;
default:
throw new InvalidArgumentException('Current verb (' . $this->verb . ') is an invalid REST verb.');
}
}
catch (InvalidArgumentException $e)
{
curl_close($ch);
throw $e;
}
catch (Exception $e)
{
curl_close($ch);
throw $e;
}
}
public function buildPostBody ($data = null)
{
$data = ($data !== null) ? $data : $this->requestBody;
if (!is_array($data))
{
throw new InvalidArgumentException('Invalid data input for postBody. Array expected');
}
$data = http_build_query($data, '', '&');
$this->requestBody = $data;
}
protected function executeGet ($ch)
{
$this->doExecute($ch);
}
protected function executePost ($ch)
{
if (!is_string($this->requestBody))
{
$this->buildPostBody();
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestBody);
curl_setopt($ch, CURLOPT_POST, 1);
$this->doExecute($ch);
}
protected function executePut ($ch)
{
if (!is_string($this->requestBody))
{
$this->buildPostBody();
}
$this->requestLength = strlen($this->requestBody);
$fh = fopen('php://memory', 'rw');
fwrite($fh, $this->requestBody);
rewind($fh);
curl_setopt($ch, CURLOPT_INFILE, $fh);
curl_setopt($ch, CURLOPT_INFILESIZE, $this->requestLength);
curl_setopt($ch, CURLOPT_PUT, true);
$this->doExecute($ch);
fclose($fh);
}
protected function executeDelete ($ch)
{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$this->doExecute($ch);
}
protected function doExecute (&$curlHandle)
{
$this->setCurlOpts($curlHandle);
$this->responseBody = curl_exec($curlHandle);
$this->responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
}
protected function setCurlOpts (&$curlHandle)
{
curl_setopt($curlHandle, CURLOPT_TIMEOUT, 10);
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
if( isset( $_SESSION['login_token'] ) ){
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array (
'Accept: ' . $this->acceptType,
'X-Pipejump-Auth: ' . $_SESSION['login_token']));
}else {
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array ('Accept: ' . $this->acceptType));
}
}
protected function setAuth (&$curlHandle)
{
if ($this->username !== null && $this->password !== null)
{
curl_setopt($curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($curlHandle, CURLOPT_USERPWD, $this->username . ':' . $this->password);
}
}
public function getAcceptType ()
{
return $this->acceptType;
}
public function setAcceptType ($acceptType)
{
$this->acceptType = $acceptType;
}
public function getPassword ()
{
return $this->password;
}
public function setPassword ($password)
{
$this->password = $password;
}
public function getResponseBody ()
{
return $this->responseBody;
}
public function getResponseInfo ()
{
return $this->responseInfo;
}
public function getUrl ()
{
return $this->url;
}
public function setUrl ($url)
{
$this->url = $url;
}
public function getUsername ()
{
return $this->username;
}
public function setUsername ($username)
{
$this->username = $username;
}
public function getVerb ()
{
return $this->verb;
}
public function setVerb ($verb)
{
$this->verb = $verb;
}
}
?>
<?php
/**
*
* This is like the super controller for the application.
* I'm just using GET requests to determine the page and request
* if this was a production app, I would have used a framework like
* Slim, or codeigniter. Nothing but vanilla PHP here.
*
*/
// Check for Curl
if(!extension_loaded("curl")) {
// echo "Curl extension is required for PocketstopRestClient to work";
} else {
// echo "curl is present";
}
//Load the session bro!
session_start();
// Load the Curl Class so we can REST
include 'curlClass.php';
// Load these helper classes, so that we can execute specific REST requests.
include 'user.php';
include 'contacts.php';
include 'sources.php';
include 'notes.php';
// some generic
$page = $_GET['page'];
$method = $_GET['method'];
$id = $_GET['id'];
$contact_id = $_GET['contact_id'];
$token = $_SESSION['login_token'];
$interestingArrayOfData = json_encode($_POST['interestingArrayOfData']);
// GET, POST, PUT, DELETE /contacts
if( $page === 'contacts' ){
$contact = new Contacts();
switch ($method) {
case 'GET':
if( isset( $id ) ){
$result = $contact->get($id);
load_template('contact', $result);
} else {
$result = $contact->get();
load_template('contacts', $result);
}
break;
case 'POST':
$result = $contact->post($interestingArrayOfData);
load_template('contact_new', $result);
break;
case 'PUT':
$result = $contact->put($id, $interestingArrayOfData);
load_template('contact_edit', $result);
break;
case 'DELETE':
$contact->delete($id);
load_template('contact_delete', $result);
break;
default:
load_template('error');
break;
}
}
// GET, POST, PUT, DELETE /contacts/:contact_id/notes/:id
if( $page === 'notes' ){
$notes = new Notes();
switch () {
case 'GET':
if( isset( $id && $contact_id ) ){
$result = $notes->get($contact_id, $id);
load_template('note', $result);
} else {
$result = $notes->get($contact_id);
load_template('notes', $result);
}
break;
case 'POST':
$result = $notes->post($contact_id, $interestingArrayOfData);
load_template('notes_new', $result);
break;
case 'PUT':
$result = $notes->put($contact_id, $id, $interestingArrayOfData);
load_template('notes_edit', $result);
break;
case 'DELETE':
$result = $notes->delete();
load_template('notes_delete', $result);
break;
default:
load_template('error');
break;
}
}
// GET, POST, PUT, DELETE /sources
if( $page === 'sources' ){
$sources = new Sources();
switch () {
case 'GET':
if( isset( $id && $contact_id ) ){
$result = $sources->get($id);
load_template('source', $result);
} else {
$result = $sources->get();
load_template('sources', $result);
}
break;
case 'POST':
$result = $sources->post($interestingArrayOfData);
load_template('sources_new');
break;
case 'PUT':
$result = $sources->put($id, $interestingArrayOfData);
load_template('sources_edit');
break;
case 'DELETE':
$result = $sources->delete($id);
load_template('sources_delete');
break;
default:
load_template('error');
break;
}
}
if( $page === 'user' ){
$user = new User();
switch ($method) {
case 'GET':
$result = $user->account($id);
load_template('user_account');
break;
case 'PUT':
$result = $user->put($id);
load_template('user_edit');
break;
case 'LOGIN':
$result = $user->login($interestingArrayOfData);
load_template('user_login');
break;
case 'LOGOUT':
$result = $user->logout();
load_template('user_logout');
break;
default:
load_template('error');
break;
}
}
?>
<?php
class Notes
{
protected $requestBody;
protected $accessToken;
public function __construct ($accessToken = null, $requestBody = null)
{
$this->requestBody = $requestBody;
$this->accessToken = null;
}
// GET, POST, PUT, DELETE /Notes
// obviously gets a contact
public function get($contact_id = null, $id = null)
{
if($id != null && $contact_id != null){
// this url gets just a single note
$request = new RestRequest('https://sales.futuresimple.com/api/v1/contacts/'.$contact_id.'/notes/'.$id.'.json', 'GET');
$request->execute();
} else {
// this url gets all of the notes
$request = new RestRequest('https://sales.futuresimple.com/api/v1/contacts/'.$contact_id.'/notes.json', 'GET');
$request->execute();
}
// Lets store this data for future use.
$responseObject = json_decode($request->getResponseBody());
// echo the response for debuggin purposes ofcourse.
//echo '<pre>' . print_r($request, true) . '</pre>';
// check if this puppy is an array, if so throw it back.
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
// creates a new contact
public function post($contact_id = null, $interestingArrayOfData = null)
{
// ideally the interesting array of data would be filled with whatever you want to post to the api
// make sure it's in an array though, in the following format:
/*$interestingArrayOfData = array(
"last_name" => "$last_name",
"first_name" => "$first_name"
);*/
$request = new RestRequest('https://sales.futuresimple.com/api/v1/contacts/'.$contact_id.'/notes.json', 'POST', $interestingArrayOfData);
$request->execute();
$responseObject = json_decode($request->getResponseBody());
// echo the response for debuggin purposes ofcourse.
//echo '<pre>' . print_r($request, true) . '</pre>';
// Check for success
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
// updates a contact
public function put($contact_id = null, $id = null, $interestingArrayOfData = null)
{
// ideally the interesting array of data would be filled with whatever you want to put to the api
// make sure it's in an array though, in the following format:
/*$interestingArrayOfData = array(
"last_name" => "$last_name",
"first_name" => "$first_name"
);*/
$request = new RestRequest('https://sales.futuresimple.com/api/v1/contacts/'.$contact_id.'/notes/'.$id.'.json', 'PUT', $interestingArrayOfData);
$request->execute();
$responseObject = json_decode($request->getResponseBody());
//echo '<pre>' . print_r($request, true) . '</pre>';
// Check for success
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
// obviously deletes a contact.
public function delete($contact_id = null, $id = null)
{
if($id != null){
// this url gets just a single contact
$request = new RestRequest('https://sales.futuresimple.com/api/v1/contacts/'.$contact_id.'/notes/'.$id.'.json', 'DELETE');
$request->execute();
}
$responseObject = json_decode($request->getResponseBody());
//echo '<pre>' . print_r($request, true) . '</pre>';
// Check for success
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
}
<?php
class Sources
{
protected $requestBody;
protected $accessToken;
public function __construct ($accessToken = null, $requestBody = null)
{
$this->requestBody = $requestBody;
$this->accessToken = null;
}
// GET, POST, PUT, DELETE /sources
// obviously gets a source
public function get($id = null)
{
if($id != null){
// this url gets just a single source
$request = new RestRequest('https://sales.futuresimple.com/api/v1/sources/'.$id.'.json', 'GET');
$request->execute();
} else {
// this url gets all of the sources
$request = new RestRequest('https://sales.futuresimple.com/api/v1/sources.json', 'GET');
$request->execute();
}
// Lets store this data for future use.
$responseObject = json_decode($request->getResponseBody());
// echo the response for debuggin purposes ofcourse.
//echo '<pre>' . print_r($request, true) . '</pre>';
// check if this puppy is an array, if so throw it back.
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
// creates a new source
public function post($interestingArrayOfData = null)
{
// ideally the interesting array of data would be filled with whatever you want to post to the api
// make sure it's in an array though, in the following format:
/*$interestingArrayOfData = array(
"name" => "$name",
"id" => "$id"
);*/
$request = new RestRequest('https://sales.futuresimple.com/api/v1/sources.json', 'POST', $interestingArrayOfData);
$request->execute();
$responseObject = json_decode($request->getResponseBody());
// echo the response for debuggin purposes ofcourse.
//echo '<pre>' . print_r($request, true) . '</pre>';
// Check for success
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
// updates a source
public function put($id = null, $interestingArrayOfData = null)
{
// ideally the interesting array of data would be filled with whatever you want to put to the api
// make sure it's in an array though, in the following format:
/*$interestingArrayOfData = array(
"last_name" => "$last_name",
"first_name" => "$first_name"
);*/
$request = new RestRequest('https://sales.futuresimple.com/api/v1/sources'.$id.'.json', 'PUT', $interestingArrayOfData);
$request->execute();
$responseObject = json_decode($request->getResponseBody());
//echo '<pre>' . print_r($request, true) . '</pre>';
// Check for success
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
// obviously deletes a source.
public function delete($id = null)
{
if($id != null){
// this url gets just a single source
$request = new RestRequest('https://sales.futuresimple.com/api/v1/sources/'.$id.'.json', 'DELETE');
$request->execute();
}
$responseObject = json_decode($request->getResponseBody());
//echo '<pre>' . print_r($request, true) . '</pre>';
// Check for success
if( is_array( $responseObject ) ){
return $responseObject;
} else {
return null;
}
}
}
<?php
//user.php
// include framework
// include user class
// establish rest API
/*
Users will have A name and an email,
You will be able to email this person.
That is all.
*/
// Get Users...
// Get a specific User
// Create a User
// Delete a User
class User
{
protected $requestBody;
protected $accessToken;
public function __construct ($accessToken = null, $requestBody = null)
{
$this->requestBody = $requestBody;
$this->accessToken = null;
}
// please note that I never got this one to work right.
public function account()
{
$request = new RestRequest('http://sales.futuresimple.com/api/v1/account.json', 'GET');
$request->execute();
$responseObject = json_decode($request->getResponseBody());
echo '<pre>' . print_r($request, true) . '</pre>';
// Check
if( is_array( $responseObject ) ){
$token = $responseObject->authentication->token;
$_SESSION['login_token'] = $token;
return true;
} else {
return false;
}
}
// logs you in silly.
// takes data from the template_login.php template
public function login($email = null, $password = null)
{
$postData = array(
"email" => "$email",
"password" => "$password"
);
$request = new RestRequest('https://sales.futuresimple.com/api/v1/authentication.json', 'POST', $postData);
$request->execute();
echo '<pre>' . print_r($request, true) . '</pre>';
$responseObject = json_decode($request->getResponseBody());
// Check if it worked.
if( isset( $responseObject->authentication->token ) ){
$token = $responseObject->authentication->token;
$_SESSION['login_token'] = $token;
return true;
} else {
return false;
}
}
public function logout()
{
$_SESSION = array();
session_destroy();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment