im working with an API for a company and completed initial task, the last task is to submit my work using their API. It's like onboarding challenge. One of the parameters value needs to be an object as said in documentation.
<?php
$myWORK = array (
'Email' => 'MY_EMAIL',
'URL' => 'REPOSITORY_URL',
);
$url = 'https://api.xxxxxxx.com/';
$data = array(
'key' => 'MY_API_KEY',
'base' => 'MY_TOKEN',
'data' => json_decode(json_encode($myWORK), FALSE)
);
$options = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header' => "Content-type: application/x-www-form-urlencoded\r\n"
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$output = json_decode($result,true);
print_r($ouput);
?>
I need to pass that $myWork
as value in the data
parameter. It needs to be an object, does my object code correct? I get no error response from the API but the data
is empty. Please give your thoughts.. a little help.
My Answer:
Your code looks mostly correct, but there is a small mistake in the way you are encoding the $myWork array as an object. Instead of using json_decode and json_encode, you can directly create an object using stdClass. Here's how you can modify your code:
php
$myWORK = new stdClass();
$myWORK->Email = 'MY_EMAIL';
$myWORK->URL = 'REPOSITORY_URL';
$url = 'https://api.xxxxxxx.com/';
$data = array(
'key' => 'MY_API_KEY',
'base' => 'MY_TOKEN',
'data' => $myWORK
);
$options = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header' => "Content-type: application/x-www-form-urlencoded\r\n"
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$output = json_decode($result, true);
print_r($output);
By creating $myWORK as an object of stdClass, you can directly pass it as a value in the 'data' parameter without the need for additional encoding and decoding. This should resolve the issue of the data being empty in the API response.
Rate this post
3 of 5 based on 8172 votesComments