Certificate error when posting with guzzle on D8 - guzzle

Using the code below on D8 to post a form, I get the following error :
cURL error 77: error setting certificate verify locations: CAfile: C:\Program Files (x86)\DevDesktop\common\cert\cacert.pem CApath: none (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
My question is how can I modify this code to not verify or how can I set a certificate so that I won't get this error. thanks
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => rawData($post_data),
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();

this worked for me, I added verify=>false:
$url="jsonplaceholder.typicode.com/posts
$client = \Drupal::httpClient();
$post_data = $form_state->cleanValues()->getValues();
$response = $client->request('POST', $url,
[ 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => $post_data,
'verify'=>false, ]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
dsm($body);
dsm($status);

Related

Argument 1 passed to GuzzleHttp\Client::send() must implement interface

hi I am new to laravel and I am trying to consume the api with laravel 8 I have a problem with my POST and I do not understand
public function storeEntreprise(Request $request){
$request->validate([
'name' => 'required',
'email' => 'required',
'phone_number'=>'required',
'address' => 'required',
'password' => 'required',
'password_confirmation' => 'required'
]);
$client = new Client();
$post = $request->all();
$url = "http://flexy-job.adsyst-solutions.com/api/entreprises-store";
$create = $client->request('POST', $url, [
'headers' => [
'Content-Type' => 'text/html; charset=UTF8',
],
'form-data' => [
'name' => $post['name'],
'email' => $post['email'],
'phone_number' => $post['phone_number'],
'address' => $post['address'],
'logo' => $post['logo'],
'password' => $post['password'],
'password_confirmation' => $post['password_confirmation']
]
]);
//dd($create->getBody());
echo $create->getStatusCode();
//echo $create->getHeader('Content-Type');
echo $create->getBody();
$response = $client->send($create);
return redirect()->back();
}
Can you help me please
You calling (accidentally?) $response = $client->send($create); where $create is response of API request you made ($create = $client->request('POST', $url, ...).
So PHP reports you that you can't pass ResponseInterface where RequestInterface required.
Also, you echo's body of response, and return redirect response at same time. So browser will not show you API response (because of instance back redirect).

Call Rest Api Using Zend\Http\Client Or Guzzle

I am calling magento2 API in laravel. Using curl, I am getting correct response but I want to call API using GuzzleHttp\Client or Zend\Http\Client.
How can I call my api using this, below is my curl code snippet:
$curl = curl_init();
$data=array('username'=>$vendordata['merchant_name'],'password'=>$vendordata['password'],'customer'=>['email'=>$vendordata['email'],"firstname"=> $vendordata['firstname'], "lastname"=> $vendordata['lastname']],"addresses"=> ["region"=> $vendordata['address'], "region_id"=> 0],"default_shipping"=> true,"default_billing"=>true,"telephone"=>$vendordata['contact_number']);
$postdata=json_encode($data);
curl_setopt_array($curl, array(
CURLOPT_URL => "http://10.10.10.7/magento2/rest/V1/customers",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $postdata,
CURLOPT_HTTPHEADER => array(
"authorization: OAuth oauth_consumer_key=\"sganfgvr2naxwmh21jgi5ffijuci0207\",oauth_token=\"d16pdq1avr1rs7h9745rc0x6py65a2vt\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1518006201\",oauth_nonce=\"4ghORA\",oauth_version=\"1.0\",oauth_signature=\"Ztq5ErznqvCl18GomWv0F55t5OA%3D\"",
"cache-control: no-cache",
"content-type: application/json",
"postman-token: 5ec55151-3365-7ffc-a6a4-ce5fe5bc451f"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
First, open the terminal and run this command to install Guzzle
composer require guzzlehttp/guzzle
Then add these lines to include guzzle in the specific controller.
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
Now, create a method you want to run to call the API and put the below code
$client = new Client(); //GuzzleHttp\Client
$result = $client->post('your-request-uri', [
'form_params' => [
'sample-form-data' => 'value'
]
]);
That's it!
Docs explain this pretty well : https://github.com/guzzle/guzzle
Here is the complete code when using guzzlehttp instead of curl
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'http://10.10.10.7/magento2/rest/V1/customers', array(
headers' => [
'Authorization' => 'OAuth oauth_consumer_key="sganfgvr2naxwmh21jgi5ffijuci0207",oauth_token="d16pdq1avr1rs7h9745rc0x6py65a2vt",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1518006201",oauth_nonce="4ghORA",oauth_version="1.0",oauth_signature="Ztq5ErznqvCl18GomWv0F55t5OA%3D',
'Cache-Control' => 'no-cache',
'Postman-Token' => '5ec55151-3365-7ffc-a6a4-ce5fe5bc451f'
],
'json' => $postdata
));
You also have to install following dependencies in your laravel project for PSR-7 support and look at this stackoverflow question as a reference:
composer require symfony/psr-http-message-bridge
composer require zendframework/zend-diactoros
That caused by you didn't define the Content-Type as application/json on HTTP Header. Please try this
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'http://10.10.10.7/magento2/rest/V1/customers', array(
headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'OAuth oauth_consumer_key="sganfgvr2naxwmh21jgi5ffijuci0207",oauth_token="d16pdq1avr1rs7h9745rc0x6py65a2vt",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1518006201",oauth_nonce="4ghORA",oauth_version="1.0",oauth_signature="Ztq5ErznqvCl18GomWv0F55t5OA%3D',
'Cache-Control' => 'no-cache',
'Postman-Token' => '5ec55151-3365-7ffc-a6a4-ce5fe5bc451f'
],
'json' => $postdata
));
And don't forget to load the dependencies using composer
composer require symfony/psr-http-message-bridge
composer require zendframework/zend-diactoros

need to set headers on guzzle request

I need to add the type of headers to the guzzle request below, but cannot figure out how to put it in without getting an error
This is what I want to add :
$command->set('command.headers', array('content-type' => 'application/x-www-form-urlencoded
to this code below:
<?php
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'form_params' => $post_data,
'verify' => false
]);
$body = $response->getBody();
dsm($body);
?>
When I needed use the Guzzle at D8 to make a POST I passed the Content-Type like this:
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => rawData($post_data),
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
A good idea is use the D8 Dependency Injection to pass the HTTP_CLIENT.

OneDrive REST API error 400 when creating folder

I have a problem when trying to create a folder in my OneDrive using the REST API. I'm using following documentation page https://dev.onedrive.com/items/create.htm. I have successfully authenticated and the token is working ok on other endpoints.
I spent now over a day trying every possible URI/method combination on this one but with no success. All other endpoints (directory listing etc.) are OK, just this one is driving me crazy.
If anyone could point me to the error in my approach, any help would be appreciated.
The code below returns error 400 with following message:
{"error":{"code":"invalidRequest","message":"The request is malformed or incorrect."}}
I'm using GuzzlePhp library for the request handling. My code (simplified):
$parentId = '01WZZ7ZY2LNHB75JADQJD3GGUQFSCRRZTQ'; //id to root
$method = "POST";
//none of these does the trick (to be clear, I use only one at the time)
$url = '/_api/v2.0/drive/items/'.$parentId.'/NewFolder'; //put
$url = '/_api/v2.0/drive/items/'.$parentId.'/children'; //put
$url = '/_api/v2.0/drive/items/'.$parentId.'/children'; //post
$url = '/_api/v2.0/drive/root:/NewFolder'; //post
$options = [
'headers' => [
'Authorization' => $token,
'Content-Type' => 'application/json',
'Content-Length'=> 0,
]
'form_params' => [
"name" => "NewFolder",
"folder" => (object)[],
"#name.conflictBehavior" => "fail"
]
];
//Guzzle library sends the code as specified
$res = $this->client->request($method, $url, $options);
The OneDrive API doesn't support form post semantics - the parameters are expected in the body as a JSON encoded blob. I haven't used Guzzle, but something like this should work:
$parentId = '01WZZ7ZY2LNHB75JADQJD3GGUQFSCRRZTQ'; //id to root
$method = "POST";
//none of these does the trick (to be clear, I use only one at the time)
$url = '/_api/v2.0/drive/items/'.$parentId.'/NewFolder'; //put
$url = '/_api/v2.0/drive/items/'.$parentId.'/children'; //put
$url = '/_api/v2.0/drive/items/'.$parentId.'/children'; //post
$url = '/_api/v2.0/drive/root:/NewFolder'; //post
$options = [
'headers' => [
'Authorization' => $token,
'Content-Type' => 'application/json',
'Content-Length'=> 0,
]
'body' =>
'{
"name": "NewFolder",
"folder": { },
"#name.conflictBehavior": "fail"
}'
];
//Guzzle library sends the code as specified
$res = $this->client->request($method, $url, $options);

Drupal7 REST: I am not able to perform POST and PUT methods. Error is :Not Acceptable : Node type is required, Code:406?

I'm using drupal7. my drupal_http_request() for get and delete are working fine for authenticated users, but the post and put methods are not working.
The error is :Not Acceptable : Node type is required, and http error code is :406. My code is below:
function ws_form_post_auth() {
$base_url = 'http://localhost/drupalws/api/v1';
$data = array(
'username' => 'student1',
'password' => 'welcome',
);
$data = http_build_query($data, '', '&');
$options = array(
'headers' => array(
'Accept' => 'application/json',
),
'method' => 'POST',
'data' => $data
);
$response = drupal_http_request($base_url . '/user/login', $options);
$data = json_decode($response->data);
// Check if login was successful
if ($response->code == 200) {
$options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
$options['headers']['X-CSRF-Token'] = $data->token;
$data = array(
'title' => 'First forum post',
'type'=> 'forum',
'body'=> array(
'und'=>array(
0=> array(
'value'=>'This is my first forum post via httprequest.'
)
)
)
);
$data = json_encode($data);
$options['data'] = $data;
$options['method'] = 'POST';
$response = drupal_http_request($base_url . '/node', $options);
return $response->status_message;
}
return $response->status_message;
}
I got the solution for my issue,I just missed a Content-Type in Headers.
[....]
if ($response->code == 200) {
$options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
$options['headers']['X-CSRF-Token'] = $data->token;
$options['headers']['Content-Type'] = 'application/json';
[....]