Hi,
Just dealing for the first time with RESTful APIs.
I am not understanding how and where I need to configure the JSON "parameter" I get during a POST done using a web service I created.
This is the RestController
<?php
class RestController extends Controller
{
private $format = 'json';
/**
* @return array action filters
*/
public function filters()
{
return array();
}
public function actions()
{
return array(
'gtv'=>array('class'=>'CWebServiceAction',),
);
}
/**
* @param string
* @return string
* @soap
*/
public function actionGetCards()
{
$jsonArray = array();
$dummyDate = DateTime::createFromFormat('d/m/Y H:i:s', date('d/m/Y H:i:s'));
$nowDateTime = $dummyDate->format('Y-m-d H:i:s');
list($response, $blackBox) = $this->_getAuthorization();
if($response==200){
$cards = ViewCardExtended::model()->findAll(
array(
'condition' => '
available_trips >= :available_trips AND
:nowDateTime between expiration_from and expiration_to
',
'params' => array(
':available_trips' => 0,
':nowDateTime' => $nowDateTime,
),
'order' => 'id',
)
);
$jsonArray['cards'] = $cards;
$jsonArray['left'] = 0;
$jsonArray['bunch'] = 1;
$this->_sendResponse($response, CJSON::encode($jsonArray));
} else {
$this->_sendResponse($response);
}
}
private function _sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
// set the status
$status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
header($status_header);
// and the content type
header('Content-type: ' . $content_type);
// pages with body are easy
if($body != '')
{
// send the body
echo $body;
}
// we need to create the body if none is passed
else
{
// create some body messages
$message = '';
// this is purely optional, but makes the pages a little nicer to read
// for your users. Since you won't likely send a lot of different status codes,
// this also shouldn't be too ponderous to maintain
switch($status)
{
case 401:
$message = 'You must be authorized to view this page.';
break;
case 404:
$message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
break;
case 500:
$message = 'The server encountered an error processing your request.';
break;
case 501:
$message = 'The requested method is not implemented.';
break;
}
// servers don't always have a signature turned on
// (this is an apache directive "ServerSignature On")
$signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
// this should be templated in a real-world solution
$body = '
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "[url="http://www.w3.org/TR/html4/strict.dtd"]http://www.w3.org/TR/html4/strict.dtd[/url]">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>' . $status . ' ' . $this->_getStatusCodeMessage($status) . '</title>
</head>
<body>
<h1>' . $this->_getStatusCodeMessage($status) . '</h1>
<p>' . $message . '</p>
<hr />
<address>' . $signature . '</address>
</body>
</html>';
echo $body;
}
Yii::app()->end();
}
private function _getStatusCodeMessage($status)
{
// these could be stored in a .ini file and loaded
// via parse_ini_file()... however, this will suffice
// for an example
$codes = Array(
200 => 'OK - Everything worked as expected',
201 => 'A resource was successfully created in response to a POST request. The Location header contains the URL pointing to the newly created resource',
204 => 'The request was handled successfully and the response contains no body content (like a DELETE request)',
304 => 'The resource was not modified - You can use the cached version',
400 => 'Bad request - This could be caused by various actions by the user, such as providing invalid JSON data in the request body, providing invalid action parameters, etc',
401 => 'Unauthorized - Authentication failed',
402 => 'Payment Required',
403 => 'Forbidden - The authenticated user is not allowed to access the specified API endpoint',
404 => 'Not Found - The requested resource does not exist',
405 => 'Method not allowed - Please check the Allow header for the allowed HTTP methods',
415 => 'Unsupported media type - The requested content type or version number is invalid',
422 => 'Data validation failed - Please check the response body for detailed error messages',
429 => 'Too many requests - The request was rejected due to rate limiting',
500 => 'Internal server error - This could be caused by internal program errors',
501 => 'Not Implemented',
);
return (isset($codes[$status])) ? $codes[$status] : '';
}
private function _getAuthorization()
{
// Start with an empty array
$rows = array();
// Process only if parameters are sent
if($_GET) {
// GET parameters filling up array
foreach($_GET as $var=>$value) {
$rows[$var] = $value;
}
// If UID is given validate
if (array_key_exists('uid', $rows)) {
// Find black box association
$authorizedDevice = OneBlackBox::model()->find(
'unique_identifier = :unique_identifier AND vehicle_id is not null',
array(
':unique_identifier' => $rows['uid'],
)
);
// Authorized
if($authorizedDevice) {
return array(200, $authorizedDevice);
}
// NOT authorized
else {
return array(401, null);
}
}
// Otherwise NOT authorized
else {
return array(401, null);
}
}
// Otherwise NOT authorized
else {
return array(401, null);
}
}
}
And this is the request I am getting:
INFO:webAPI:Connected to: [url="http://www.xxx.com:80"]www.xxx.com:80[/url], ssl: False
DEBUG:webAPI:Provisional request: POST /app/gtv/136/Rest/getCards/uid/91C0F7B1-EAA1-8863-5979-EACB8BB8C0FC
{"initial": {"start_time": "2015-08-15 15:43:23", "vehicle_id": 1, "device_id": "b8:27:eb:3d:b6:92"}}
INFO:webAPI:Request POST, body: {"initial": {"start_time": "2015-08-15 15:43:23", "vehicle_id": 1, "device_id": "b8:27:eb:3d:b6:92"}}
The question is how do I read the:
{"initial": {"start_time": "2015-08-15 15:43:23", "vehicle_id": 1, "device_id": "b8:27:eb:3d:b6:92"}}
Hope to see some light at the end of the tunnel.
Thanks