Guzzle responses from POST on REST API are mixed

I develop a custom module to store and retrieve users data from an API. I used the user entity hooks to call the API on registration, edition and consultation of the Drupal users.
It works well, and we use it on several website all using the same partner API.

To update or save the data, we use a POST method with the fields in the body and without URL parameters.

In some cases, when 2 users are registering or saving their account at the same time (max 3 seconds delay), then the information return in the POST response of the second call is the same as the first one.

Here is the method I’m using to call the API:

/**
 * Make the Calls to the API.
 *
 * @param string $function
 *   The API endpoint to call.
 * @param string $method
 *   The method (GET / POST / ...).
 * @param array $data
 *   The data to POST to the API.
 *
 * @return array
 *   Array of data from the API, can be empty if error or no results.
 */
public static function callApi($function, $method = 'GET', array $data = []) {
  $srv_url = 'https://someapi.com/';

  if ($srv_url === '/') {
    return FALSE;
  }

  $headers = [
    'Content-Type' => 'application/json;charset=UTF-8',
  ];

  $token = self::getToken($srv_url);
  if ($token === FALSE) {
    return FALSE;
  }
  elseif ($token !== TRUE) {
    $headers['Authorization'] = 'Bearer ' . $token;
  }

  $options = [
    'headers' => $headers,
  ];
  $full_url = $srv_url . $function;

  if ($method === 'POST') {
    $options['body'] = Json::encode($data);
  }
  else {
    $full_url .= '?' . UrlHelper::buildQuery($data);
  }

  try {
    $client = Drupal::httpClient();
    $mthd = strtolower($method);
    $response = $client->$mthd($full_url, $options);

    $statusCode = $response->getStatusCode();
    // Expected result.
    $jresp = Json::decode($response->getBody());

    // No result (GET).
    if ($statusCode == 204) {
      return [];
    }

    if (isset($jresp['code']) || !in_array($statusCode, [200, 201])) {
      // Something went wrong.
      $code = isset($jresp['code']) ? $jresp['code'] : $statusCode;
      if (isset($jresp['error'])) {
        $msg = $jresp['error'];
      }
      elseif (isset($jresp['message'])) {
        $msg = $jresp['message'];
      }
      else {
        $code = $statusCode;
        $msg = $response->getReasonPhrase() . '<br>' . $response->getBody()->getContents();
      }
      $message = "Response API {$method} - {$function} : {$code}<br>{$msg}<pre>" . print_r($response, TRUE) . '</pre>';
      Drupal::logger('mymodule')->error($message);
      return [];
    }

    // Log posted result.
    if ($method === 'POST' && $function === 'contact') {
      AtixTools::debug('atix_crm_cible', ["Result API {$method} - {$function}" => ['options' => $options, 'resp' => $jresp]]);
    }
    if (isset($jresp['body'])) {
      return $jresp['body'];
    }
    return $jresp;
  }
  catch (RequestException $e) {
    watchdog_exception('mymodule', $e);
  }

  return [];
}

Here are an example of two calls where the data have been mixed. In the arrays are the options used for the POST request and the Body answered by the API.

Array
(
    [options] => Array
        (
            [headers] => Array
                (
                    [Content-Type] => application/json;charset=UTF-8
                    [Cache-Control] => no-cache
                    [Authorization] => Bearer XXXXXXX
                )

            [body] => @"email":ttf-test54@yopmail.com,"sms":"","nom":"ttf-test54","prenom":"ttf-test54","date_de_naissance":"","code_postal":"","ville":"","langue":"fr","id_filiale":9
        )

    [resp] => Array
        (
            [0] => Array
                (
                    [langue] => fr
                    [nom] => ttf-test54
                    [upd_date] => 2021-08-26 14:18:22
                    [id_contact] => 53550
                    [prenom] => ttf-test54
                    [email] => ttf-test54@yopmail.com
                )
        )
)

The second one has the same answer

Array
(
    [options] => Array
        (
            [headers] => Array
                (
                    [Content-Type] => application/json;charset=UTF-8
                    [Cache-Control] => no-cache
                    [Authorization] => Bearer XXXXXXX
                )

            [body] => @"email":ttf-test55@yopmail.com,"sms":"","nom":"ttf-test55","prenom":"ttf-test55","date_de_naissance":"","code_postal":"","ville":"","langue":"fr","id_filiale":9
        )

    [resp] => Array
        (
            [0] => Array
                (
                    [langue] => fr
                    [nom] => ttf-test54
                    [upd_date] => 2021-08-26 14:18:22
                    [id_contact] => 53550
                    [prenom] => ttf-test54
                    [email] => ttf-test54@yopmail.com
                )
        )
)

The people from the API assure me their is no cache on the server side, specially for a POST. The API is developed just for this purpose and is hosted on AWS (Amazon).

How is it possible that 2 calls to the API using Guzzle from two web pages are giving back the same set of data ?
Is their a way Drupal or Guzzle are caching the response from the server ?

I looked a lot to find a solution to resolve this trouble, try using no cache header (like in this example), try reproducing it with Postman or a scenario in integromat without any success.

Thanks for some help.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Guzzle responses from POST on REST API are mixed

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.