cancel
Showing results for 
Search instead for 
Did you mean: 

Magento2 API and Swagger Codegen

Magento2 API and Swagger Codegen

Hi 

Has anyone used Swagger Codegen to generate the client code to connect to the Magento API (Magento CE 2.3).

 

I have generated the client code but can't work out how to pass the Base URL and the Access Token into the API Calls.

 

The generated code, provides examples (see below) but the URL and Authentication details are missing.

 

<?php
require_once(__DIR__ . '/vendor/autoload.php');

$apiInstance = new Swagger\Client\Api\SalesOrderRepositoryV1Api(
    // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
    // This is optional, `GuzzleHttp\Client` will be used as default.
    new GuzzleHttp\Client()
);
$body = new \Swagger\Client\Model\Body85(); // \Swagger\Client\Model\Body85 | 

try {
    $result = $apiInstance->salesOrderRepositoryV1SavePut($body);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling SalesOrderRepositoryV1Api->salesOrderRepositoryV1SavePut: ', $e->getMessage(), PHP_EOL;
}
?>

If anyone has a working example or can point me in the right direction, I would be really grateful.

 

Thanks 

Rob

1 REPLY 1

Re: Magento2 API and Swagger Codegen

SOLUTION
For anyone with a similar problem I found there was 2 issues.

 

1. I needed to create a \Swagger\Client\Configuration object and pass that into the API eg 

 

<?php
require_once(__DIR__ . '/vendor/autoload.php');
$baseUrl = 'https://<Domain>/rest';
$token = '<access token>';

$config = new \Swagger\Client\Configuration();
$config->setHost($baseUrl);
$config->setAccessToken($token);

$api_instance = new Swagger\Client\Api\SalesOrderRepositoryV1Api(new GuzzleHttp\Client(), $config, new Swagger\Client\HeaderSelector());
$id = 1; // int | The order ID.

try {
    $result = $api_instance->salesOrderRepositoryV1GetGet($id);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling SalesOrderRepositoryV1Api->salesOrderRepositoryV1GetGet: ', $e->getMessage(), PHP_EOL;
}
?>

2. The codegen process hadn't generated the code to add the 'Authentication' header into the Guzzle Request call, so for every request call I had to add the following

 

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }
//Added Code
		if ($this->config->getAccessToken()) {
			$defaultHeaders['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
		}
//End of Code
        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );     

I fixed it with a Global Search & replace in the lib/Api directory.

 

 

R