How to solved something went wrong when using guzzle in POST API? - php

My framework is codeigniter and I make libraries like this:
function checkOut($url, $params){
$client = new GuzzleHttp\Client([
'headers' => [ 'Content-Type' => 'application/json' ,'Accept' => 'application/json; charset=utf-8'],
'verify' => false,
'cookies' => true
]);
$response = $client->request('POST', $url, [
'json' => $params
]);
return $response->getBody->getContents();
}
I call that libraries in my controller like this:
$dataArray is some array was i make,
$response_checkout = $this->corekredivo->checkOut($url, $dataArray)
and in view I just parsing to view like this:
$data = array(
'_respon' => $response_checkout
);]
But, when var_dump(); in view the result is:
string(90) "{"status": "ERROR", "error": {"message": "Something went
wrong.", "kind": "APIException"}}"
Before that I tried in a postman and succeeded and the structure of the arrays used is the same.

Looks like that this string ("{"status": "ERROR", "error": {"message": "Something went wrong.", "kind": "APIException"}}") is a valid server response.
I mean that there no error from you side, you get this response from the server. Something went wrong inside the server app and you got this message.
To me it seems that you should be aware of this type of responses and process them somehow in your app.

Related

Paymongo can't disable a webhook

I am trying to disable a webhook of Paymongo via the web console, but it seems I can not disable the webhook. When I do so, the interface shows the error like so:
{
"errors": [
{
"code": "resource_processing_state",
"detail": "Webhook with id hook_L0r3mIp5umD0L0r5itAm3t is still being processed."
}
]
}
It also has a 400 HTTP status code and its PHP code look like so:
<?php
require_once('vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://api.paymongo.com/v1/webhooks/hook_L0r3mIp5umD0L0r5itAm3t/disable', [
'headers' => [
'accept' => 'application/json',
'authorization' => 'Basic someBase64encodedStringOfAKey',
],
]);
echo $response->getBody();
Note: The shown codes above don't contain the exact credentials. I edited these before posting here for privacy reasons.
What does it mean by "Webhook with id hook_L0r3mIp5umD0L0r5itAm3t is still being processed."?

Trying to update data with guzzle

I am using Guzzle and I need to update data, so for this I am trying the following:
$request = $this->guzzleClient->put($this->url, [
'headers' => $this->dcsheaders,
'json' => json_encode([
"status" => "Open",
"accountNumber"=> "01236548",
"reasonId"=>"ccaa8e8d-70ae-466d-b8c8-dd16bc5454e0"
])
]);
$a = $request->send();
var_dump($a);
But I receive
resulted in a 400 Bad Request response
I tried another types like form_params, but I receive 403
The json option is used to easily upload JSON encoded data as the body of a request.
source: json request option guzzle
change to this
$request = $this->guzzleClient->put($this->url, [
'headers' => $this->dcsheaders,
'json' => [
"status" => "Open",
"accountNumber"=> "01236548",
"reasonId"=>"ccaa8e8d-70ae-466d-b8c8-dd16bc5454e0"
]
]);

GuzzleHTTP returns 404 on existing page

My Guzzle POST request to https://api.scarif.dev/auth gives back a 404, while the page exists through Postman, or browser, or javascript. It should return a 200 with a 401 message, but Guzzle gives back a 404. In both POST and GET mode that is.
I've tried multiple Client setups, including different headers and disabling SSL verification, but without any success. Now I've copied the exact same headers that made it work in postman, but still no success.
I've been searching through google and stackoverflow, but couldn't find an answer that fixed my problem.
Request in PHP:
<?php
$client = new Client([
'header' => [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded'
],
'verify' => false
]);
$response = $client->request('POST', 'https://api.scarif.dev/auth', [
'form_params' => []
]);
echo $response->getBody()->getContents();
?>
Expected result:
{
"detail": "https://login.scarif.dev",
"status": 401,
"title": "Unauthorized",
"type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"
}
Actual result:
Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client
error: POST https://api.scarif.dev/auth resulted in a 404 Not
Found response:
404 Not Found Not Found
(truncated...) in
/home/admin/domains/login.scarif.dev/framework/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113
Stack trace: #0
/home/admin/domains/login.scarif.dev/framework/vendor/guzzlehttp/guzzle/src/Middleware.php(66):
GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request),
Object(GuzzleHttp\Psr7\Response)) #1
/home/admin/domains/login.scarif.dev/framework/vendor/guzzlehttp/promises/src/Promise.php(203):
GuzzleHttp\Middleware::GuzzleHttp{closure}(Object(GuzzleHttp\Psr7\Response))
2 /home/admin/domains/login.scarif.dev/framework/vendor/guzzlehttp/promises/src/Promise.php(156):
GuzzleHttp\Promise\Promise::callHandler(1,
Object(GuzzleHttp\Psr7\Response), Array) #3
/home/admin/domains/login.scarif.dev/framework/ven in
/home/admin/domains/login.scarif.dev/framework/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php
on line 113
API endpoint controller:
<?php
namespace Controller;
use Core\Config;
use Core\Request;
use Core\Response;
use Model\Token;
use Model\User;
use MongoDB\BSON\UTCDateTime;
class AuthController extends Controller
{
public function view(User $user, Token $token)
{
extract(Request::getPostData());
if (isset($access_token) && !empty($access_token)) {
$_token = $token->getTokenByToken($access_token);
if (
$_token['type'] !== Token::TYPE_ACCESS_TOKEN ||
$_token['expires_on'] <= new UTCDateTime()
) {
return $this->view->display('json', [
'payload' => Response::apiResponse(
$this->config->get('url.login'), 401
)
]);
}
$token->delete($_token['_id']);
$newToken = $token->create(Token::TYPE_ACCESS_TOKEN, $_token['user_id']);
return $this->view->display('json', [
'payload' => Response::apiResponse($newToken['token'])
]);
}
if (!isset($email) || !isset($password) || empty($email) || empty($password)) {
return $this->view->display('json', [
'payload' => Response::apiResponse(
$this->config->get('url.login'), 401
)
]);
}
if (!$user->checkCredentials($email, $password)) {
return $this->view->display('json', [
'payload' => Response::apiResponse(
"The email address or password you've entered is invalid. Please check your entry and try again.",
422
)
]);
}
$user = $user->getUserByEmail($email);
$token = $token->create(Token::TYPE_ACCESS_TOKEN, $user['_id']);
return $this->view->display('json', [
'payload' => Response::apiResponse($token['token'])
]);
}
}
It seems like the issue is coming from the API you are consuming. When using your code with a different url it works just fine:
$client = new Client([
'header' => [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded'
],
'verify' => false
]);
$response = $client->request('POST', 'https://jsonplaceholder.typicode.com/posts', [
'form_params' => []
]);
echo $response->getBody()->getContents();
Could you show the code for the API endpoints?
I had the same issue and was looking for solutions until I landed here. Didn't get any help online though and solutions of other people didn't work for me but later I solved myself through extensive debugging and I am sharing the solution in a hope it might help someone else in the future.
Scenario: In my case I had an API gateway and client (Postman in my case) was making request to the API gateway and gateway in turn was making request to a microservice using Guzzle 7 in Laravel 8. I used to pass all headers I received from the client to microservice as is and that was causing 404 error. When I changed that and passed only my own headers in the request to the microservice, there was light and 404 was gone.
These were default headers of Postman and I was passing in the request as is:
{
"authorization": [
"Bearer eyJ0eXAiOiJKV1 .."
],
"user-agent": [
"PostmanRuntime/7.29.0"
],
"accept": [
"*/*"
],
"postman-token": [
"ca180f3a-ec65-4212-bd9f-dc294846dc65"
],
"host": [
"sagateway.com"
],
"accept-encoding": [
"gzip, deflate, br"
],
"connection": [
"keep-alive"
]
}
I removed all of it and only passed one thing in the header:
['Authorization' => "<Key Here>"]
It then worked fine and I took a breath of relief after a few days of continuous googling.

JSON param through Guzzle 6 post always errors out

It always errors out saying one of 2 messages.
{"message":"Required field 'specList' is not specified"} or if I add specList then it says '400 Bad Request' response: {"message":"Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token"}
This is what I have:
$client = new GuzzleHttp\Client(['base_uri' => 'https://someURL/PrismGateway/services/rest/v1/']);
$res = $client->request('POST', 'vms/'.$vmId.'/clone',
[
'verify' => false,
'auth' => ['user', 'pass'],
'json' => [
'specList' => '[{"name":"test9"}]'
//tried 'create.dto.acropolis.VMCloneDTO' => '{"specList":[{"name":"test9"}]}'
]
]
);
If I use create.dto.acropolis.VMCloneDTO it tells {"message":"Required field 'specList' is not specified"} and if I change it up to specList it gives me the deserialize error from above. I'm not sure what I'm doing wrong but the actual param in the api is listed as create.dto.acropolis.VMCreateDTO and it expects the specList response as a json data type.
Someone help me figure out why it's not working?
Figured it out. Got rid of the json and added body:
'body' => '{"specList":[{"name":"test9"}]}'

yii2 rest api exception handling

I am using yii2 rest api module in which controller class extends an ActiveController and i have a problem dealing with the error exception . i need a proper json response when HTTP status code that are used by the Yii REST framework like 500 , 400. If i try a wrong method call on access api it show a exception object
object(yii\web\NotFoundHttpException)#170 (8) { ["statusCode"]=> int(404)
In my config/main.php set the response
'response' => [
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
if ($response->data !== null) {
$response->data = [
'success' => $response->isSuccessful,
'data' => $response->data,
];
$response->statusCode = 200;
}
},
]
It should display a msg like:
{
"status": 0,
"error_code": 400,
"message": "Bad request"
}
I have try to add the behaviour verbs in controller using this link : click here
My whole application is based on api so please help me for handling all kind of errors
Also depends on your server configs but usually you don't need any of that. this should be enough:
'response' => [
'format' => yii\web\Response::FORMAT_JSON,
'charset' => 'UTF-8',
],
Here is an output example using those configs: https://yii2-f4a.rhcloud.com/api/tags

Categories