Converting command cURL to PHP - Stuck with passing POSTFIELD data - php

In an attempt to replicate the following cURL:
curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'Authorization: Bearer XXXXXXXXXX-XXXXXXXXXXX' 'https://XXXXXXXXX.XXX.com/api/v3/assets/76c860cd184ae4adfa105d46135c9b27.json' -F 'name=fileupdate99.pdf' -F 'description=curlviaphp'
The purpose of the call is to update the two fields (name & description) at this specific end point.
I used https://incarnate.github.io/curl-to-php/ to get the bulk of the conversion. However, I appear to be stuck on passing the data.
From what I can tell, it looks like the -F flag is expected (also used to upload files) and I can't make a swap to -d (I tried running call in the command line and -d wasn't accepted).
<?php
$subdomain = "XXXXXXXX";
$name = "fileupdate4.pdf";
$description = "curlviaphp";
$auth = "XXXXXXXXXX-XXXXXXXXXXX";
$asset = "76c860cd184ae4adfa105d46135c9b27";
$ch = curl_init();
$curlurl = "https://" . $subdomain . ".XXX.com/api/v3/assets/" . $asset . ".json' ";
$variables = array(
"name" => $name,
"description" => $description,
);
curl_setopt($ch, CURLOPT_URL, $curlurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $variables);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Content-Type: multipart/form-data";
$headers[] = "Accept: application/json";
$headers[] = "Authorization: Bearer " . $auth;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo "Error:" . curl_error($ch);
}
curl_close($ch);
echo $result;
?>
When I execute, the code runs and I get a blank page (no return and no change on the receiving end).
What am I missing?

Related

Php cURL with calling an API with GRAPHQL

I am trying to call an api called Wave I have used cURL before but never with GRAPHQL queries. I am wondering what is wrong with the below when using cURL. I get an error Bad Request Below is an exmple of my code.
This is what the API cURL is
curl -X POST "https://reef.waveapps.com/graphql/public" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: application/json" \
-d '{ "query": "query { user { id defaultEmail } }" }'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://reef.waveapps.com/graphql/public');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "query": "query { user { id defaultEmail } }');
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer 1212121';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
Any help would be helpful.
For those wanting to query a GraphQL service WITHOUT a third party library, I basically took Brian's code and tested against a GraphCMS service I had already written Node.js code for. So I knew the url, authorization token, and query all worked.
<?php
$endpoint = "https://api-euwest.graphcms.com/v1/[[your id number here]]/master";//this is provided by graphcms
$authToken = "[[your auth token]]";//this is provided by graphcms
$qry = '{"query":"query {products(where:{status:PUBLISHED}){title,img,description,costPrice,sellPrice,quantity,sku,categories {name},brand {name}}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
?>
All worked fine.
The auth token is a big long character string provided by GraphCMS and only needs to be passed in the header. So no real tricky authentication process - as long as you have the token.
I can recommend using https://github.com/softonic/graphql-client, it has worked great for us.
A way easier way to go about doing this is by using an API platform. I often use Postman, the platform have the functionality to give you the PHP cURL code for a GraphQL request in the GraphQl tools part of the application.
You can create your own client passing whatever middleware you'd like:
$clientWithMiddleware = \MyGuzzleClientWithMiddlware::build();
$graphQLClient = new \Softonic\GraphQL\Client(
$clientWithMiddleware,
new \Softonic\GraphQL\ResponseBuilder()
);
For an example how to build a Guzzle client with middleware you can check this out:
https://github.com/softonic/guzzle-oauth2-middleware/blob/master/src/ClientBuilder.php
If there is no authentication
You can use file_get_contents instead of curl
$url = http://myapi/graphql?query={me{name}}
$html =file_get_contents($url);
echo $html;
use json in query paramter for graphql;
Bit late but I made this code
$endpoint = "https://gql.waveapps.com/graphql/public";
$authToken = ""; //Your Bearer code
$qry = '{"query": "query {user {id firstName lastName defaultEmail createdAt modifiedAt}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
var_dump($result);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}

How to properly set headers for a json request through curl

I am new at API´s, Curl and Json. I need to link my appilcation with the an API.
The API I want to connect with has a CURL example which is this:
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X GET https://www.api.com -u 'user:token'
I have made some research and I make a request like this:
$url = "https://www.api.com";
$headers = array(
-H "Accept: application/json",
-H "Content-type: application/json"
-u 'Authorization: Basic '. base64_encode("user:token") // <---
);
//initializing curl object
$curl = curl_init();
//adding fields to the curl object to enter the site
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
//executing the curl call and getting data back
$json = curl_exec($curl);
curl_close($curl); // close the connection
//echo $json;
return $json;
I get the Json request but I still don´t understand the example the API gives. I even don´t know if I am setting well the Curl.
can someone explain to me how can I interpret the Curl example if I doing it well ?
This is not valid PHP syntax:
$headers = array(
-H "Accept: application/json",
-H "Content-type: application/json"
-u 'Authorization: Basic '. base64_encode("user:token") // <---
);
You should use this instead:
$headers = array(
'Accept: application/json',
'Content-type: application/json',
);
And for the auth, use this:
curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);

Curl -H flag in php

I have to make a call to an API and I have the terminal command that works but I can't seem to make it work with php (I get 403 forbidden error). This is the call that works:
curl -X GET -H "mail: mail#api.com" -H "password: XXX" "http://api.com/rest/v1"
This is what I have in PHP so far:
$url = "http://api.com/rest/v1";
$headers = array(
"Content-type: application/json",
"Accept: application/json",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$auth = array('mail: mail#api.com', 'password: XXX');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($auth));
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
The var_dump shows bool(true) but I also get the 403 error message. I also tried adding the email/password in the headers but didn't work. Like this (and removing the CURLOPT_POSTFIELDS line):
$headers = array(
"Content-type: application/json",
"Accept: application/json",
'mail: mail#api.com',
'password: XXX'
);
-H is a header for the curl command line, so why are you setting them as the postfields?
Seems like it should be:
$headers = array('mail: mail#api.com', 'password: XXX');
This should be the same as your CLI command above. If this doesn't work, check the output of curl_exec() to see what the server is responding.

How to use PHP CURL function to do the same request?

Here is my curl commaad line .
curl -u 'username:password' -X GET -H 'Accept: application/json' -H 'Content-Type: application/xml' -d '<request><layout>1</layout><filtermode>category</filtermode><filtervalue>115399046</filtervalue><limit>1</limit><start></start><sortfield></sortfield><sortdir></sortdir></request>' https://example.com/contacts
I use curl command line. It works for me. Now, I need do it in PHP.
The hard part is: The server accept GET request, but need a xml string in request body. I have tried to change GET to POST, the server did NOT return the correct message.
<?php
$ch = curl_init();
$credentials = "user:pass";
$data = 'xml string';
$page = "/contacts";
$headers = array( "GET ".$page." HTTP/1.0", "Content-type: application/xml", "Accept: application/json", "Authorization: Basic " . base64_encode($credentials) );
curl_setopt($ch, CURLOPT_URL, 'example.com/contacts');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$ret = curl_exec($ch);
?>
You can't put the GET line in $header, that causes an invalid header to be sent. The PHP equivalent of -X GET is:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

My command line curl is working correctly, but my php curl is getting an error. (Twitter rest api) [duplicate]

How can i send a CURL request mentioned below in PHP? What functions i will use in php?
$ curl -H 'X-Sifter-Token: 343b1b831066a40e308e0af92e0f06f0' \
-H 'Accept: application/json' \
'http://example.sifterapp.com/api/projects'
I have tried this code.. but its not working..
Please do the needful
$curlString = "";
$curlString .= "-H \"X-Sifter-Token: 343b1b831066a40e308e0af92e0f06f0\" \";
$curlString .= "-H \"Accept: application/json\" \";
$url="http://example.sifterapp.com/api/projects";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlString);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
You do not use correctly CURLOPT_HTTPHEADER. From the manual:
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_HTTPHEADER An array of HTTP header fields to set, in the
format array('Content-type: text/plain', 'Content-length: 100')
So you would need:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-Sifter-Token: 343b1b831066a40e308e0af92e0f06f0',
'Accept: application/json',
));

Categories