Home > Net >  First time with PHP and an API - can you help me with a basic example?
First time with PHP and an API - can you help me with a basic example?

Time:10-24

I'm very new to PHP and API, and my company was asked for a job of incorporating API calls on a PHP website.

This is the info about the API that the client gave to us:

API Manual

General Notes:
API URL: https://www.somedomain.com/api/
apiKey: 123qwe456rty678yui
HTTP Verb: POST
Content-Type: application/x-www-form-urlencoded

1. {EMPLOYEES category}

POST /en/1001/cat/10
POST /en/1001/cat/10/page/[999]

Observations:
• the list returns 20 records
• to get the reamining records: /en/1001/cat/10/page/2; /en/1001/cat/10/page/3; ...
• the information is returned in JSON format
• all the requests should be made by the POST method and the api key should be sent on the request body


Input variables:
• apiKey => the API key

Return parameters:
retCode = “error”
retCode = “ok”

(...)


2. {NEWS category}

POST /en/2002/cat/20
POST /en/2002/cat/20/page/[999]

Observations:
• the list returns 20 records
• to get the reamining records: /en/2002/cat/20/page/2; /en/2002/cat/20/page/3; ...
• the information is returned in JSON format

Input variables:
• apiKey => the API key

Return parameters:
retCode = “error”
retCode = “ok”

(...)

And I've made a simple PHP script but I'm getting an empty return value:

<?php

//API URL: https://www.somedomain.com/api/
//This is to test the Employees category - /en/1001/cat/10

$curl = curl_init();
$apiKey = urlencode("123qwe456rty678yui");
//$apiKey = "123qwe456rty678yui";

//it doesn't matter if this variable is urlencoded or not, as the result is always empty...


curl_setopt_array($curl, array(
  CURLOPT_URL => "https://www.somedomain.com/api/en/1001/cat/10",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_SSL_VERIFYPEER => "false",
  CURLOPT_POSTFIELDS => "apiKey=$apiKey",
  
  CURLOPT_HTTPHEADER => array(
    "content-type: application/x-www-form-urlencoded"
  ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo "Response: " . $response;
}

?>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Like I said, I'm very new to this, PHP and API's, and the client isn't very helpful.

Based on the Manual API I have, what I'm doing wrong? $response is always empty, it gives no error even if I enter a wrong API Key, and I don't even know if I'm calling this the correct way...

Thanks in advance!

CodePudding user response:

Here is a function that should work from the manual: https://www.php.net/manual/en/function.curl-setopt-array.php#89850

<?php

function get_web_page($url, $curl_data )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,         // return web page
        CURLOPT_HEADER         => false,        // don't return headers
        CURLOPT_FOLLOWLOCATION => true,         // follow redirects
        CURLOPT_ENCODING       => "",           // handle all encodings
        CURLOPT_USERAGENT      => "spider",     // who am i
        CURLOPT_AUTOREFERER    => true,         // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,          // timeout on connect
        CURLOPT_TIMEOUT        => 120,          // timeout on response
        CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
        CURLOPT_POST            => 1,            // i am sending post data
           CURLOPT_POSTFIELDS     => $curl_data,    // this are my post vars
        CURLOPT_SSL_VERIFYHOST => 0,            // don't verify ssl
        CURLOPT_SSL_VERIFYPEER => false,        //
        CURLOPT_VERBOSE        => 1                //
    );

    $ch      = curl_init($url);
    curl_setopt_array($ch,$options);
    $content = curl_exec($ch);
    $err     = curl_errno($ch);
    $errmsg  = curl_error($ch) ;
    $header  = curl_getinfo($ch);
    curl_close($ch);

  //  $header['errno']   = $err;
  //  $header['errmsg']  = $errmsg;
  //  $header['content'] = $content;
    return $header;
}

$curl_data = "var1=60&var2=test";
$url = "https://www.example.com";
$response = get_web_page($url,$curl_data);

print '<pre>';
print_r($response);

?>

CodePudding user response:

You can also try the file_get_contents function to get this JSON data.

Something like this could do the job:

// API URL
$apiUrl = 'https://www.somedomain.com/api/en/2002/cat/20';

// Request options 
$opts = [
    "http" => [
        'method'  => 'POST',
        'header'  => [
            'Content-Type: application/x-www-form-urlencoded', 
            'apiKey: 123qwe456rty678yui'
        ]
    ]
];

// Request context
$context = stream_context_create($opts);

// Get JSON 
$json = file_get_contents($apiUrl, false, $context);

Try and see if you can adapt it.

  • Related