在您的路线中定义以下代码:
// used for the rest API
$routes->extensions(['json','xml']); // type of format you want to get response
$routes->resources('Api');
然后在控制器文件夹中为 API 创建一个控制器,如下所示
<?php
namespace App\Controller;
use Cake\I18n\Time;
use Cake\Database\Type;
Type::build('date')->setLocaleFormat('yyyy-MM-dd'); // customize date format
// src/Controller/RecipesController.php
class ApiController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
// load Model
$this->loadModel('Sales'); // load model to fetch data from database
$this->Auth->allow(); // allow URL to public in case of Auth check
}
public function beforeFilter(\Cake\Event\Event $event)
{
parent::beforeFilter($event);
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
}
public function index($fromdate = null, $todate = null)
{
//set date range to fetch the sales in particular date
if(!empty($_GET['fromdate_utc']) && !empty($_GET['todate_utc'])){
// if from amd to date are same add +1 day in to date to get result
$to_date = date('Y-m-d', strtotime($_GET['todate_utc'] . ' +1 day'));
$dateRage = array('Sales.SalesDate >= ' => $_GET['fromdate_utc'], 'Sales.SalesDate <=' => $to_date);
}else{
$dateRage = array();
}
$conditions = array(
'and' => array($dateRage),
);
//$this->Auth->allow();
$sales= $this->Sales->find('all', array(
'conditions' => $conditions
))
->select(['SalesNo', 'SalesDate', 'TotalValue', 'TotalDiscount', 'NetTotal', 'PaymentMode', 'Status'])
->where(['StoreId' => '1']);
// set data for view or response of API
$this->set([
'sales' => $sales,
'_serialize' => ['sales']
]);
}
}
?>
如何在 API URL 中传递参数以检查以下 XML 格式:-
https://example.com/api/index.xml?fromdate_utc=2016-10-03&todate_utc=2016-10-03
如何在 API URL 中传递参数以检查以下 JSON 格式:-
https://example.com/api/index.json?fromdate_utc=2016-10-03&todate_utc=2016-10-03