PHP REST API Integration with Guzzle and Twig
This comprehensive tutorial will show you how to use PHP with Guzzle to make GET, POST, PUT, DELETE, and PATCH requests to an API and render the results using the Twig templating engine. You’ll also learn how to test your scripts properly, making this guide perfect for beginners who want to master RESTful API integration in PHP using modern tools.
Setting Up Your Project
To get started, you’ll need Composer installed. Then run the following commands in your terminal to install Guzzle and Twig:
composer require guzzlehttp/guzzle twig/twig
Create a directory structure like this:
/project-root
├── vendor/
├── views/
│ └── output.twig
├── index.php
└── composer.json
Initializing Twig and Guzzle
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use Twig\Loader\FilesystemLoader;
use Twig\Environment;
$loader = new FilesystemLoader('views');
$twig = new Environment($loader);
$client = new Client(['base_uri' => 'https://jsonplaceholder.typicode.com']);
GET Request Example
Let’s fetch posts from the API and pass them to Twig for rendering:
$response = $client->request('GET', '/posts');
$data = json_decode($response->getBody(), true);
echo $twig->render('output.twig', ['title' => 'GET Request', 'data' => $data]);
POST Request Example
Sending new data using a POST request:
$response = $client->request('POST', '/posts', [
'json' => [
'title' => 'New Title',
'body' => 'New body content.',
'userId' => 1
]
]);
$result = json_decode($response->getBody(), true);
echo $twig->render('output.twig', ['title' => 'POST Request', 'data' => $result]);
PUT Request Example
Use PUT to replace an existing record:
$response = $client->request('PUT', '/posts/1', [
'json' => [
'id' => 1,
'title' => 'Updated Title',
'body' => 'Updated content.',
'userId' => 1
]
]);
$updated = json_decode($response->getBody(), true);
echo $twig->render('output.twig', ['title' => 'PUT Request', 'data' => $updated]);
PATCH Request Example
Use PATCH to partially update a record:
$response = $client->request('PATCH', '/posts/1', [
'json' => ['title' => 'Partially Updated Title']
]);
$patched = json_decode($response->getBody(), true);
echo $twig->render('output.twig', ['title' => 'PATCH Request', 'data' => $patched]);
DELETE Request Example
Use DELETE to remove a record:
$response = $client->request('DELETE', '/posts/1');
echo $twig->render('output.twig', ['title' => 'DELETE Request', 'data' => ['status' => $response->getStatusCode()]]);
Sample Twig Template
Save this as views/output.twig
:
<h2 class="text-xl font-semibold mb-4">{{ title }}</h2>
<pre class="bg-gray-100 p-4 rounded overflow-x-auto">{{ data|json_encode(constant('JSON_PRETTY_PRINT')) }}</pre>
Testing Your Script
You can test each method by modifying your index.php
to switch between methods based on a query string or form input. Alternatively, use tools like:
- Postman: Send HTTP requests and see the output live.
- Browser: Test GET endpoints directly via browser URL.
- Command Line: Use
php index.php
and echo different responses for different actions.
Conclusion
You now know how to perform all major HTTP requests using PHP and Guzzle and display the responses using Twig. This combination is great for building frontend-friendly APIs and server-rendered content. Whether you're developing admin panels, dashboards, or connecting to external APIs, this setup gives you power and flexibility in PHP development.