Fetch data through API in Drupal 8

To fetch data through API, you need to send a request, and then handle the response of the API according to the data comes in API response.

You also need to handle the exception in API request, because sometimes when server does not respond the correctly then an error occurred in your site.

So you can handle these exceptions to use try and catch method.

$client = \Drupal::httpClient();

$url = 'http://www.webcaravan.in/api';

$method = 'POST';

$parameters = [ 'foo' => 'test', 'bar' => 12345];

try {

$response = $client->request($method, $url, $parameters);

$code = $response->getStatusCode();

if ($code == 200) {

$body = $response->getBody()->getContents(); return $body;


} catch (RequestException $e) { watchdog_exception('api_request_exception', $e);