How to consume my webservice with PHP - php

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;
}
?>

Related

My PlayFab reset email API POST request seems not to have a payload

I am trying to submit a php response to the following PlayFab API: https://learn.microsoft.com/en-us/rest/api/playfab/admin/account-management/reset-password?view=playfab-rest
This is my first ever php script and I have been working with this for quite some time and being able to run my script without errors but it seems like I have no payload.
The echo in the code:
echo ' The resp: ' .$resp;
...response from the above echo is:
The resp: string(0) ""
Unfortunately I really do not know what is wrong and how to fix it as there is not error messages. I have tried to echo $options array to control if there is a payload but not succeeded. I realise I need help and would really appreciate that.
$url = "https://titleId.playfabapi.com/Admin/ResetPassword/json/";
$data = array('Password' => $pw1, 'Token' => $params['token']);
$options = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header' => 'X-SecretKey: xxxxxxxxxxxx\r\n',
'ignore_errors' => true
)
);
$context = stream_context_create($options);
$resp = file_get_contents($url, false, $context);
echo ' The resp: ' .$resp;
var_dump($resp);
Ok here is the solution. I was able to get this to work in Postman and when I test the code it works.
Here is the snippet that work:
echo '>>>>>>>>>> TEST <<<<<<<<<<';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://99999.playfabapi.com/Admin/ResetPassword?Password=pekapeka&Token=1B5A9C01EFD5DB69',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'X-SecretKey: xxxxxxx',
'Content-Type: application/json\\'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
print_r($response);
echo '<br>========== END ==========';

Uploading a file (server to server) with PHP using cURL

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 =)

Oauth1.0 third party api integration not working for post method

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!

How to set curl request properly in php laravel 5.5

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

Retrieve a JSON from postman on PHP

I am trying to retrieve a json from an api (and store as a variable), but I am unable to retrieve.
I am trying in all ways that postman and the web give to me.
I Am using laravel/homestead (ubuntu)
I am using laravel framework.
This way give me a HTTP Status 415 - Unsupported Media Type
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "443",
CURLOPT_URL => "https://iescities.com:443/IESCities/api/data/query/268/sql?origin=original",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "select * from wifi",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 1471daf9-329d-e9b4-b144-0383850f4769"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I also try another way but I haven't http\Client class and I haven't idea of how install and/or link it.
$client = new http\Client;
$request = new http\Client\Request;
$body = new http\Message\Body;
$body->append('select * from wifi');
$request->setRequestUrl('https://iescities.com:443/IESCities/api/data/query/268/sql');
$request->setRequestMethod('POST');
$request->setBody($body);
$request->setQuery(new http\QueryString(array(
'origin' => 'original'
)));
$request->setHeaders(array(
'postman-token' => 'e854f317-fdcc-1888-0043-758a3d5e32ba',
'cache-control' => 'no-cache'
));
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
Lot of thanks and sorry for my ignorance.
From the IESCities manual:
Query must be sent in text/plain format.
So in the line you set the headers:
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 1471daf9-329d-e9b4-b144-0383850f4769"
),
You should put another key:
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 1471daf9-329d-e9b4-b144-0383850f4769",
"Content-Type: text/plain"
),
After doing this you should be able to query the API.
Have you tried decoding the JSON?
$response = curl_exec($curl);
$responseJSON = json_decode($response, true);
print_r($responseJSON);
If you JSON looks like:
{
"name": Susy,
"age": 22
}
You can pull the age by using echo $responseJSON["age"];

Categories