I am trying to hit a POST API Endpoint with Guzzle in PHP (Wordpress CLI) to calculate shipping cost. The route expects a RAW JSON data in the following format:
{
"startCountryCode": "CH"
"endCountryCode": "US",
"products": {
"quantity": 1,
"vid": x //Variable ID
}
}
Link to the API I am consuming: https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate
$body = [
"endCountryCode" => "US",
"startCountryCode" => "CN",
"products" => [
'vid' => $vid,
'quantity' => 1
],
];
$request = $this->client->request(
'POST', 'https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate',
[
'headers' => [
'CJ-Access-Token' => $this->auth_via_cj(), // unnecessary, no auth required. Ignore this header
],
'body' => json_encode( $body )
],
);
I've also tried using 'json' => $body instead of the 'body' parameter.
I am getting 400 Bad Request error.
Any ideas?
Try to give body like this.
"json" => json_encode($body)
I spent so many hours on this to just realise that products is actually expecting array of objects. I've been sending just a one-dimensional array and that was causing the 'Bad Request' error.
In order to fix this, just encapsulate 'vid' and 'quantity' into an array and voila!
You don't need to convert data in json format, Guzzle take care of that.
Also you can use post() method of Guzzle library to achieve same result of request. Here is exaple...
$client = new Client();
$params['headers'] = ['Content-Type' => 'application/json'];
$params['json'] = array("endCountryCode" => "US", "startCountryCode" => "CN", "products" => array("vid" => $vid, "quantity" => 1));
$response = $client->post('https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate', $params);
Related
I'm working on Lavravel 9 with guzzle to send some data in
the below code need to get some data from the database how can get data from the database?.
$response = Http::post('APIurl', [
"headers" => [
//header information
],
"body" => [
'title' => "**Get data from database**",
'body' => "**Get data from database**,
'userId' => 22
],
]);
Thank you
Assuming your API returns a json result, simply call the json() method on the Response object. If you want the raw response body, use body() instead.
For example, take github's api:
$response = Http::get('api.github.com'); // replace with your call
$body = $response->body(); // returns string
$json = $response->json(); // tries to return a json array.
To add data to your request, try passing a json string in the body.
$data = json_encode([
'title' => ...,
'body' => ...,
'user_id' => ...,
]);
$response = Http::post('your-api-here', [
'headers' => [
...
],
'body' => $data,
]);
I am trying to get a response from the Metals API but keep getting 404 errors even though I can get the API using the URL.
public function valueFromApi(){
$accesskey = "123456";
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://metals-api.com/api/latest', [
'form_params' => [
'access_key' => $accesskey,
'base' => 'GBP',
'symbols' => 'XAU',]
]);
dd($response);
}
If I try and access the URL directly through a browser this works:
https://metals-api.com/api/latest?access_key=123456&base=GBP&symbols=XAU
I must have misunderstood the way the parameters are working. Any advice is appreciated.
Form params is not the same as query parameters. Therefor you need to set the parameters as query. If you are accessing this in the browser, i would not expect it to be a POST but a GET.
$response = $client->request('GET', 'https://metals-api.com/api/latest', [
RequestOptions::QUERY => [
'access_key' => $accesskey,
'base' => 'GBP',
'symbols' => 'XAU',
]
]);
I am using the RequestOptions, this is syntaxic sugar for the hardcoded string options, the same as 'query'.
As specified in their docs, you need to define the constant
define("form_params", GuzzleHttp\RequestOptions::FORM_PARAMS );
Then you can use your code
$response = $client->request('POST', 'https://metals-api.com/api/latest', [
'form_params' => [
'access_key' => $accesskey,
'base' => 'GBP',
'symbols' => 'XAU',]
]);
I've managed to go through creating webhook using Shopify API, but I can create only one webhook per request. I've already tried to customize the request so it could possibly create a few webhooks at once, but it doesn't seem to work.
I'm using GuzzleHttp\Client for my requests and this is what my working request look like:
$client = new Client();
$response = $client->request(
'POST',
"https://{$store}/admin/webhooks.json",
[
'headers' => [
'X-Shopify-Access-Token' => $access_token,
'X-Shopify-Shop-Domain' => $store
],
'form_params' => [
'webhook' => [
"topic" => "orders/create",
"address" => $appAddress,
"format" => "json"
],
]
]);
But when I try something like this:
$client = new Client();
$response = $client->request(
'POST',
"https://{$store}/admin/webhooks.json",
[
'headers' => [
'X-Shopify-Access-Token' => $access_token,
'X-Shopify-Shop-Domain' => $store
],
'form_params' => [
'webhook' => [
[
"topic" => "orders/create",
"address" => $appAddress,
"format" => "json"
],
[
"topic" => "orders/delete",
"address" => $appAddress,
"format" => "json"
]
]
]
]);
Im getting this:
POST https://smshopify.myshopify.com/admin/webhooks.json resulted in
a 422 Unprocessable Entity response: {"errors":{"topic":["can't be blank","Invalid topic specified. Topics allowed: app/uninstalled,
carts/create, carts/u (truncated...)
Is there a way to create couple webhooks in one request, I couldn't find a word about it in Shopify documentation, and my attempts to modify request body are not very successful. What I've managed to do is just foreach topics array and to the single request for every webhook.
No, there is no way to create a batch of webhooks in one request. This is true for most Shopify resources - e.g. products must also be created one-by-one.
I am using Shape Shift API for sending transaction with Guzzle. I am always getting the error given in title. My code given below:
$client = new GuzzleHttp\Client();
$data = [
"amount" => 1,
"withdrawal" => '0x23f016d7a8e408e5551ae7aa51b3fe1534165463',
"pair" => 'btc_eth',
"returnAddress" => '12stJs8vZNuuVfjZSSzpLPA96quNissk1b'
];
$result = $client->post( 'https://shapeshift.io/shift', [ 'Content-Type' => 'application/json' ],
[ 'json' => $data ] );
print "<pre>";
print_r( $result->getBody()->getContents() );
print "</pre>";
Same parameters work fine when using in Python.
You are doing the request wrong. The correct variant is with two parameters:
$result = $client->post('https://shapeshift.io/shift', ['json' => $data]);
Content type is configured automatically when you use json option.
I recently tried to use ES. So I set it up in a cloud 9 environnement. I inserted data using a curl request file and I can see them with
http://mydomain/ingredients/aliments/_search?size=350&pretty=true
I then tried to set up elastic SDK (v.2.0) with Silex but I can't get the same output...
Here is my code :
$client = $app['elasticsearch'];
$params = array(
'size' => 350,
'index' => 'ingredients',
'type'=>'aliment',
'body' => array(
'query'=>array(
'match_all' => new \stdClass()
)
)
);
$ingredients = $client->search($params);
The output is NULL but when I do the following :
$params = array(
'index' => 'ingredients',
'type' => 'aliment'
);
$count = $client->count($params);
The output is as expected : {"count":240,"_shards":{"total":5,"successful":5,"failed":0}}
I've already spent a few hours trying to figure what's going on, I tried to replace the 'query' args with a json string, I tried empty array instead of the new stdClass but nothing seems to work.
Edit : I read the documentation again and tried the official example :
$client = $app['elasticsearch'];
$params = [
"search_type" => "scan", // use search_type=scan
"scroll" => "30s", // how long between scroll requests. should be small!
"size" => 50, // how many results *per shard* you want back
"index" => "ingredients",
"body" => [
"query" => [
"match_all" => []
]
]
];
$output = $client->search($params);
$scroll_id = $output['_scroll_id']; /*<<<This works****/
while (\true) {
// Execute a Scroll request
$response = $client->scroll([
"scroll_id" => $scroll_id, //...using our previously obtained _scroll_id
"scroll" => "30s" // and the same timeout window
]
);
var_dump($response); /*<<<THIS IS NULL****/
...
}
And unfortunately got same null result...
What am I doing wrong ?
Thanks for reading.
In my case it works this way:
$json = '{
"query": {
"match_all": {}
}
}';
$params = [
'type' => 'my_type',
'body'=> $json
];
I found out that the inserted data was malformed.
Accessing some malformed data via browser URL seems to be OK but not with a curl command line or the SDK.
Instead of {name:"Yaourt",type:"",description:""} , I wrote {"name":"Yaourt","description":""} in my requests file and now everything work as expected !
#ivanesi 's answer works. You may also try this one:
$params["index"] = $indexName;
$params["body"]["query"]["match_all"] = new \stdClass();