0

I am using cURL for an API call, below is my code:

$data = array(
            'r'                          =>  'create',
            '_object'                    =>  'Question',
            '_api_key'                   =>  '........',
            '_user_id'                   =>  $creator_id,
            '_subtype_id'                =>  $type_id,
            '_subtopic_id'               =>  $subtopic_id,
            '_title'                     =>  $title,
            '_description'               =>  $description,             
            '_encoded_xml'               =>  $main_xml
        );
     
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,"http://urlhere/v1/resources/objects");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
        $server_output = curl_exec($ch);    
        curl_close ($ch);
        print_r($server_output);

I want these parameters to be sent as GET request instead of POST, how can I do that pls advise

2

1 Answer 1

2

CURLOPT_POSTFIELDS is for the body (payload) of a POST request. For GET requests, the payload is part of the URL.

You just need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.


$data = array(
            'r'             =>  'create',
            '_object'       =>  'Question',
            '_api_key'      =>  '........',
            '_user_id'      =>  $creator_id,
            '_subtype_id'   =>  $type_id,
            '_subtopic_id'  =>  $subtopic_id,
            '_title'        =>  $title,
            '_description'  =>  $description,             
            '_encoded_xml'  =>  $main_xml
        );


        $send_data = http_build_query($data);
     
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,"http://urlhere/v1/resources/objects?" . $send_data);
        // curl_setopt($ch, CURLOPT_POST, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
        
        $server_output = curl_exec($ch);    
        curl_close ($ch);
        print_r($server_output);

Sign up to request clarification or add additional context in comments.

2 Comments

i am sending $data array to the server as get request so should i add ?iitem= itemval , like this in url ?
Ah yes... add something like this... $send_data = http_build_query($data); adding it to your URL, I've updated the code in the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.