iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 17
0
Modern Web

你說Codeigniter還能怎麼做?系列 第 17

[Day17] 改造API Part2

上次我們已經帶出API路徑,這次我們要寫一個函式去驗證有哪些可以去使用。

驗證API

首先我們要先新增一個設定檔來管理所有的API,我們在config裡新增一個routes_api.php的檔案,接著新增設定:

<?php 
  $config['routes_api'] = array(

  );
?>

新增API設定

接著我們進入config/autoload.php來把設定載入:

$autoload['config'] = array('global', 'code_success', 'code_error', 'routes_api');

下一步我們回到controllers/Api.php針對authenticate來驗證:

  function authenticate($path_name, $func_name) {
    // 驗證設定檔是否有符合規則
    $auth = $this->check_api_file($path_name, $func_name);
    echo json_encode($auth);
    // echo $path_name . ': ' . $func_name;
  }

接著在下方新增check_api_file的函式來驗證:

  function check_api_file($path_name, $func_name) {
    // 取得API清單
    $routes = $this->config->item('routes_api');
    // 確認是否有指定的API路徑與資料
    if (isset($routes[$path_name]) && isset($routes[$path_name][$func_name])) {
      // 有此API可以進行接下來動作
      $json_arr = $this->mod_config->msgResponse((isset($json_arr))?$json_arr:array(), 'success', 'GET_DATA_SUCCESS', $this->language);
      $json_arr['path'] = $path_name;
      $json_arr['func'] = $routes[$path_name][$func_name]; // 取得名稱
    } else {
      // 找不到API,回報錯誤
      $json_arr = $this->mod_config->msgResponse((isset($json_arr))?$json_arr:array(), 'error', 'DATA_FAIL', $this->language);
    }
    return $json_arr; // 回傳結果
  }

接著我們分別在config/code_success.phpconfig/code_error.php加入新的成功與錯誤訊息:

!#code_success.php

  /**
   * @apiDefine sucCode_20002
   * @apiSuccess GET_DATA_SUCCESS 20002 取得資料成功
   */
  $config['suc_code']['GET_DATA_SUCCESS'] = array(
      "sys_code"=> "200",
      "sys_num"=> "20002",
      "sys_msg"=> array(
          "zh-tw"=> '取得資料成功',
          "en-us"=> 'Get data Success'
      )
  );
!#code_error.php

  /**
   * @apiDefine errCode_40002
   * @apiError DATA_FAIL 40002 資料位置存取錯誤
   */
  $config['err_code']['DATA_FAIL'] = array(
      "sys_code"=> "500",
      "sys_num"=> "40002",
      "sys_msg"=> array(
          "zh-tw"=> '資料位置存取錯誤',
          "en-us"=> 'Resource can\'t access'
      )
  );

如此一來當沒有被寫入到routes_api的API就會被回報錯誤,接著我們在routes_api新增測試的API:

<?php 
  $config['routes_api'] = array(
    'user'=> array(
      'get_user'=> 'get_user'
    )
  );
?>

API驗證設定

測試

接著我們再透過網址去測試:
http://ip-address/api/user/get_user
名單上的API

假設如果API不在名單上呢?
http://ip-address/api/user/fake_api
不在名單上的API

如此一來就可以透過routes_api來管理各個API,明天我們在把API分成不同的資料夾來管理吧!

Next station ... 改造API Part3


上一篇
[Day16] 改造API Part1
下一篇
[Day18] 改造API Part3
系列文
你說Codeigniter還能怎麼做?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言