Home > front end >  POST parameter with value as an object in HTTP method
POST parameter with value as an object in HTTP method

Time:06-25

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.

CodePudding user response:

I suspect the API wants JSON, not url-encoded data.

$myWORK = array (
'Email' => 'MY_EMAIL',
'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' => json_encode($data),
        'header'  => "Content-type: application/json\r\n"
    )
);

There's no need to call json_decode(json_encode($myWORK)), you can just nest the array directly into $data.

  • Related