0

I am trying to call an external API with a POST method which is working fine on Postman, but when trying to implement it in a custom module using drupal_http_request() I am getting a strange error.

The requested resource does not support http method 'GET'.

This is the extracted cURL command from Postman: curl --location --max-time 2000 --request POST 'https://example.com/api' --header 'Authorization: [token]' --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'subject=Lead XXX' --data-urlencode 'firstName=XXX' --data-urlencode 'lastName=XXX' --data-urlencode 'Email=test@test.test' --data-urlencode 'Mobile=XXX' --data-urlencode 'Interest=XXX ' --data-urlencode 'meetingdate=2020-04-20T13:00:00.000'.

This is the code I am using.

$url = 'https://example.com/api';
$data = [
    'subject' => 'XXX',
    'firstName' => 'XXX',
    'lastName' => 'XXX',
    'Email' => 'test@test.test',
    'Mobile' => 'XXXX',
    'Interest' => 'Testing',
    'meetingdate' => '2020-04-20T13:00:00.000',
];
$options = [
    'method' => 'POST',
    'headers' => array(
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Authorization' => [token],
    ),
    'data' => json_encode($data),
];
$request = drupal_http_request($url, $data);

I have the feeling this must be easy, but I couldn't figure out what I'm doing wrong. I search the documentation, searched here with no luck.

Any hit will be appreciated.

  • For a start it doesn't look like you're doing anything with your $options variable. Shouldn't you be passing $options in your call drupal_http_request($url, $options); – Leigh May 12 at 11:50
  • 1
    Thanks for pointing this out... I was passing the $data instead of $options. Can't believe I stuck with this for hours. This is what happens when someone didn't get a good sleep. – Hodba Khalaf May 12 at 13:46
  • No problem! Glad you got it sorted – Leigh May 12 at 13:59
1

In your post request you have specified

'Content-Type' => 'application/x-www-form-urlencoded'

but your post data is in JSON format.

Perhaps you need

'Content-Type' => 'application/json'

alternatively, pass the raw $data array as the post data for key=value&key1=value2 form encoding.

You also need to pass the function parameter $options instead of $data

$request = drupal_http_request($url, $options);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.