简体   繁体   中英

Call api in php using curl by giving api key

Suppose i have an api key and by this api key i want to fetch data this is my code.

  $apiKey = 'admin@123'; 
             $headers = array(
'Content-Type:application/json',
 'Authorization: '.$apiKey
 );
    $payload = array(
    'id' => 1,
);
$process = 
curl_init('http://localhost/codeigniterapi/api/example/user_fetch'); 
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 1);
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);
print_r($return);                 

But it shows an error charset=utf-8 {"status":false,"error":"Invalid API key "} but this api work perfectly on postman using same key

Sending the authorization header with the request requires you to add a bearer and a token.

If you used postman to test the request, you prolly entered the username and password in the "Authorization" tab inside postman. You will also have chosen a type for the authorization.

On the second tab, the Headers tab, you can now see that Postman has added your crendentials from the first tab as an authorization header. The key will be "Authorization" and you can steal the Value from this table. As you can see, this contains both the bearer (for Basic Auth, this will be "Basic") and the token itself.

If you want to send the token in the authorization header, it would look like this:

 $headers = array(
    'Content-Type:application/json',
    'Authorization: Basic abcdefghijklmnop'
 );

If you don't want to set the header yourself, you can use

You can set the CURLOPT_USERPWD if you want to use the user and password (example for basicauth):

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);    
curl_setopt($process, CURLOPT_USERPWD, "$username:$password");

To set the curloption for username and password.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM