Search code examples
phpapify

Sending HTTP Post Request to site with array in Body


I'm trying to make a POST request and send some values in the body of an API call. In the documentation of the API it says I need to make a POST request, using startUrls as an array with key and value.

<?php
$url = 'https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID';

$postData = array(
'startUrls' => array(array('key'=>'START', 'value'=>'https://instagram.com/instagram'))
);
$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-type: application/json',
        'body' => json_encode($postData)
        )
));
$resp = file_get_contents($url, FALSE, $context);
print_r($resp); 
?>

The JSON seems to be how it should, but the script is not sending the body properly to the website.


Solution

  • According to the documentation, there is no body option for the HTTP context. Try content instead:

    <?php
    $url = "https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID";
    
    $postData = [
        "startUrls" => [
            ["key"=>"START", "value" => "https://instagram.com/instagram"]
        ]
    ];
    
    $context = stream_context_create([
        "http" => [
            "method"  => "POST",
            "header"  => "Content-type: application/json",
            "content" => json_encode($postData)
        ]
    ]);
    $resp = file_get_contents($url, FALSE, $context);
    print_r($resp);