How to perform HTTP requests in Drupal

Let’s say you need to consume an API, and you’re using Drupal. In this case, you’ll have to perform HTTP requests to a server, and I’m about to tell you how to do it for both Drupal 7 and Drupal 8.

Drupal 7

For Drupal 7, we’ll use the drupal_http_request method to get the job done

$url = 'https://someexternal';

$data = [ 'user' => $user;
'token' => $token

$options = [
'http' => [
'method' => 'POST',
'content' => http_build_query($data)

$response = drupal_http_request($url, $options);

Drupal 8

For Drupal 8 we’ll use the The Guzzle HTTP client, that has been added to the Core.

$url = 'https://someexternal';
$method = 'POST';
$options = [
'form_params' => [
'user' => $user,
'token' => $token

$client = \Drupal::httpClient();

$response = $client->request($method, $url, $options);
$code = $response->getStatusCode();
if ($code == 200) {
$body = $response->getBody()->getContents();


And voilá! If you have questions then let me know in the comments. If you need help with Drupal then give us a call!

Do you need some help?

Let's get started. Tell us a little about yourself and your organization
and we can start a conversation about your needs and our capabilities.
Tagged: ,

Related Posts