簡體   English   中英

在codeigniter控制器中使用REST API

[英]Consume a REST API in codeigniter controller

我已經創建了一個REST API,並想在codeigniter控制器中使用自己創建的API。

我創建的REST API控制器(example.php)

   class Example extends REST_Controller {

    public function __construct() { 
    parent::__construct();        
    $this->load->model('user');
   }

     public function user_fetch_post() {
    //returns all rows if the id parameter doesn't exist,
    //otherwise single row will be returned
    $id = $this->input->post('id');
    $users = $this->user->getRows($id);

    //check if the user data exists
    if(!empty($users)){
        //set the response and exit
        $this->response($users, REST_Controller::HTTP_OK);
    }else{
        //set the response and exit
        $this->response([
            'status' => FALSE,
            'message' => 'No user were found.'
        ], REST_Controller::HTTP_NOT_FOUND);
    }
    }

模型(user.php)

    function getRows($id = ""){
    if(!empty($id)){
        $query = $this->db->get_where('users', array('id' => $id));
        return $query->row_array();
    }else{
        $query = $this->db->get('users');
        return $query->result_array();
    }
    }

在這里我想通過基本身份驗證(uname-admin,pwd-1234)調用我創建的api(來自example.php)以在welcome.php控制器中獲取記錄

我的控制器welcome.php

public function index()
{
}

任何人都可以幫助我,如何使用基本身份驗證在控制器welcome.php中調用我的api。

使用CURL可以使用任何API /網絡調用。

<?php
    $headers = array(
        'Content-Type:application/json',
        'Authorization: Basic '. base64_encode("user:password") // place your auth details here
    );
    $payload = array(
        'id' => 1,
    );

    $process = curl_init($host); //your API url
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($process, CURLOPT_HEADER, 1);
    curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
    curl_setopt($process, CURLOPT_TIMEOUT, 30);
    curl_setopt($process, CURLOPT_POST, 1);
    curl_setopt($process, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
    $return = curl_exec($process);
    curl_close($process);

    //finally print your API response
    print_r($return);
?>

但是,為什么要這樣調用自己的API? 您只需調用API模型並執行操作即可

在下方添加您的卷曲選項

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
  'APIKEY: admin@123',
  'Content-Type: application/json',
   ));

也更新

$config['rest_key_name'] = 'APIKEY';

在您的codeigniter設置的config文件夾內的rest.php文件中。 默認情況下是“ X-API-KEY”

如果OP自己解決了問題,這可能對尋求解決方案的其他人有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM