Generating PHP library code from OpenAPI

I'm working with a bunch of OpenAPI specs now I am working for Nexmo and so far I'm loving working with API descriptions. OpenAPI is the next iteration of what used to be called "Swagger", a machine-readable way to describe your API and from that description create docs, code libraries, tests, and all sorts. Today's post is a quick writeup of how I generated some PHP code so that I can refer back to this next time I want to do it!

Nexmo currently has a bunch of hand-built libraries but I wondered if we could generate some of the backend legwork bits - this would also allow us to regenerate them when things change (useful for the APIs that are still under development). To this end, I used and it was an easy experience.
Good: they supply the whole thing in a docker image so installation is simple!

Better: there are great docs on what I need to to do run the code. I was looking at the Secret Management API for Nexmo (so you can rotate your secrets programmatically and in a sane way), the definition is on GitHub so my command was like this:

docker run --rm -v ${PWD}:/local openapitools/openapi-generator-cli generate \
  -i \
  -g php -o /local/out/php

Best: Along with my generated code (in out/php/ relative to where I ran this command from), this project generates a file. A readme, people! It even has accurate instructions of how to use the code that was generated!

Here's the PHP example for posterity: calling the endpoint that receives all current secrets (actually just the ID and timestamp, not the actual secrets because that would be quite the opposite of secure)

require "out/php/vendor/autoload.php";

$config = OpenAPI\Client\Configuration::getDefaultConfiguration()

$client = new OpenAPI\Client\Api\DefaultApi(new GuzzleHttp\Client(), $config);
$inline_object = new \OpenAPI\Client\Model\InlineObject();

try {
    $result = $client->retrieveSecrets(NEXMO_API_KEY, $inline_object);
} catch (Exception $e) {
    echo 'Exception when calling DefaultApi->retrieveSecrets: ', $e->getMessage(), PHP_EOL;

Looks pretty good to me, it knows how to handle the Basic Auth that this API uses, and methods have been created for each of the endpoints in my API Specification (there is also documentation! Wow!). Are you generating code from the v3 OpenAPI specs? I'd love to hear your tips, tricks and stories from the front - leave me a comment.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.