We just published a new package called Laravel OpenAPI CLI that turns any OpenAPI spec into dedicated Laravel artisan commands. Each endpoint gets its own command with typed options for path parameters, query parameters and request bodies.

Let me walk you through what the package can do.

Why this package exists

Many APIs publish an OpenAPI spec, but interacting with them from the command line usually means writing curl commands or building custom HTTP clients. This package reads the spec and generates artisan commands automatically, so you can start querying any API without writing boilerplate.

Combined with Laravel Zero, this is a great way to build standalone CLI tools for any API.

Registering a spec

After installing the package via Composer, you register an OpenAPI spec in a service provider:

use SpatieOpenApiCliFacadesOpenApiCli;

OpenApiCli::register('https://api.bookstore.io/openapi.yaml', 'bookstore')
    ->baseUrl('https://api.bookstore.io')
    ->bearer(env('BOOKSTORE_TOKEN'))
    ->banner('Bookstore API v2')
    ->cache(ttl: 600)
    ->followRedirects()
    ->yamlOutput()
    ->showHtmlBody()
    ->useOperationIds()
    ->onError(function (Response $response, Command $command) {
        return match ($response->status()) {
            429 => $command->warn('Rate limited. Retry after '.$response->header('Retry-After').'s.'),
            default => false,
        };
    });

That single registration gives you a full set of commands. For a spec with GET /books, POST /books, GET /books/{book_id}/reviews and DELETE /books/{book_id}, you get:

  • bookstore:get-books
  • bookstore:post-books
  • bookstore:get-books-reviews
  • bookstore:delete-books
  • bookstore:list

Using the commands

You can list all available endpoints:

php artisan bookstore:list

By default, responses are rendered as human-readable tables:

php artisan bookstore:get-books --limit=2

You can also get YAML output:

php artisan bookstore:get-books --limit=2 --yaml

Path parameters, query parameters and request body fields are all available as command options. The package reads them from the spec, so you get proper validation and help text for free.

In closing

We are already using this package internally to build another package that we will share very soon. Stay tuned!

You can find the full documentation on our documentation site and the source code on GitHub.

This is one of the many packages we have created at Spatie. If you want to support our open source work, consider picking up one of our paid products.

Read more

Categories: PHP