1

I am using Drupal as a backend to deliver data, collected using sensors, and stored in the Drupal database to a mobile app that present the data to the end user.

Drupal records the value from a temperature sensor. When some event happens that changes the temperature, the value is stored in a temperature field in a standard node. I then need to wrap the temperature and use a POST endpoint (defined by an external app) to notify the app about the temperature recorded (i.e. a push notification or export of data by means of POST).

I know how to do this with GET (which requires the app to poll the endpoint periodically to check if a new data point is available), but I need to do this by means of POST from the the Drupal back end whenever a new data point is created.

I believe I shall be able to implement hook_ENTITY_TYPE_insert()to intercept the node when it is being created to save the new data. What I am struggling with is how to use POST to push the data to the app.

0

1 Answer 1

1

Drupal core includes the Guzzle HTTP Client library under the hood. Guzzle can be used to make post requests. Whenever your event fires, you can send off a POST request as follows:

$post_data = [
  'field_1' => $node->get('field_one')->value,
  'field_2' => $node->get('field_two')->value,
];
$options['body'] = http_build_query($post_data);
// Instantiate the Guzzle HTTP client.
$client = \Drupal::httpClient();
$client->request('POST', $url, $options);

See the guzzle documentation for how to set $options for your request. Guzzle is extremely dynamic, can be used for any type of HTTP request, and allows for all sorts of options to be set. Note that depending on the endpoint, http_build_query() is not necessary (for example a JSON endpoint), and you may need to a different key than body in the options.

4
  • The question, which is two questions, also asks how to extract node fields.
    – cilefen
    Dec 25, 2022 at 17:00
  • I don't think it did ask how to extract post data, but I've updated my post to show how.
    – Jaypan
    Dec 25, 2022 at 17:31
  • ...err node data I mean.
    – Jaypan
    Dec 25, 2022 at 20:11
  • 1
    I don't think I asked about how to extract node data - just about how to export using POST. The suggestion to use built-in Guzzle looks very promising. It is past bedtime here now, but I'll check it out first thing tomorrow. Dec 25, 2022 at 21:16

Your Answer

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

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