Member-only story

Using ReactPHP to consume data from an HTTP API

Matt Glaman
10 min readSep 12, 2020

This is the first of two blogs detailing how to build a middleware leveraging ReactPHP to consume data from an API, normalize it, and then push that data into Drupal through JSON:API. In this example will be grabbing data from the PokéAPI. In the second blog post, we will take the data and create Pokémon nodes on a Drupal site.

The purpose of the middleware is to avoid putting this logic into the Drupal codebase. Drupal has an amazingly robust Migration API for consuming data and processing data to create content. Every Drupal site I have ever worked on — since Drupal 8’s beta days — has used the migration system to import content through CSVs or JSON from remote APIs. However. That means you have to be a Drupal developer to understand it, or go through the learning curve if you are not. A generic middleware means that any team can control and maintain the code. All you need to know is some PHP.

Why ReactPHP and not XYZ?

But, why ReactPHP? ReactPHP provides a low-level library for event-driven applications based around its event-loop library. If you're familiar with Rust, it is like the Tokio runtime. Node.js has an event loop runtime built-in.

Consuming data from a remote API is time-consuming. Especially if the process is synchronous:

  • Make a request to the API
  • Wait for the request to finish
  • Parse the response
  • Handle the response data

--

--

Matt Glaman
Matt Glaman

Written by Matt Glaman

PHP software engineer, open source contributor, and speaker

No responses yet