Browsed by
Day: March 7, 2017

Use Swagger to generate a full functional Magento API Client

Use Swagger to generate a full functional Magento API Client

Magento 2 comes with a nice swagger schema which describes the Webapi. The Magento guys were very clever to choose swagger. It not only comes with a schema, but moreover it is a complete interactive API client as well.

A swagger schema is a JSON document to formalize the REST API. Formalized documents have the big advantage that you can process the data with a machine. One idea I had was to create a PHP API for the Magento 2 API. Fortunately the swagger guys created a code generator tool. I really like the idea to generate code out of the schema. The swagger code-gen tool comes with support for multiple languages. PHP is one of the standard languages.

The code generator tool can be found here: http://swagger.io/swagger-codegen/

If you are on a mac it’s possible to install the code generator with homebrew.

After the installation you can test the tool with the help command.

On my machine i can see this help output. Works!

Run the generator

Now we are able to run the code generator. I used the schema from public developer documentation. You can also use your own schema from an existing installation.

You should see a long list of generated classes like this:

Run test unit tests

After the code generation is done, we should run the generated unit tests. You can run the tests by typing vendor/bin/phpunit in the project folder.

Test the new generated client

After that we can try our freshly generated API client library.

As an example we will fetch all the installed Magento modules of our shop instance.

Save the script as installed_modules.php and replace {{YOUR_SHOP_URL}}  with a local or remote shop url and {{YOUR_API_TOKEN}} with a API bearer token of your user. A brief description about the generation of API-Tokens can be found in the developer documentation topic “Token-based authentication“.

Now run the script with php installed_modules.php.

On my local machine I am getting this output:

Conclusion

That’s it. We have a full functional REST API client in PHP to call Magento 2 instances. The generated code is not perfect but very usable.

You can try it by yourself. For all lazy developers we pushed the code in a public github repository.

https://github.com/netz98/magento2-swagger-api-client-demo

Have fun!

– Creator of n98-magerun
– Fan of football club @wormatia
– Magento user since version 0.8 beta
– 3x certified Magento developer
– PHP Top 1.000 developer (yes, I’m PHP4 certified and sooooo old)
– Chief development officer at netz98