RPeraltaJr
4/4/2017 - 2:40 AM

RESTful APIs in PHP with Guzzle. 1. Download Composer globally from https://getcomposer.org/download/ 2. Terminal: 'cd' into your project d

RESTful APIs in PHP with Guzzle.

  1. Download Composer globally from https://getcomposer.org/download/
  2. Terminal: 'cd' into your project directory and download Guzzle (terminal.txt)

composer require guzzlehttp/guzzle:~6.0

<?php

require 'vendor/autoload.php';
use GuzzleHttp\Client; // use a class from this package
$client = new Client();

// jsonplaceholder.typicode.com - Fake Online REST API
// define request
$response = $client->request(
  'GET',
  'http://jsonplaceholder.typicode.com/posts/1' // url
);

$body = $response->getBody(); // all the details of this post
$string = $body->getContents();
// echo $string;

$json = json_decode($string);
$response = $client->request(
  'GET',
  'http://jsonplaceholder.typicode.com/users/' . $json->userId
);

// var_dump(json_decode($response->getBody()));
// echo $json;
echo $json->title;

?>