Can’t submit data to API Platform - api-platform.com

I have a controller through which I send data to my local environment of the api platform (which is running fine)
/**
* Creates a new Location entity.
*
*/
public function createAction(Request $request)
{
$this->get("suvya_breadcrumbs.factory")->update('New Hub');
$form = $this->createForm(HubType::class);
$form->handleRequest($request);
$new_url = $this->generateUrl('new_hub');
$redirect_url = $this->generateUrl('home');
if ($form->isSubmitted() && $form->isValid()) {
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'form_params'=> $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Content-Type'=> 'application/json',
'Authorization'=> 'eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJhZG1pbiIsImlhdCI6MTUxNzg3NjE1NCwiZXhwIjoxNTE3ODc5NzU0fQ.gIG9lueJJZxzkOl8qblhHWwiJvW97m4gz1-1mYeM9SgMzMW35Wh6XamOOYiISDN99yJ6Ovo-wKk6whpE5UGMDVw_wGek003Dd6r-Y7Ql3kVLHksn2JFzhAN3GwlXFcOI4MIjmq5qBhkzv21pHymO0yn1SlzWBwb0O7WygywefMu5p09zGuvAiP9I2ShyQLZhjj8bB_odf3dI-Ql0ZbRmn_JDkDoPcm5U11i-3S1oMikBmFq0WtTcWo7vezt3QdA3bY4_bgaISINAiYRR-_cvjpBSqFSE6n1ZYtHvKFn-98wXXsBGxEAoZw6iQL4iRgOI8F_uaiCo0eRHC7q0_xQ_V_W0-5XDIQXWDwoiVaUXnjO6xo2Fldp7PLO1ueJz1e4wiOy2-TunZdc8UCtw2BdFIQtWatPLi_v_rsNvF2H-6hwa9UOKEi9Z4tH4KkuATbXAxxfkCbSOyY1SAWP0riooPQi_AI2J7L2Ly86eAuKo1Hix3EuEogo19GSyBz_cCWczyERQWM9gikuUs8E22SIAdxTl8ZLFaXgiZIibDvb8pqcN8izFjywWbF2CkyWC58WxrVd6Bfmfnm7k9T6oZqwIZ-TQR-SbRnUHN1hpWUjFCk-tHhgvh7osHXmxe3grzA8M3LPBpQGQiTeqBZFMjF4Tx8zW2tuiEn6TwhV14Lj24Vc'
]
]);
die();
}
return $this->render('SuvyaFabricsCloudBundle:Common:basic.html.twig', array(
'form' => $form->createView(),
'page_title'=> 'Hub aanmaken',
'action_path' => $new_url,
'cancel_path'=> $redirect_url,
'submit_button_title' => 'Opslaan',
));
}
But unfortunately i'm getting an error in my dev.log of the api environment:
[2018-02-06 02:32:37] request.INFO: Matched route "api_hubs_post_collection". {"route":"api_hubs_post_collection","route_parameters":{"_controller":"api_platform.action.post_collection","_format":null,"_api_resource_class":"AppBundle\\Entity\\Hub","_api_collection_operation_name":"post","_route":"api_hubs_post_collection"},"request_uri":"http://127.0.0.1:8000/hubs","method":"POST"} []
[2018-02-06 02:32:37] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Serializer\Exception\UnexpectedValueException: "Syntax error" at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php line 78 {"exception":"[object] (Symfony\\Component\\Serializer\\Exception\\UnexpectedValueException(code: 0): Syntax error at /Users/myname/Sites/suvyalogistics-api/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php:78)"} []
The output of form->getData():
array (size=4)
'postalCode' => string 'sdfdsf' (length=6)
'streetName' => string 'sdfsdf' (length=6)
'doorNumber' => string 'sdfsfd' (length=6)
'city' => string 'sdfsfd' (length=6)
Running the endpoint at the api platform with the same values goes fine as well.
Does anyone of you has an idea why this goes wrong?

You're sending a payload encoded in application/x-www-form-urlencoded (HTML form like) to the API Platform API, while, according to the headers you've set, it excepts data encoded in JSON.
To encode the data of the form in JSON, you can use the following Guzzle snippet:
$client = new Client([
'base_uri' => 'http://127.0.0.1:8000',
]);
$response = $client->request('POST', '/hubs', [
'json' => $form->getData(),
'headers' => [
'Accept' => 'application/ld+json',
'Authorization'=> '...'
]
]);
Alternatively, you can configure API Platform to accept form data, but I would not recommend going this way (it's better to only deal with JSON API-side).

Related

cURL Error: Operation timed out after 15001 milliseconds with 0 bytes received woocomerce API

Facing cURL Error: Operation timed out after 15001 milliseconds with 0 bytes received issues with Woocomerce API to create products.
I am using the Laravel package i.e https://github.com/Codexshaper/laravel-woocommerce
It was working fine and creating products but suddenly it stopped working and start throwing PHP errors.
Below are the method that I am using to create a book on Woocomerce from laravel Controller:
public function addProductToWC(Request $request)
{
set_time_limit(0);
$response = '';
if ($request->isMethod('post')){
if(!empty($request->get('book_id'))){
$book = Book::find($request->get('book_id'));
$coverImgPath = base_path('public/customize_book/'.Session::get('cover_image'));
if (file_exists($coverImgPath)) {
$imageurl = url('/public/customize_book/'.Session::get('cover_image'));
} else {
$imageurl = url('/images/'.$book->bookimage);
}
if(!empty($book->id)){
$data = [
'name' => $book->title,
'type' => 'simple',
'regular_price' => number_format($request->get('book_price')),
'description' => (!empty($book->description) ? $book->description :''),
'short_description' => 'Simple product short description.',
'categories' => [
[
'id' => 1
]
],
'images' => [
[
'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg'
],
[
'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg'
]
]
];
$product = Product::create($data);
if($product['id']){
$response = array('error' => false,'code' => '200', 'data' => array('product_id' => $product['id'], 'message' => 'Product created successfully.'));
}else{
$response = array('error' => true,'code' => '401', 'data' => array('product_id' => $product['id'], 'message' => 'Product syncing failed please try again later.'));
}
}else{
$response = array('error' => true,'code' => '401','message' => 'Invalid book detail please try again.');
}
}else{
$response = array('error' => true,'code' => '401','message' => 'Invalid book detail please try again.');
}
}else{
$response = array('error' => true,'code' => '401','message' => 'Invalid method please try again.');
}
// return response
return response()->json($response);
}
Looking at the composer.json at https://github.com/Codexshaper/laravel-woocommerce/blob/master/composer.json, I can see that they are using the woocommerce client "automattic/woocommerce": "^3.0" This defaults to a request timeout of 15 seconds, hence why set_time_limit(0); didn't fix the issue.
When using it directly you'd set the timeout in the options
$woocommerce = new Client(
env('MGF_WOOCOMMERCE_API_URL'), // Your store URL
env('MGF_WOOCOMMERCE_API_KEY'), // Your consumer key
env('MGF_WOOCOMMERCE_API_SECRET'), // Your consumer secret
[
'timeout' => 120, // SET TIMOUT HERE
'wp_api' => true, // Enable the WP REST API integration
'version' => 'wc/v3' // WooCommerce WP REST API version
]
);
Looking at the library source https://github.com/Codexshaper/laravel-woocommerce/blob/master/src/WooCommerceApi.php
$this->client = new Client(
config('woocommerce.store_url'),
config('woocommerce.consumer_key'),
config('woocommerce.consumer_secret'),
[
'version' => 'wc/'.config('woocommerce.api_version'),
'wp_api' => config('woocommerce.wp_api_integration'),
'verify_ssl' => config('woocommerce.verify_ssl'),
'query_string_auth' => config('woocommerce.query_string_auth'),
'timeout' => config('woocommerce.timeout'),
]
);
It looks like the timeout is coming from woocommerce.timeout in your Laravel config file.

Laravel Shopify API returns Required parameter missing or invalid on POST Request

I am using Osiset's github for laravel + shopify: https://github.com/osiset/laravel-shopify
But I don't seem the get the POST request going, tried all kinds of variantions already hope one of you'll see my mistake!
Code:
$order_array = [
'order' => [
'email' => "foo#example.com",
'line_items' => [
'variant_id' => 6103067132088,
'quantity' => 1
]
]
];
$order_array = json_encode($order_array);
$shop = User::first();
$request = $shop->api()->rest('POST', '/admin/orders.json', ['body' => $order_array]);
dd($request['body']);
if I do a dd() on order_array after the encode it shows:
{"order":{"email":"foo#example.com","line_items":{"variant_id":6103067132088,"quantity":1}}}
And then it returns
array:1 [
"order" => "Required parameter missing or invalid"
]
I've also tried to make 'body' to 'query'...
I finally found the solution!
// Replace rest
$request = $shop->api()->rest('POST', '/admin/orders.json', ['body' => $order_array]);
// With request
$request = $shop->api()->request('POST', '/admin/orders.json', $order_array);

How to send bulk data through Guzzle?

I am implementing an API that needs to receive data from my database. The data comes from my 'Products' table. I organized the products that I want to send through Guzzle.
public function post()
{
$product = Product::where('erp_status', '=', 1)->limit(5)->offset(0)->get();
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://httpbin.org',
// You can set any number of default request options.
'timeout' => 2.0,
]);
And right after I created a foreach to send the data through the URL.
foreach($product as $prod){
set_time_limit(0);
$r = $client->request('POST', 'https://api.mercadolibre.com/items?access_token=XXXXXXXXXXXXXXXXXXX', [
'json' => [
'title' => $prod->description->erp_name,
'category_id' => 'MLB46511',
'price' => 10,
'currency_id' => 'BRL',
'available_quantity' => 10,
'buying_mode' => 'buy_it_now',
'listing_type_id' => 'gold_special',
'condition' => 'new',
'description' => 'Teste',
'pictures' => [
['source' => $prod->image->erp_image]
]
]
]);
}
return view('home');
}
But every time I run. It returns the message:
cURL error 28: Operation timed out after 2012 milliseconds with 0 out of 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
My variable $product have 5 thousand rows.
Does Guzzle support this amount? Is it possible to use the guzzle in this case or what is the pure PHP script?
Any suggestion?

Guzzle 6 Async request return Argument 1 passed must be of the type array, string given,

I'm trying to make an asynchronous POST call, but guzzle call returns the following error:
" ErrorException in Request.php line 220:
Argument 1 passed to Symfony\Component\HttpFoundation\Request::__construct() must be of the type array, string given, called in C:\Program Files ...\app\Http\Controllers\ConfirmAccountController.php on line 87 and defined "
In ConfirmAccountController:
$client = new Client(['base_uri' => 'correct_api_address']);
$request = new Request('POST', 'testpromoboiler/updateUser', [
'query' => ['token' => $user->sdg_token ,
'address' => $user->address ,
]
]);
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
Why I get this error?
I have done two other synchronous calls and everything went well.
Thanks
That code instantiates Laravel frameworks Request class.
Use guzzles request method instead:
$request = $client->request('POST', 'testpromoboiler/updateUser', [
'query' => ['token' => $user->sdg_token ,
'address' => $user->address ,
]
]);

guzzle client throws exception in laravel

I am trying to make a http post request in laravel as below
$client = new Client(['debug'=>true,'exceptions'=>false]);
$res = $client->request('POST', 'http://www.myservice.com/find_provider.php', [
'form_params' => [
'street'=> 'test',
'apt'=> '',
'zip'=> 'test',
'phone'=> 'test',
]
]);
It return empty response. On debugging ,following exception is occurring
curl_setopt_array(): cannot represent a stream of type Output as a STDIO FILE*
I am using latest version of guzzle.
Any idea how to solve it?.
The request() method is returning a GuzzleHttp\Psr7\Response object.
To get the actual data that is returned by your service you should use:
$data = $res->getBody()->getContents();
Now check what you have in $data and if it corresponds to the expected output.
More information on using Guzzle Reponse object here
I had to do this
$data = $res->getBody()->getContents();<br>
but also change<br>
$client = new \GuzzleHttp\Client(['verify' => false, 'debug' => true]);<br>
to<br>
$client = new \GuzzleHttp\Client(['verify' => false]);
Here is what i did for my SMS api
use Illuminate\Support\Facades\Http; // Use this on top
// Sample Code
$response = Http::asForm()
->withToken(env('SMS_AUTH_TOKEN'))
->withOptions([
'debug' => fopen('php://stderr', 'w') // Update This Line
])
->withHeaders([
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/x-www-form-urlencoded',
])
->post($apiUrl,$request->except('_token'));

Resources