I am sending an HTTP request using CURL API in PHP and trying to receive the variable custid in python: How do I receive the custid? Below is the PHP code and also the python code. The url in this example is $temp_url = "https://test.com//api/v1/users/all?custid=123";
PHP Send:
function __pull($temp_url)
{
$curl = curl_init();
$username = "##########";
$password = "##########";
$temp_url = "https://test.com//api/v1/users/all?custid=123";
curl_setopt_array($curl, array(
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_URL => "$temp_url",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_USERPWD => "$username:$password",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),));
$this->response = curl_exec($curl);
$this->err = curl_error($curl);
curl_close($curl);
$this->response = json_decode($this->response, true); //because of true, it's in an array
//var_dump($this->response);
//print_r($this->err);
if (empty($this->response)) return FALSE; else return TRUE;
}
Here is the Python Code at the designated URL:
#app.route('/api/v1/users/all', methods=['GET'])
#auth.login_required
def get_users():
# what is the code in python to retrieve the variable custid from this url
# https://test.com//api/v1/users/all?custid=123
print(request['custid'])
return TRUE
To get custid in above example, you should request object like below:
def get_users():
custid = request.args.get('custid')
print(custid)
return 'OK'
Basically, the get() method of the args object returns the value of the custid query parameter as a string (or returns None)
Related
When I print the response, everything seems to be correct, and the type is also correct.
Assertion: True
Response type: <class 'scrape_pb2.ScrapeResponse'>
But on postman I get "13 INTERNAL" With no additional information:
I can't figure out what the issue is, and I can't find out how to log or print the error from the server side.
Relevant proto parts:
syntax = "proto3";
service ScrapeService {
rpc ScrapeSearch(ScrapeRequest) returns (stream ScrapeResponse) {};
}
message ScrapeRequest {
string url = 1;
string keyword = 2;
}
message ScrapeResponse {
oneof result {
ScrapeSearchProgress search_progress = 1;
ScrapeProductsProgress products_progress = 2;
FoundProducts found_products = 3;
}
}
message ScrapeSearchProgress {
int32 page = 1;
int32 total_products = 2;
repeated string product_links = 3;
}
scraper.py
def get_all_search_products(search_url: str, class_keyword: str):
search_driver = webdriver.Firefox(options=options, service=service)
search_driver.maximize_window()
search_driver.get(search_url)
# scrape first page
product_links = scrape_search(driver=search_driver, class_keyword=class_keyword)
page = 1
search_progress = ScrapeSearchProgress(page=page, total_products=len(product_links), product_links=[])
search_progress.product_links[:] = product_links
# scrape next pages
while go_to_next_page(search_driver):
page += 1
print(f'Scraping page=>{page}')
product_links.extend(scrape_search(driver=search_driver, class_keyword=class_keyword))
print(f'Number of products scraped=>{len(product_links)}')
search_progress.product_links.extend(product_links)
# TODO: remove this line
if page == 6:
break
search_progress_response = ScrapeResponse(search_progress=search_progress)
yield search_progress_response
Server:
class ScrapeService(ScrapeService):
def ScrapeSearch(self, request, context):
print(f"Request received: {request}")
scrape_responses = get_all_search_products(search_url=request.url, class_keyword=request.keyword)
for response in scrape_responses:
print(f"Assertion: {response.HasField('search_progress')}")
print(f"Response type: {type(response)}")
yield response
Turns out it's just an issue with postman. I set up a python client and it worked.
I am in the process of incorporating the gate,io rest api and am currently trying to convert the signature function from python to php(laravel).
Apparently there is a bug hiding in the conversion.
Can someone take a look and tell me if this is all correct or if something is missing here?
For improvement suggestions I would be grateful
Python code:
def gen_sign(method, url, query_string=None, payload_string=None):
key = '' # api_key
secret = '' # api_secret
t = time.time()
m = hashlib.sha512()
m.update((payload_string or "").encode('utf-8'))
hashed_payload = m.hexdigest()
s = '%s\n%s\n%s\n%s\n%s' % (method, url, query_string or "", hashed_payload, t)
sign = hmac.new(secret.encode('utf-8'), s.encode('utf-8'), hashlib.sha512).hexdigest()
return {'KEY': key, 'Timestamp': str(t), 'SIGN': sign}
Source: Gate.io API Signature string generation
Php Code:
public function createSignature($method, $url, $query=null, $payload=null, $algo = 'sha256'){
$key = 'xxx';
$secret= 'xxx';
$time = microtime(true);
$hashed_payload = hash_hmac($algo,$query ?? '');
$string = "{$methode}\n{$url}\n{$query ?? ''}\n{$hashed_payload}\n{$time}"
$sign = hash_hmac($algo,$string,$secret)
return ['KEY' => $key, 'Timestamp' => "{$time}", 'SIGN' => $sign]
}
i got the answer, i hope it will helps:
public function buildSignHeaders($method, $resourcePath, $queryParams = [], $payload = null)
{
$fullPath = parse_url(config('gate-io.host'), PHP_URL_PATH) . $resourcePath;
$fmt = "%s\n%s\n%s\n%s\n%s";
$timestamp = time();
$hashedPayload = hash("sha512", ($payload !== null) ? $payload : "");
$signatureString = sprintf(
$fmt,
$method,
$fullPath,
GuzzleHttp\Psr7\build_query($queryParams, false),
$hashedPayload,
$timestamp
);
$signature = hash_hmac("sha512", $signatureString, config('gate-io.apiSecretKey'));
return [
"KEY" => config('gate-io.apiKey'),
"SIGN" => $signature,
"Timestamp" => $timestamp
];
}
i have a python application that send data to request.log using webhook.php
webhook.php working code :
<?php
$request = file_get_contents('php://input');
$req_dump = print_r( $request, true );
$fp = file_put_contents( 'request.log', $req_dump );
// Updated Answer
if($json = json_decode(file_get_contents("php://input"), true)){
$data = $json;
}
print_r($data);
?>
content in request.log is on json format.
I get results in request.log without issue, but i need to send same details to telegram, here's the not working code :
<?php
$request = file_get_contents('php://input');
$req_dump = print_r( $request, true );
$fp = file_put_contents( 'request.log', $req_dump );
// Updated Answer
if($json = json_decode(file_get_contents("php://input"), true)){
$data = $json;
}
print_r($data);
if($json = json_decode(file_get_contents("php://input"), true)){
$token = "166.....:AAFlfaCuGdkG3MD1hO.......";
$chatid = "-51....";
$message = $data;
function sendMessage($chatid, $message, $token)
{
$url = "https://api.telegram.org/bot" . $token . "/sendMessage?chat_id=" . $chatid;
$url = $url . "&text=" . urlencode($message);
$ch = curl_init();
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $optArray);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
sendMessage($chatid, $message, $token);
}
?>
Can't figure out how to get those data sent to telegram, if it's impossible to send to request.log and to telegram in same time, is there a way to get updated content from request.log and send them to telegram.
Thank you
I have this php api request example I want to convert to python
function sendRequest($url, $params, $apiKey, $secretKey) {
$query = http_build_query($params);
$params['api_key'] = $apiKey;
$params['auth_hash'] = hash_hmac('sha512', $query, $secretKey);
$params['nonce'] = explode(' ', microtime())[1];
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_RETURNTRANSFER => true
));
$response = curl_exec($ch);
curl_close($ch);
return $response;}
And this is my python code but it keep returning incorrect hash, please how can I make this request in python?
import hashlib
import hmac
import requests
import time
params = {
'name':'Matthew Jackson',
'state':'nj',
'zip':'034572',
'address':'14 Main Street',
'phone':'',
'dob':''}
def request_ss( url, params, api_key, secretKey):
tosign = "&".join( [i + '=' + params[i] for i in params] )
secretKey = str.encode(secretKey)
tosign = str.encode(tosign)
sign = hmac.new(secretKey, tosign , hashlib.sha512)
res_body = {
'api_key': api_key,
'auth_hash': sign.hexdigest(),
'nonce': str(time.time())}
r = requests.post(url, data=res_body)
return r.text
create_url = 'api_url'
res = request_ss(create_url,params,api_key, api_secret)
print(res)
This code keep returning wrong hash from the server, I don't know if am right or wrong on the way I coded this on python, The goal is just to make a request and get the data from the server, the API provider only give the request example in php in which I don't understand. Your support is going to be highly appriciated
I've been trying for a while now to connect to the suiteCRM API using Python's request module but to no avail, the official tutorial uses PHP: https://docs.suitecrm.com/developer/api/api-4_1/
I can't seem to create the Python equivalent of this request, no matter what I get the same response:
<pre>/**
* SugarWebServiceImplv4_1.php
*
* This class is an implementation class for all the web services. Version 4_1 adds limit/off support to the
* get_relationships function. We also added the sync_get_modified_relationships function call from version
* one to facilitate querying for related meetings/calls contacts/users records.
*
*/
Class [ <user> class SugarWebServiceImplv4_1 extends SugarWebServiceImplv4 ] {
- Constants [0] {
}
- Static properties [1] {
Property [ public static $helperObject ]
}
- Static methods [0] {
}
- Properties [0] {
}
- Methods [36] {
/**
* Class Constructor Object
*
*/
Method [ <user, overwrites SugarWebServiceImplv4, ctor> public method __construct ] {
}
/**
* Retrieve a collection of beans that are related to the specified bean and optionally return relationship data for those related beans.
* So in this API you can get contacts info for an account and also return all those contact's email address or an opportunity info also.
*
* #param String $session -- Session ID returned by a previous call to login.
* #param String $module_name -- The name of the module that the primary record is from. This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
* #param String $module_id -- The ID of the bean in the specified module
* #param String $link_field_name -- The name of the lnk field to return records from. This name should be the name the relationship.
* #param String $related_module_query -- A portion of the where clause of the SQL statement to find the related items. The SQL query will already be filtered to only include the beans that are related to the specified bean.
... that continues on, it looks like some documentation.
This is my code:
def get_info():
headers = {
"Content-Type": "application/json"
}
creds = OrderedDict()
creds = {"user_auth": {'user_name':"***", "password": "***"}}
creds = json.dumps(creds)
data = {
'method':'login',
'input_type': 'JSON',
'response_type':'JSON',
'rest_data': creds
}
data = json.dumps(data)
response = requests.post("http://example.com/suitecrm/service/v4_1/rest.php", headers=headers, data=data)
print(response.text)
return response.text
Does anyone have any experience doing this? Thank you
edit: this is the PHP call from their docs:
<?php
$url = "http://example.com/suitecrm/service/v4_1/rest.php";
function restRequest($method, $arguments){
global $url;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$post = array(
"method" => $method,
"input_type" => "JSON",
"response_type" => "JSON",
"rest_data" => json_encode($arguments),
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($curl);
curl_close($curl);
return json_decode($result,1);
}
$userAuth = array(
'user_name' => 'suitecrmuser',
'password' => md5('suitecrmpassword'),
);
$appName = 'My SuiteCRM REST Client';
$nameValueList = array();
$args = array(
'user_auth' => $userAuth,
'application_name' => $appName,
'name_value_list' => $nameValueList);
$result = restRequest('login',$args);
$sessId = $result['id'];
$entryArgs = array(
//Session id - retrieved from login call
'session' => $sessId,
//Module to get_entry_list for
'module_name' => 'Accounts',
//Filter query - Added to the SQL where clause,
'query' => "accounts.billing_address_city = 'Ohio'",
//Order by - unused
'order_by' => '',
//Start with the first record
'offset' => 0,
//Return the id and name fields
'select_fields' => array('id','name',),
//Link to the "contacts" relationship and retrieve the
//First and last names.
'link_name_to_fields_array' => array(
array(
'name' => 'contacts',
'value' => array(
'first_name',
'last_name',
),
),
),
//Show 10 max results
'max_results' => 10,
//Do not show deleted
'deleted' => 0,
);
$result = restRequest('get_entry_list',$entryArgs);
print_r($result);
Please check this working example, it should help you get started. Its using python3.
import urllib.request
import json
import hashlib
encode = hashlib.md5("MasterPass".encode('utf-8'))
encodedPassword = encode.hexdigest()
args = {'user_auth': {'user_name': 'admin','password': encodedPassword}}
crmUrl="https://yourname.crm.cr/service/v4_1/rest.php"
data = json.dumps(args)
args = {'method': 'login', 'input_type': 'json',
'response_type' : 'json', 'rest_data' : data}
params = urllib.parse.urlencode(args).encode('utf-8')
response = urllib.request.urlopen(crmUrl, params)
response = response.read().strip()
if not response:
print( "error: " , response)
result = json.loads(response.decode('utf-8'))
print (result)