I am trying to make a curl request!
Here I can make this request using postman and I am getting response perfectly using postman:
My Body parameter is: sub_domain
and my header is x-api-key value is something ZYWHUYAOSYSOASYYY
Ind i can get response perfectly!
But here want to make curl request on my end:
My Controller Code:
public function curlPost()
{
$data1 = [
'sub_domain' => 'value_1',
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://uwxcdwsc0k.execute-api.us-east-
1.amazonaws.com/prod/domain",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30000,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data1),
CURLOPT_HTTPHEADER => array(
// Set here required headers
"x-api-key: KiZTkTO9Ex2ZCOr7xmYRA4bInlJc9kVNrVN2INrc",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
print_r(json_decode($response));
}
}
and my Routes/api.php:
Route::post('subdomain', 'ApiController#curlPost');
and when i hit post request using postman i get error
stdClass Object
(
[code] => [422] Unprocessable Entity
[message] => sub_domain is required
)
Your help will be highly appreciated!
Add this to your header array,
'Content-Type:application/json'
Make the $data an array as below:
$data1 = array(
'sub_domain' => 'value_1'
);
Cheers
Related
I am attempting to use Auth0 to secure an API on Laravel Framework 8.83.22
I am using this tutorial (machine-to-machine) https://auth0.com/blog/build-and-secure-laravel-api/
Problem:
Curl at the command line works fine:
curl -X GET -H "Authorization: Bearer ***REMOVED***" -H "Content-Type: application/json" -d "{}" http://localhost:8000/api/weightrecords/4195
However, making the call inside a PHP script times out (I've tried longer timeouts with no help). I get the token fine (SECTION 1 below) but SECTION 2 times out (cURL Error #:Operation timed out after 30000 milliseconds with 0 bytes received).
public function test_api()
{
//SECTION 1: Get the token
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://**REMOVED***.auth0.com/oauth/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\"client_id\":\"qDpVdykOlRYkxOdq8J7a2CJ7X7E3WUK8\",\"client_secret\":\"**REMOVED**\",\"audience\":\"**REMOVED**",\"grant_type\":\"client_credentials\"}",
CURLOPT_HTTPHEADER => array(
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$response_array = json_decode($response);
$access_token = "authorization: Bearer " . $response_array->access_token;
echo $access_token;
}
//SECTION 2: Use the token
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_VERBOSE => true,
CURLOPT_URL => "http://127.0.0.1:8000/api/weightrecords/4195",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
$access_token
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
.env
AUTH0_STRATEGY=api
AUTH0_DOMAIN=**REMOVED**.us.auth0.com
AUTH0_CLIENT_ID=qDpVdykOlRYkxOdq8J7a2CJ7X7E3WUK8
AUTH0_AUDIENCE=**REMOVED**
API_IDENTIFIER=**REMOVED**
kernal.php
protected $routeMiddleware = [
//...all the defaults...
'jwt' => \App\Http\Middleware\CheckJWT::class, //<<<<------Added
];
api.php
Route::apiResource('weightrecords', ApiController::class);
CheckJWT.php and auth.php same as in article..
What does $access_token look like?
Try using the post data without the escapes.
You may need to urlencode() the json. Typically not, but I have had it help with one API.
This is how I begin the trouble shooting process.
Add these options.
CURLOPT_CONNECTTIMEOUT=>10,
CURLOPT_FAILONERROR=>true,
CURLINFO_HEADER_OUT=>true,
Get the curl_getinfo:
$response = curl_exec($curl);
$err = curl_error($curl);
$info = var_export(curl_getinfo($curl),true);
echo $info;
You should see the out going request header in $info because of the CURLINFO_HEADER_OUT=>true.
I have a PHP script where it returns details about the request including Body, $_POST, $_GET, $_REQUEST, $_SERVER
LINK to see your request details
You can use this link as your curl URL.
I'm very new to PHP and API, and my company was asked for a job of incorporating API calls on a PHP website.
This is the info about the API that the client gave to us:
API Manual
General Notes:
API URL: https://www.somedomain.com/api/
apiKey: 123qwe456rty678yui
HTTP Verb: POST
Content-Type: application/x-www-form-urlencoded
1. {EMPLOYEES category}
POST /en/1001/cat/10
POST /en/1001/cat/10/page/[999]
Observations:
• the list returns 20 records
• to get the reamining records: /en/1001/cat/10/page/2; /en/1001/cat/10/page/3; ...
• the information is returned in JSON format
• all the requests should be made by the POST method and the api key should be sent on the request body
Input variables:
• apiKey => App key
Return parameters:
retCode = “error”
retCode = “ok”
(...)
2. {NEWS category}
POST /en/2002/cat/20
POST /en/2002/cat/20/page/[999]
Observations:
• the list returns 20 records
• to get the reamining records: /en/2002/cat/20/page/2; /en/2002/cat/20/page/3; ...
• the information is returned in JSON format
Input variables:
• apiKey => App key
Return parameters:
retCode = “error”
retCode = “ok”
(...)
And I've made a simple PHP script but I'm getting an empty return value:
<?php
//API URL: https://www.somedomain.com/api/
//This is to test the Employees category - /en/1001/cat/10
$curl = curl_init();
$apiKey = urlencode("123qwe456rty678yui");
//$apiKey = "123qwe456rty678yui";
//it doesn't matter if this variable is urlencoded or not, as the result is always empty...
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.somedomain.com/api/en/1001/cat/10",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_SSL_VERIFYPEER => "false",
CURLOPT_POSTFIELDS => "apiKey=$apiKey",
CURLOPT_HTTPHEADER => array(
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo "Response: " . $response;
}
?>
Like I said, I'm very new to this, PHP and API's, and the client isn't very helpful.
Based on the Manual API I have, what I'm doing wrong? $response is always empty, it gives no error even if I enter a wrong API Key, and I don't even know if I'm calling this the correct way...
Thanks in advance!
Here is a function that should work from the manual: https://www.php.net/manual/en/function.curl-setopt-array.php#89850
<?php
function get_web_page($url, $curl_data )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_POST => 1, // i am sending post data
CURLOPT_POSTFIELDS => $curl_data, // this are my post vars
CURLOPT_SSL_VERIFYHOST => 0, // don't verify ssl
CURLOPT_SSL_VERIFYPEER => false, //
CURLOPT_VERBOSE => 1 //
);
$ch = curl_init($url);
curl_setopt_array($ch,$options);
$content = curl_exec($ch);
$err = curl_errno($ch);
$errmsg = curl_error($ch) ;
$header = curl_getinfo($ch);
curl_close($ch);
// $header['errno'] = $err;
// $header['errmsg'] = $errmsg;
// $header['content'] = $content;
return $header;
}
$curl_data = "var1=60&var2=test";
$url = "https://www.example.com";
$response = get_web_page($url,$curl_data);
print '<pre>';
print_r($response);
?>
You can also try the file_get_contents function to get this JSON data.
Something like this could do the job:
// API URL
$apiUrl = 'https://www.somedomain.com/api/en/2002/cat/20';
// Request options
$opts = [
"http" => [
'method' => 'POST',
'header' => [
'Content-Type: application/x-www-form-urlencoded',
'apiKey: 123qwe456rty678yui'
]
]
];
// Request context
$context = stream_context_create($opts);
// Get JSON
$json = file_get_contents($apiUrl, false, $context);
Try and see if you can adapt it.
I have the following php code from my API console on RapidApi working correctly:
<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://webit-computer-vision.p.rapidapi.com/describe",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"\r\n\r\n\r\n-----011000010111000001101001--\r\n\r\n",
CURLOPT_HTTPHEADER => [
"content-type: multipart/form-data; boundary=---011000010111000001101001",
"x-rapidapi-host: webit-computer-vision.p.rapidapi.com",
"x-rapidapi-key: XXXXXXXXXX"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The only problem is that it also includes a file which is sent to the endpoint. How can I upload file to the given endpoint? The content-type appears to already be set correctly. I believe I just need to send the content of file in addition.
for anyone wondering, I was able to get it working by modifying the header with this code:
CURLOPT_HTTPHEADER => [
"content-type: multipart/form-data",
"x-rapidapi-host: webit-computer-vision.p.rapidapi.com",
"x-rapidapi-key: VMssAjUwitmshMGT0yv1SbvOhkLVp1f3BaqjsnpKZ8t9yLcbxs"
]
and then had to change the following to get the image file to POST properly:
$fields = [
'image' => new \CurlFile("images/2021_04_01_Ied8W_Ex0P-meVoActjCQ.jpg", 'image/jpeg', 'filename.jpg')
];
...
CURLOPT_POSTFIELDS => $fields,
...
started working pretty quickly after that =)
I am working on third party api integration using oauth1.0 in php.
all get methods working but only post method api not working giving oauth verification failed.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://samplewebsite.com/generatebill",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\r\n\"availableTripId\": \"2000002130750088374\",\r\n\"boardingPointId\": \"220692\",\r\n\"droppingPointId\": \"208070\",\r\n\"destination\": \"3\",\r\n\"inventoryItems\": [{\r\n\"fare\": \"105.00\",\r\n\"ladiesSeat\": \"false\",\r\n\"passenger\": {\r\n\"address\": \"S.K.C ROAD\",\r\n\"age\": \"34\",\r\n\"email\": \"univerttt#gmail.com\",\r\n\"gender\": \"MALE\",\r\n\"mobile\": \"9933336069\",\r\n\"name\": \"PRAKASH RAO \",\r\n\"primary\": \"true\",\r\n\"title\": \"Mr\"\r\n},\r\n\"seatName\": \"2\"\r\n}],\r\n\"source\": \"102\"\r\n}",
CURLOPT_HTTPHEADER => array(
"Authorization: OAuth oauth_signature_method='HMAC-SHA1', oauth_signature='6NzsraQZ0GcfEKxcOXYP4fRqZxQ%3D', oauth_nonce='5cf2603501283', '
. 'oauth_timestamp='1559388213', oauth_consumer_key='xxxxxxxxxx', oauth_version='1.0','Content-Type: application/json'"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
if let me know there is any good library for oauth1.0 and what is problem in my code
Please try to use json_encode() function instead of manually adding JSON string in CURLOPT_POSTFIELDS parameter. Sometimes manually adding string, we missed comma, quote or double quote matching.
$arrParams = [
'availableTripId' => '2000002130750088374',
'boardingPointId' => '220692',
'droppingPointId' => '208070',
...
];
$postParams = json_encode($arrParams);
curl_setopt_array($curl, array(
...
CURLOPT_POSTFIELDS => $postParams,
...
));
Hope it may helpful to you!
I have a question ..
My app gives me the following information:
HTTP + JSON
The following are sample HTTP requests and responses. The placeholders shown need to be replaced with actual values.
POST /json/reply/Zona
HTTP/1.1
Host: equatepro.azurewebsites.net
Content-Type: application/json
Content-Length: length
{"zonaId":0,"nombre":"String","creadoPor":"String","creadoFecha":"/Date(-62135596800000-0000)/","modificadoPor":"String","modificadoFecha":"/Date(-62135596800000-0000)/","estado":"String","nota":"String","borrar":false}
AND then
The following routes are available for this service:
POST /api/zonas
PUT /api/zonas/{zonaId}
enter image description here
enter image description here
I'm trying to communicate with my webservice using PUT method
My code
<?php
$pantalla="zonas";
%id =8;
$url= "http: //miapp.com /api/zonas/8".$pantalla ;
$url = $url ."/" . $id;
// complete url http://miapp.com/api/zonas/8
//build json
$ConstructorJson = array(
'ZonaId' => $Datos['txt_codigo'],
'Nombre' => $Datos['txt_Nombre'],
'CreadoPor' => $Datos['txt_CreadoPor'],
'CreadoFecha' => $Datos['txt_CreadoFecha'],
'ModificadoPor' => $Datos['txt_ModificadoPor'],
'ModificadoFecha' => $Datos['txt_ModificadoFecha'],
'Estado' => $Datos['cbo_Estado'],
'Nota' => $Datos['txt_Notas']
);
$json = json_encode($ConstructorJson);
$opts = array(
"http" => array(
"method" => "PUT",
"header" => "Accept: application/xml\r\n",
"content" => $json
)
);
$context = stream_context_create($opts);
$response = file_put_contents($url,'8',false,$context);
?>
Give me the following error
Warning: file_put_contents(http: //miapp .com/api/zonas/8): failed to open >stream: HTTP wrapper does not support writeable connections in C:\xampp\htdocs\Codigo2.0\models\zonas.model.php on line 34
and nothing happens.
I would rather connect using PHP curl.
$ConstructorJson = array(
'ZonaId' => $Datos['txt_codigo'],
'Nombre' => $Datos['txt_Nombre'],
'CreadoPor' => $Datos['txt_CreadoPor'],
'CreadoFecha' => $Datos['txt_CreadoFecha'],
'ModificadoPor' => $Datos['txt_ModificadoPor'],
'ModificadoFecha' => $Datos['txt_ModificadoFecha'],
'Estado' => $Datos['cbo_Estado'],
'Nota' => $Datos['txt_Notas']
);
$json = json_encode($ConstructorJson);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http: //miapp.com/api/zonas/8/zonas",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => $json
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"Accept: application/xml\r\n",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
HTTP wrapper does not support writeable connections - basically, PHP is telling you "Hey, you can't use this function to write to a file that lives on the internet. How do you expect me to write a file # http: //miapp .com/api/zonas/8? Not gonna happen".
I assume what you're trying to do is to send a PUT request # that location to update a zonas resource with ID 8.
Solution
Consider using a proper HTTP client that can send actual HTTP request methods and conform to the HTTP spec.
My personal favourite inside PHP is Guzzle -
http://docs.guzzlephp.org/en/stable/. Guzzle is a standalone package and can be downloaded from their site. You can use it in any PHP project - without or without a framework.
With Guzzle, you'd do something like the following:
$client = new GuzzleHttp\Client();
$json = json_encode($ConstructorJson);
$headers = [
"Accept" => "application/xml\r\n"
]
$request = new Request('PUT', $url, ['body' => $json, 'headers' => $headers]);
$client->send($request);
I finally solved the problem (thank you Kyle O'Brien)
Code
<?php
// web service url + tabla + id
$url = "mywebservice.com/zonas/8";
$Datos = $_POST;
//create a array with dates
$ConstructorJson = array(
'Nombre' => $Datos['txt_Nombre'],
'CreadoPor' => $Datos['txt_CreadoPor'],
'CreadoFecha' => $Datos['txt_CreadoFecha'],
'ModificadoPor' => $Datos['txt_ModificadoPor'],
'ModificadoFecha' => $Datos['txt_ModificadoFecha'],
'Estado' => $Datos['cbo_Estado'],
'Nota' => $Datos['txt_Notas']
);
//convert array to json
$json = json_encode($ConstructorJson);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => $json,
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>