Skip to content
This repository was archived by the owner on Nov 19, 2024. It is now read-only.

Commit 9edc184

Browse files
authored
Merge pull request #6859 from eduard13/guzzle-http-page
Adding a new topic related to GuzzleHttp library
2 parents 77955af + 99a0f24 commit 9edc184

File tree

2 files changed

+173
-0
lines changed

2 files changed

+173
-0
lines changed

src/_data/toc/extension-best-practices.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,7 @@ pages:
6767

6868
- label: Creating an Access Control List (ACL) rule
6969
url: /ext-best-practices/tutorials/create-access-control-list-rule.html
70+
71+
- label: Creating an integration with an external API
72+
url: /ext-best-practices/tutorials/create-integration-with-api.html
73+
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
---
2+
group: extension-best-practices
3+
title: Creating an integration with an external API
4+
contributor_name: Atwix
5+
contributor_link: https://www.atwix.com/
6+
---
7+
8+
This tutorial shows you how to create an integration with an external API using [GuzzleHttp](http://docs.guzzlephp.org/en/stable/quickstart.html){:target="_blank"} library, that is included into Magento package.
9+
10+
Guzzle is a PHP HTTP client that makes it easy to create some integrations with some web services.
11+
Its implementation code is more simpler, cleaner and readable, in comparision with cURL.
12+
13+
GuzzleHttp uses cURL by default, but it can use any HTTP client that you want other than cURL like PHP's stream wrapper or sockets, in case `curl` isn't installed on your Web Server.
14+
15+
{:.bs-callout-info}
16+
It's much easier to cover a GuzzleHttp implementation by [Unit Tests]({{ page.baseurl }}/test/unit/writing_testable_code.html), as you're able to mock the HTTP requests.
17+
18+
## Request options
19+
20+
| Option | Description | Type |
21+
| --- | --- | --- |
22+
| `method` | HTTP method, any of `GET`, `POST`, `PUT`, `DELETE` | String |
23+
| `uri` | The API endpoint that needs to be called | String |
24+
| `params` | A list of parameters that needs to be passed to the API | Array |
25+
26+
## Create a Github API integration
27+
28+
In the following example, we're using the [Github API](https://api.github.com/) as web service, and will fetch some data regarding the Magento 2 Git repository.
29+
30+
```php
31+
<?php
32+
33+
declare(strict_types=1);
34+
35+
namespace Vendor\Module\Service;
36+
37+
use GuzzleHttp\Client;
38+
use GuzzleHttp\ClientFactory;
39+
use GuzzleHttp\Exception\GuzzleException;
40+
use GuzzleHttp\Psr7\Response;
41+
use GuzzleHttp\Psr7\ResponseFactory;
42+
use Magento\Framework\Webapi\Rest\Request;
43+
44+
/**
45+
* Class GitApiService
46+
*/
47+
class GitApiService
48+
{
49+
/**
50+
* API request URL
51+
*/
52+
const API_REQUEST_URI = 'https://api.github.com/';
53+
54+
/**
55+
* API request endpoint
56+
*/
57+
const API_REQUEST_ENDPOINT = 'repos/';
58+
59+
/**
60+
* @var ResponseFactory
61+
*/
62+
private $responseFactory;
63+
64+
/**
65+
* @var ClientFactory
66+
*/
67+
private $clientFactory;
68+
69+
/**
70+
* GitApiService constructor
71+
*
72+
* @param ClientFactory $clientFactory
73+
* @param ResponseFactory $responseFactory
74+
*/
75+
public function __construct(
76+
ClientFactory $clientFactory,
77+
ResponseFactory $responseFactory
78+
) {
79+
$this->clientFactory = $clientFactory;
80+
$this->responseFactory = $responseFactory;
81+
}
82+
83+
/**
84+
* Fetch some data from API
85+
*/
86+
public function execute(): void
87+
{
88+
$repositoryName = 'magento/magento2';
89+
$response = $this->doRequest(static::API_REQUEST_ENDPOINT . $repositoryName);
90+
$status = $response->getStatusCode(); // 200 status code
91+
$responseBody = $response->getBody();
92+
$responseContent = $responseBody->getContents(); // here you will have the API response in JSON format
93+
// Add your logic using $responseContent
94+
}
95+
96+
/**
97+
* Do API request with provided params
98+
*
99+
* @param string $uriEndpoint
100+
* @param array $params
101+
* @param string $requestMethod
102+
*
103+
* @return Response
104+
*/
105+
private function doRequest(
106+
string $uriEndpoint,
107+
array $params = [],
108+
string $requestMethod = Request::HTTP_METHOD_GET
109+
): Response {
110+
/** @var Client $client */
111+
$client = $this->clientFactory->create(['config' => [
112+
'base_uri' => self::API_REQUEST_URI
113+
]]);
114+
115+
try {
116+
$response = $client->request(
117+
$requestMethod,
118+
$uriEndpoint,
119+
$params
120+
);
121+
} catch (GuzzleException $exception) {
122+
/** @var Response $response */
123+
$response = $this->responseFactory->create([
124+
'status' => $exception->getCode(),
125+
'reason' => $exception->getMessage()
126+
]);
127+
}
128+
129+
return $response;
130+
}
131+
}
132+
```
133+
134+
## Result
135+
136+
As result, you get all the available information regarding the Magento repository.
137+
138+
```json
139+
{
140+
...
141+
"name": "magento2",
142+
"full_name": "magento/magento2",
143+
"private": false,
144+
"html_url": "https://github.com/magento/magento2",
145+
"description": "All Submissions you make to Magento Inc. (\"Magento\") through GitHub are subject to the following terms and conditions: (1) You grant Magento a perpetual, worldwide, non-exclusive, no charge, royalty free, irrevocable license under your applicable copyrights and patents to reproduce, prepare derivative works of, display, publically perform, sublicense and distribute any feedback, ideas, code, or other information (“Submission\") you submit through GitHub. (2) Your Submission is an original work of authorship and you are the owner or are legally entitled to grant the license stated above. (3) You agree to the Contributor License Agreement found here: https://github.com/magento/magento2/blob/master/CONTRIBUTOR_LICENSE_AGREEMENT.html",
146+
"fork": false,
147+
"url": "https://api.github.com/repos/magento/magento2",
148+
"homepage": "http://www.magento.com",
149+
"size": 559209,
150+
"stargazers_count": 8379,
151+
"watchers_count": 8379,
152+
"language": "PHP",
153+
"has_issues": true,
154+
"has_projects": false,
155+
"has_downloads": true,
156+
"has_wiki": true,
157+
"has_pages": false,
158+
"forks_count": 7405,
159+
"archived": false,
160+
"disabled": false,
161+
"open_issues_count": 1535,
162+
"forks": 7405,
163+
"open_issues": 1535,
164+
"watchers": 8379,
165+
"default_branch": "2.4-develop",
166+
"subscribers_count": 1421,
167+
...
168+
}
169+
```

0 commit comments

Comments
 (0)