http://labelary.com/viewer.html
This webservice has an 'undocumented' service where you can post them a png, and then send you back the image encoded as a zpl file (for label printers). don't worry, I'm not trying to do anything they don't want me to do, it's mentioned at the bottom here that they allow this undocumented use of their api
So, when you use the api from within the web portal, it makes a post request to this url: http://api.labelary.com/v1/graphics
If I upload a png and then look in the Network tab of Chrome developer tools, I can see that it posted a Form Data, file: (binary)
In their documentation, they actually recommend this Ruby library: https://github.com/rjocoleman/labelary -- this has implemented into it a way to send the post request with the file up to that url and get the zpl data back.
If you navigate to labelary/lib/labelary/image.rb you can see the code for the encode function:
def encode
response = Labelary::Client.connection.post '/v1/graphics', { file: #file }, { Accept: 'application/json' }
image = response.body
return '^GFA,' + image['totalBytes'].to_s + ',' + image['totalBytes'].to_s + ',' + image['rowBytes'].to_s + ',' + image['data'] + '^FS'
end
It makes that request using the faraday request library, if that's of any relevance.
So basically, I'm trying to implement this request in php+laravel using Guzzle. Now I know how to make a post request, but I don't exactly know how to send an image, and I searched around and came up with this code, which isn't working:
$pngPath = storage_path('image.png'); // this is a confirmed real file on my system in the storage folder
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://api.labelary.com/v1/graphics', [
'headers' => [
'Content-Type' => 'multipart/form-data'
],
'multipart' => [
[
'name' => 'file',
'contents' => fopen($pngPath, 'r'),
]
]
]);
When I make that request, I get this error message that doesn't have much detail: ERROR: HTTP 400 Bad Request
I just needed to modify a bit of my request and it worked -- I think it might have been the Content-Type header messing me up more than anything.
This is what the request looks like now:
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://api.labelary.com/v1/graphics', [
'headers' => [
// 'Content-Type' => 'multipart/form-data'
'Accept' => 'application/json'
],
'multipart' => [
[
'Content-Type' => 'image/png',
'name' => 'file',
'contents' => fopen($pngPath, 'r'),
'filename' => basename($pngPath)
]
]
]);
Sorry for wasting everyone's time!
Related
I try to send the file via GuzzleHTTP from my application to external API, I make it like this:
public function storeImagesInAmazon(Request $request) {
$uploadFilePath = 'some/endpoint';
$file = $request->file('file');
$client = new Client();
$response = $client->request('POST', $uploadFilePath, [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'multipart/form-data',
],
'multipart' => [
[
'name' => 'file',
'contents' => $file
]
]
]);
$result = json_decode($response->getBody(), true);
return [
'hashedID' => $result['hashedID']
];
}
The error I get is:
Server error: POST some/endpoint resulted in a 500 Internal Server Error response:\n
Errorerror while processing file: Failed to process file: part was null
I tested it via Postman, adding key = 'file', value = 'some_file.pdf' in Body form-data, I am sure file is correct, I mean it isn't damaged, I tried to post different files large one, a small one, pdf or jpg/png.
But I still have this issue and I can't find a solution for this.
I found this solution Guzzle form_params not accepting array
what I'm trying to say is, you need $option as your next param like in that post
$response = $client->post('api', $options);
and that $option is where your headers or multipart or other options goes as per documentation. i already tried using $options and its worked in my case.
I am trying to make a post on laravel using Guzzle. I already got one post working but that one doesn't have a header that I need. The problem is when I try to include that same header and raw JSON body I always get the error: MethodNotAllowedHttpException. From my understanding this is the post request function with some structural error (just my thinking).
My code is the following:
$response = $client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json',
'x-auth-token' => $token,
],
'body' => $body
]);
The code above is returning the error.
The following code (from a different function with different goals) just doesn't have the 'x-auth-token' header and it is working just fine:
$response = $client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json',
],
'body' => $body
]);
$token = $response->getHeader('X-Subject-Token')[0];
Update: The error that i get is: Expecting to find auth in request body. The server could not comply with the request sin.
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',
],
]);
I am using "guzzlehttp/guzzle": "~6.0", and trying to post a file to an API endpoint. The file posts fine when using RequestBin but the API is not getting the header it requires. The Header is not sent to Request bin either. According to the docs, I need to do an array of associative arrays. http://docs.guzzlephp.org/en/latest/quickstart.html#post-form-requests
However, this is not working. Here's the Guzzle request:
$client = new GuzzleHttp\Client(['base_uri' => '127.0.0.1:3000']);
$response = $client->request('POST', '/process', [
'multipart' => [
[
'name' => 'file',
'contents' => $file,
'bucketName' => 'test',
'headers' => ['X-API-Key' => 'abc345']
],
]
]);
What am I doing wrong that it's not sending the header?
Thank you very much,
Josh
Headers is an $option, that's mean it must be at the same level as multipart.
<?php
$response = $client->request('POST', '/process', [
'multipart' => [
[
'name' => 'file',
'contents' => 'test',
'bucketName' => 'test',
],
],
'headers' => ['X-API-Key' => 'abc345'] // <------- HERE
]);
You were probably using multipart in conjunction with form_params , this is not explicitly explained in the documentation of laravel but guzzle won't work with both
Note
multipart cannot be used with the form_params option. You will need to
use one or the other. Use form_params for
application/x-www-form-urlencoded requests, and multipart for
multipart/form-data requests.
This option cannot be used with body, form_params, or json
To solve this problem you will need to parse all the params to multipart, if you are using laravel or lumen you can do it in this way
if(!empty($this->files))
{
//if there is an image parse all the rest parameters to
// multipart
$file_keys=array_keys($this->files);
foreach($this->files as $k => $file)
{
$http = $http->attach($k, file_get_contents($file),$k);
}
foreach($this->data as $dk =>&$d)
{
if(!in_array($dk,$file_keys))
{
if(is_array($d))
{
$d=json_encode($d);
}
$http = $http->attach($dk,$d);
}
}
return $http=$http->post($this->url);
}
//if there isn't any file just send all as form_params
return $http=$http->post($this->url,$this->data);