pythonphpcurlwhmcs

How do I translate a PHP cURL request to python


I'm coding a tool to get Whois info, and I need to use the WHMCS API for it.

This is the code they provide:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.example.com/includes/api.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
    http_build_query(
        array(
            'action' => 'DomainGetWhoisInfo',
            // See https://developers.whmcs.com/api/authentication
            'username' => 'IDENTIFIER_OR_ADMIN_USERNAME',
            'password' => 'SECRET_OR_HASHED_PASSWORD',
            'domainid' => '1',
            'responsetype' => 'json',
        )
    )
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

I want to use this request without PHP, and inside Python. What library should I use and how do I set the variables in the payload?(php or python-style?)


Solution

  • What library should I use

    requests is popular python module for working with HTTP(S) requests, note however that it is external module and needs to be installed as follows

    pip install requests
    

    It is not hard to do, but if you are not allowed to install external module you can not use it. In such situation you might use urllib.request built-in module.

    how do I set the variables in the payload?

    Just translate your array to python's dict and use it as data argument, requests Quickstart provide following example

    r = requests.post('https://httpbin.org/post', data={'key': 'value'})
    

    {'key': 'value'} is python's equivalent to PHP7's array('key' => 'value') and {'key1': 'value1', 'key2': 'value2'} would be array('key1' => 'value1', 'key2' => 'value2') and so on