Mani Ratna
Mani Ratna

Reputation: 911

How to generate token for rest call in codeigniter?

I have to call rest api function in codeigniter project . Data is returning from the api call using Postman . In Postman first i generate a token and put that generated token in the rest call. I have to do the same process in codeigniter. First i have to generate token and pass that token in second api call to get the desired result.

My Controller code :

public function getToken()
{
        $url='http://localhost:8080/myapplication/rest/api/validate-request';
        $key=$this->get_data($url);
}
public function get_data($url)
{

    //create a new cURL resource
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");   
    //curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_USERPWD, R_U_NAME.':'.R_U_PWD);
    $result = curl_exec($ch);
    $result = json_decode($result);
    //var_dump($result);
    //close cURL resource
    curl_close($ch);


}

Here var_dump($result) is returning null value.

Upvotes: 0

Views: 916

Answers (1)

Mani Ratna
Mani Ratna

Reputation: 911

I donot had to pass username and password for authentication .Instead i had to post postman username and password in my function. Now I am getting the token back from the postman.

private function get_data($url)
    {   
        $member_data = array(
            'username' => R_U_NAME,
            'password' => R_U_PWD
        );
        //create a new cURL resource
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $member_data);

        $result = curl_exec($ch);

        curl_close($ch);

        return $result;
    }

Upvotes: 1

Related Questions