`Usage` schema is like OpenAPI for CLIs

Brett,

Thanks for mentioning Usage in your recent Web Excursion on the blog.

I had not heard about this schema/tool. It’s rather interesting, actually. It’s like Swagger/OpenAPI standards for webAPIs, but for CLIs.

This made me think of when I was developing my own APIs for a couple of projects (in Python, as usual for me). I had been inspired by a few books[1] that I read on API design, and I really wanted to follow Swagger/OpenAPI conventions. But it was so much work to do it by hand. Then I discovered FastAPI. One of my two projects was simply an API, but the other used an API on the backend and served web pages as the user interface. FastAPI was applicable to both scenarios – but the kicker is that FastAPI generates OpenAPI reference docs for free based on automatically generated JSON Schema and Swagger UI!

I bring that up because something like Usage seems like a good start to the discussion of CLI conventions. But it may be hard to implement fully by hand. Well, FastAPI has a little sibling called Typer. Simply by using the function decorators in specification of your commands, Typer will generate the CLI --help information for free. For example, with a simple script like this:

import typer

app = typer.Typer()


@app.command()
def hello(name: str):
    print(f"Hello {name}")


@app.command()
def goodbye(name: str, formal: bool = False):
    if formal:
        print(f"Goodbye Ms. {name}. Have a good day.")
    else:
        print(f"Bye {name}!")


if __name__ == "__main__":
    app()

You get the following --help for the main function:

And even --help for the sub-commands:

I have not yet had occasion to use Typer in my own “real-world” project… But as I evolve Squarto, I may in fact test out Typer.


  1. Designing APIs with Swagger and OpenAPI, Design of Web APIs, and API Design Patterns ↩︎

1 Like

For Rubyists, I use GLI for scaffolding most of my CLIs, which does a great job of generating the help for commands and subcommands.