Score:1

How to export data using POST?

kz flag

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.

Score:1
de flag

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.

id flag
The question, which is two questions, also asks how to extract node fields.
Jaypan avatar
de flag
I don't think it did ask how to extract post data, but I've updated my post to show how.
Jaypan avatar
de flag
...err node data I mean.
Free Radical avatar
kz flag
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.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.