How can I display the values returned from an external API under a form? I have created a custom module that pulls in data from an external API. Users select a few values on a form; submitting the form makes a call to the external API. The module then displays the data, which has been filtered by the values entered from users.
I have been able to show the returned data with \Drupal::messenger()-&gt;addMessage(), but this doesn't seem the right method. I've found a few other suggestions, but I can't get any of them to work. They are for older Drupal versions.
I'd like to be able to display the formatted results under the form, on the same page.
How can I achieve this in Drupal 9?
It's not much different from what done with Drupal 7; the difference is the involved classes (which weren't implemented in Drupal 7) and the used methods.

The submission handler stores the values obtained from the external API and sets the form to be rebuilt
The form builder verifies the values set by the submission handler are set and shows them

In the case of a class extending the FormBase class this means:

submitForm() calls $form_state-&gt;setValue() to set the value obtained from the external API
submitForm() calls $form_state-&gt;setRebuild() to tell Drupal the form needs to be rebuilt
buildForm() uses $form_state-&gt;hasValue() to check the value has been set and $form_state-&gt;getValue() to get that value

As for showing the returned value, it's sufficient to use a form element similar to the following one.
$form['api_value'] = [
  '#type' =&gt; 'markup',
  '#markup' =&gt; $api_result,
];

As side note, the $key value passed to $form_state-&gt;setValue() should not be a value already used for a form element. Differently, $form_state-&gt;setValue() would set the value submitted for that form element.