Laravel OpenAPI CLI: Generate Artisan Commands from Your API Spec
Laravel

Laravel OpenAPI CLI: Generate Artisan Commands from Your API Spec

Laravel OpenAPI CLI: Generate Artisan Commands from Your API Spec

In the ever-evolving landscape of web development, Laravel continues to stand out as a powerful PHP framework. With the introduction of the Laravel OpenAPI CLI by Spatie, developers can now seamlessly generate Artisan commands from their API specifications. This innovative package simplifies the process of interacting with APIs, allowing for a more efficient workflow.

Understanding Laravel OpenAPI CLI

The Laravel OpenAPI CLI package is designed to convert OpenAPI specifications into dedicated Laravel Artisan commands. Each API endpoint defined in your OpenAPI spec is translated into a corresponding Artisan command, complete with typed options for path and query parameters, as well as request bodies.

How It Works

To begin using the Laravel OpenAPI CLI, you first need to install the package via Composer. The installation command is as follows:

composer require spatie/laravel-openapi-cli

Once installed, you will need to register your OpenAPI specification URL using the OpenApiCli facade, typically within your AppServiceProvider. Here’s a basic example:


namespace AppProviders;

use IlluminateSupportServiceProvider;
use SpatieOpenApiCliFacadesOpenApiCli;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        OpenApiCli::register('https://api.acme.com/openapi.yaml', 'acme')
            ->baseUrl('https://api.acme.com')
            ->bearer(env('ACME_API_TOKEN'));
    }
}

Generating Artisan Commands

After registering your OpenAPI spec, the package will generate Artisan commands for each endpoint. For example, if your spec defines the following endpoints:

  • GET /orders
  • POST /orders
  • DELETE /orders/{order_id}

The generated Artisan commands will be:

  • acme:get-orders
  • acme:post-orders
  • acme:delete-orders
  • acme:list

The acme:list command displays all available endpoints along with their descriptions. The naming convention for commands follows the pattern {prefix}:{http-method}-{path}, where the prefix is the name given during registration, and the path is converted to kebab-case with path parameters stripped out. For example, the endpoint GET /orders/{order_id}/items becomes acme:get-orders-items.

Running Commands

To execute any generated command, simply call it directly from the terminal. For example:

php artisan acme:get-orders --limit=10

By default, responses are rendered as human-readable tables. If you prefer YAML output, you can add the --yaml flag:

php artisan acme:get-orders --limit=10 --yaml

Handling Path and Query Parameters

Path parameters are required options, while query parameters are optional. Both types of parameters are converted to kebab-case. For instance:

  • Path parameter: php artisan acme:get-orders-items --order-id=42
  • Multiple path parameters: php artisan acme:delete-customers-orders --customer-id=1 --order-id=7
  • Query parameters: php artisan acme:get-orders --status=pending --limit=10

Additionally, bracket notation in query strings is flattened to kebab-case, meaning that filter[status] becomes --filter-status.

Sending Data

For endpoints that accept a request body, you can send fields individually using the --field option:

php artisan acme:post-orders --field customer_id=1 --field status="pending"

By default, fields are sent as JSON unless specified otherwise in the OpenAPI spec. If you need to send raw JSON, you can use the --input option:

php artisan acme:post-orders --input '{"customer_id":1,"shipping":{"address":"123 Main St","city":"New York"}}'

Note that the --field and --input options cannot be combined. For file uploads, prefix the field value with @:

php artisan acme:post-orders-attachments --order-id=67 --field file=@/path/to/invoice.pdf

This will send the request as multipart/form-data when any field contains a file.

Configuration Options

The registration API supports several configuration options through a fluent interface. Here’s an example:


OpenApiCli::register('https://api.acme.com/openapi.yaml', 'acme')
    ->baseUrl('https://api.acme.com')
    ->bearer(env('ACME_API_TOKEN'))
    ->banner('Acme Orders API v2')
    ->cache(ttl: 600)
    ->followRedirects()
    ->yamlOutput()
    ->showHtmlBody()
    ->useOperationIds()
    ->onError(function (Response $response, Command $command) {
        return match ($response->status()) {
            429 => $command->warn('Rate limited...'),
            default => false,
        };
    });

Some notable options include:

  • cache(ttl: 600) — Caches responses for the specified number of seconds.
  • followRedirects() — Automatically follows HTTP redirects.
  • useOperationIds() — Names commands using the operation IDs from your spec rather than the HTTP method and path.
  • onError() — Accepts a callback for handling specific HTTP error status codes.

Conclusion

The Laravel OpenAPI CLI package by Spatie is a game-changer for developers working with APIs. By automating the generation of Artisan commands from OpenAPI specifications, it streamlines the process of API interaction and enhances productivity. Whether you are building a new application or maintaining an existing one, this tool can significantly improve your workflow.

Frequently Asked Questions

What is the Laravel OpenAPI CLI package?

The Laravel OpenAPI CLI package is a tool that converts OpenAPI specifications into dedicated Laravel Artisan commands, allowing developers to easily interact with API endpoints directly from the command line.

How do I install the Laravel OpenAPI CLI?

You can install the Laravel OpenAPI CLI package via Composer using the command composer require spatie/laravel-openapi-cli.

Can I customize the generated Artisan commands?

Yes, you can customize the generated Artisan commands by using various configuration options provided by the package, such as useOperationIds() and onError().

Call To Action

Explore the capabilities of the Laravel OpenAPI CLI and enhance your API development process. Start integrating this powerful tool into your Laravel projects today!

Note: The Laravel OpenAPI CLI package is a powerful addition to any Laravel developer’s toolkit, making API interactions more efficient and manageable.

Disclaimer: Tech Nxt provides news and information for general awareness purposes only. While we strive for accuracy, we do not guarantee the completeness or reliability of any content. Opinions expressed are those of the authors and not necessarily of Tech Nxt. We are not liable for any actions taken based on the information published. Content may be updated or changed without prior notice.