Speed up development with full-stack environments for every branch.

Learn More

Base Rest PHP API [web service]

Forked from Hello World.

373 Runs 559 Views 81 Copies

Base rest php api

Saved

Saved

sergioska 5

sergioska
published 2 years ago

 <?php 
 
 abstract class API {
  	
  	protected $_method;
  	protected $_verb;
  	protected $_args = array();
  	protected $_endpoint;
  	protected $_file;
  	
  	function __construct($request) {
    		$this->_args = explode('/', $request);
    		$this->_endpoint = array_shift($this->_args);
    		$this->_method = $_SERVER['REQUEST_METHOD'];
    		if($this->_method=='PUT')
    			  $this->_file = file_get_contents("php://input");
  	}
  
  	public function process() {
  		  if(method_exists($this, $this->_endpoint))
  			    return $this->_response($this->{$this->_endpoint}($this->_args));
  		  return $this->_response("No Endpoint: $this->endpoint", 404);
  	}
  
  	private function _response($data) {
  		  header("Content-Type: application/json");
  		  $aRet = array('result' => $data);
  		  echo json_encode($aRet);
  	}
}

class MyAPI extends API {
	  protected function example() {
		    if($this->_method=='GET')
			      return array('version' => '1.0.0');
		    else "this is a get method!";
	  }
}

try{
	  $api = new MyAPI($_REQUEST['request']);
	  $api->process();
} catch(Exceptin $e) {
	  var_dump($e);
}
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).