简体   繁体   中英

How to Authenticate an API in PHP?

so I'm trying to authenticate an API using a key the developers gave me. It's the Propublica Congress API and googling anything on the topic seems to take me to if I was making my own API, how I could create keys to give to users(searching here is the same). I want to authenticate this API so I can get information from it, but nowhere I look seems to have a straightforward answer. How can I authenticate this API using PHP?

就在文档中,只需将X-API-Key标头和您的api密钥添加到每个请求即可。

You have to email them for the API key... got to the website and click on this button

在此处输入图片说明

After you receive the API key from the owner you will then be able to use it in your requests as per the documentation.

Its depends on how you gonna get data form your API, Suppose if you are using PHP Curl to get data or You are placing request using Javascript you have to create custom header and pass your key through the custom header name X-API-Key .

This is simple PHP Curl example and i have put the custom header

curl_setopt( $res, CURLOPT_URL, $url );
//curl_setopt( $res, CURLOPT_POST, 3 ); 
//curl_setopt( $res, CURLOPT_POSTFIELDS, $fields );
curl_setopt( $res, CURLOPT_RETURNTRANSFER, true ); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "X-API-Key: $key",
    "customer-header2:value2"
    )); //you can specify multiple custom keys.


$result = curl_exec( $res );
print_r($result);

First of all you have to see how people call APIs using PHP or JS and then you can try authentication and custom headers.
I would like to recommend you.
1) PHP Curl example
2) JQUery AJAX to make request to the any APIs Link

You need to first explore about how to call APIs using PHP Curl.

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