I am trying to consume an API, and anytime I send the data to the API, I get a "No data sent" response from the API. below is my code.
<?php
$url = 'endpoint';
$curl = curl_init();
$valu = array(
'username' => 'used',
'firstname' => 'user',
'email' => 'user@email.com',
'bio' => 'A very good personality',
'lastname' => 'demo',
'password' => 'date'
);
$json_string = json_encode(array( "data" => $valu));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );
$data = curl_exec($curl);
if($data){
echo $data;
}
curl_close($curl);
?>
below is data the API requires from the client
{
"username":"username",
"firstname":"firstname",
"email":"email",
"bio":"A very good personality",
"lastname":"lastname",
"password":"data"
}
inside a node called 'data'
Please, help
I am providing with example, it worked for me!
<?php
$url = 'https://reqres.in/api/users';
$curl = curl_init($url);-> this line is incorrect
$valu = array(
'name' => 'used',
'job' => 'user'
);
$json_string = json_encode(array( "data" => $valu));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );
$data = curl_exec($curl);
if($data){
echo $data;
}
curl_close($curl);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.