I'm trying to make post request and the post request is working but I'm not getting the response
$client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Basic ' . 'token==']]);
$data = $client->post(
'url',
[
'form_params' => [
'address' => 'addreww',
'name' => 'Zia Sultan',
'phone_number' => '2136000000',
]
]
);
return $data;
What I'm getting in my insomnia
Error: Failure when receiving data from the peer
You're code is working, post method returns ResponseInterface, we need to fetch the content from it, we need to first fetch the StreamInterface by calling getBody() and chaining it will getContents() gives us the actual response. Keep debug mode On, to get find the exact error for Error: Failure when receiving data from the peer, and when this error occurs, share the entire trace with us
try {
$response = (new \GuzzleHttp\Client())->post(
'url',
[
'headers' => [
'Authorization' => 'Basic ' . 'token=='
],
'form_params' => [
'address' => 'addreww',
'name' => 'Zia Sultan',
'phone_number' => '2136000000',
],
// 'http_errors' => false, // Set to false to disable throwing exceptions on an HTTP protocol errors (i.e., 4xx and 5xx responses)
// 'debug' => true,
// 'connect_timeout' => 30 // number of seconds to wait while trying to connect to a server, Use 0 to wait indefinitely (the default behavior)
// 'read_timeout' => 10 // timeout to use when reading a streamed body, default value is default_socket_timeout in php.ini
// 'timeout' => 30 // the total timeout of the request in seconds. Use 0 to wait indefinitely (the default behavior).
]
);
return $response->getBody()->getContents();
} catch (Throwable $exception) {
print_r($exception);
}
I was returning the data only but I needed to return getBody() like this way
$data->getBody()
Its working now
Related
I searched online but couldn't find a proper solution. I am calling a Spring service with a POST request using Guzzle Client, The service in case of any errors provides the error message in its URL param like: http://localhost:8085/fedauth/null?errMessage=Mot%20de%20passe%20invalide%20pour%20l'utilisateur%20Karan%20Sharma.. How can I fetch this param errMessage using Guzzle. Below is my code with Slim in PHP.
$data = [
'userName' => base64_encode($userName),
'userPassword' => base64_encode($userPassword),
'institution' => $institution,
'redirectUrl' => $redirectUrl,
'callerUrl' => $callerUrl,
'clientId' => $clientId,
'encryptMode' => $encryptMode,
'moodleLandPage' => $moodleLandPage,
'login' => $login,
'isEncrypted' => true
];
try {
$apiResponse = $client->post( $_ENV['FEDAUTH_API_URL'], ['form_params'=> $data]);
} catch (Exception $exception) {
return $response->write(json_encode(['error' => $exception->getMessage(), "auth" => "0" ]));
}
I have tried using the getEffectiveUrl() method but its no longer supported in Guzzle 7
I guess you get the response as a redirect url? Your question is not clear in that point. In this case you can access it like this:
$apiResponse = $client->post( $_ENV['FEDAUTH_API_URL'], ['form_params'=> $data]);
echo $apiResponse->getEffectiveUrl();
like here: https://docs.guzzlephp.org/en/5.3/http-messages.html#responses
Actually found the answer. You need to add track redirects option as true and then use $response->getHeaderLine('X-Guzzle-Redirect-History'); like below
$client = new GuzzleHttp\Client(['headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded'], 'verify' => false, 'allow_redirects' => ['track_redirects' => true]]);
$apiResponse = $client->post( $_ENV['FEDAUTH_API_URL'], ['form_params'=> $data]);
echo $apiResponse->getHeaderLine('X-Guzzle-Redirect-History');
I have a script that uses guzzle to make an API call. The api server checks for headers and it is case sensitive.
Below is an example code of mine
<?php
$headers = [
'set_headers' => [
'Connection' => 'Keep-Alive',
'Accept-Encoding' => ‘gzip’,
'Accept-Language' => ‘en_US’,
'US-Token' => '1f23a-d234s-3s45d-452g',
'AToken' => 'XXXX'
],
];
// Build HTTP request object.
$request = \GuzzleHttp\Psr7\Request( // Throws (they didn't document that properly).
'POST',
'htps://api.website.com/',
$headers,
bodystream() //StreamInterface
);
// Default request options (immutable after client creation).
$_guzzleClient = new \GuzzleHttp\Client([
'handler' => $stack, // Our middleware is now injected.
'allow_redirects' => [
'max' => 8, // Allow up to eight redirects (that's plenty).
],
'connect_timeout' => 30.0, // Give up trying to connect after 30s.
'decode_content' => true, // Decode gzip/deflate/etc HTTP responses.
'timeout' => 240.0, // Maximum per-request time (seconds).
// Tells Guzzle to stop throwing exceptions on non-"2xx" HTTP codes,
// thus ensuring that it only triggers exceptions on socket errors!
// We'll instead MANUALLY be throwing on certain other HTTP codes.
'http_errors' => false,
]);
// Add critically important options for authenticating the request.
$guzzleOptions = [
'cookies' => ($_cookieJar instanceof CookieJar ? $_cookieJar : false),
'verify' => file_exists('/etc/ssl/certs/cacert.pem') ? '/etc/ssl/certs/cacert.pem' : $_verifySSL,
'proxy' => ($_proxy !== null ? $_proxy : null),
'curl' => [
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2, // Make http client work with HTTP 2/0
CURLOPT_SSLVERSION => 1,
CURLOPT_SSL_VERIFYPEER => false
]
];
// Attempt the request. Will throw in case of socket errors!
$response = $_guzzleClient->send($request, $guzzleOptions); ?>
I tested the same request with cURL and it works perfectly. Is there a way I can rectify this in the guzzle php library, thanks in advance.
First of all: First question here in Stack Overflow, quite an honor! :D
How do i convert the following curl into Guzzle?
curl -u USER_KEY:USER_SECRET https://api.apiexample.com/example/oauth/oauth?grant_type=client_credentials
I tried the following, but i kept getting 403 - Forbidden error:
$res = $client->request('GET', 'https://api.apiexample.com/example/oauth/oauth',[
'auth' => ['USER_KEY', 'USER_SECRET'],
'header' => [
'Content-Type' => 'application/x-www-form-urlencoded'
],
'form_params' => [
'grant_type' => 'client_credentials'
]
]);
What could be wrong with my code?
Edit: Forgot one thing: This request returns a token that lasts for 30 minutes. Any tip to run this function only when the token is about to expire?
I would recommend maybe reformatting your request by putting your constant values in the Client object declaration and also wrapping the request in a try-catch block. The try-catch block provides the added benefit that it will help you debug the response. Feel free to alter the catch statement as you wish.
$client = new Client([
'base_uri' => 'https://api.apiexample.com/example/',
'auth' => [
'USER_KEY',
'USER_SECRET'
]
]);
try {
$response = $client->request( 'GET', 'oauth/oauth', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'form_params' => [
'grant_type' => 'client_credentials'
]
]);
} catch (Exception $e) {
error_log($e->getCode());
error_log($e->getMessage());
error_log(print_r($e->getTrace(), true));
}
I'm trying to submit an application to Greenhouse with the following way:
$url = "https://api.greenhouse.io/v1/boards/{MY_BOARD_TOKEN}/jobs/{MY_JOB_ID}";
$args = [
'headers' => [
'Content-Type' => 'multipart/form-data',
'Authorization' => 'Basic ' . base64_encode('{MY_API_TOKEN}'),
'Cache-Control' => 'no-cache',
],
'body' => $form,
];
$response = wp_remote_post($url, $args);
But I'm getting the following error:
{"status":400,"error":"Failed to save person"}
My $form looks like this:
[
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john#doe.com',
]
I'm sure the credentials are OK.
Thanks in advance,
Status code: 400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot or
will not process the request due to something that is perceived to be
a client error (e.g., malformed request syntax, invalid request
message framing, or deceptive request routing).
Link
Means that need to double check you request to API.
I suggest to test it in some other tool and copy&paste request after that.
You could use Restlet Client - REST API Testing for checking.
I'm trying to delete files from my CloudFlare cache using PHP. Using Guzzle I've done this:
$client = new \GuzzleHttp\Client;
$response = $client->delete('https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache', [
'query' => [
'files' => 'https://example.com/styles.css,
],
'headers' => [
'X-Auth-Email' => 'myemail',
'X-Auth-Key' => 'myapikey',
],
]);
But when I run this I get an error:
Client error: DELETE https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache?files=https%3A%2F%2Fexample.com/etc resulted in a 400 Bad Request response: {"success":false,"errors":[{"code":1012,"message":"Request must contain one of \"purge_everything\", \"files\", \"tags\" (truncated...)
I can't get it to work using Postman either. I put in the required headers and try to set a key of files or files[] with the URL but it doesn't work. I've also tried data with raw JSON as the value like {"files":["url"]} (along with a JSON content-type header) but get the same error. It thinks I'm not sending the files key.
The method for purge_cache is POST instead of DELETE (Source: https://api.cloudflare.com/#zone-purge-files-by-url).
The payload is not sent as 'query', but as 'json'.
Files should be an array, not a string.
So the correct syntax should be....
$client = new \GuzzleHttp\Client;
$response = $client->post('https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache', [
'json' => [
'files' => ['https://example.com/styles.css'],
],
'headers' => [
'X-Auth-Email' => 'myemail',
'X-Auth-Key' => 'myapikey',
],
]);