Home > other >  Converting PHP Curl request API to python
Converting PHP Curl request API to python

Time:05-08

Can somebody have me trans this PHP API code to Python. I try but it failed. I know about basic requests in python but couldn't pass attributes in that request, I am also confused about passing cURL data in requests.

    <?php
$apiKey = 'SOME_API_KEY';
$apiSecret = 'SOME_API_SECRET';

$message = array(
    'message' => array(
        'message' => 'How are you doing today?',
        'chatBotID' => 6,
        'timestamp' => time()
    ),
    'user' => array(
        'firstName' => 'Tugger', 
        'lastName' => 'Sufani',
        'gender' => 'm',
        'externalID' => 'abc-639184572'
        )
);

// construct the data
$host = "https://www.personalityforge.com/api/chat/";
$messageJSON = json_encode($message);
$hash = hash_hmac('sha256', $messageJSON, $apiSecret);

$url = $host."?apiKey=".$apiKey."&hash=".$hash."&message=".urlencode($messageJSON);

// Make the call using cURL
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// make the call
$response = curl_exec($ch);
curl_close($ch);

echo 'Response JSON: '.$response.'<br>';

$responseObject = json_decode($response);
echo 'Response Object: <br>';
var_dump($responseObject);
?>

CodePudding user response:

import requests
import hashlib
import time
import json
import hmac
apiKey = 'SOME_API_KEY'
apiSecret = 'SOME_API_SECRET'

message = {
    'message': {
        'message': 'How are you doing today?',
        'chatBotID': 6,
        'timestamp': time.time(),
    },
    'user': {
        'firstName': 'Tugger',
        'lastName': 'Sufani',
        'gender': 'm',
       'externalID': 'abc-639184572',
    }
}

host = 'https://www.personalityforge.com/api/chat/index.php'
messageJSON = json.dumps(message)
hash_message = hmac.new(apiSecret.encode('utf-8'), messageJSON.encode('utf-8'), hashlib.sha256).hexdigest()
response = requests.get(host, {"apiKey": apiKey, "hash": hash_message, "message": messageJSON})
print('Response JSON: ', response.json())

Is this what you're looking for? It gives the response that I need a valid api key which makes sense considering you gave fakes...

  • Related