Convert Figma logo to code with AI

fastapi logotyper

Typer, build great CLIs. Easy to code. Based on Python type hints.

15,343
651
15,343
181

Top Related Projects

15,652

Python composable command line interface toolkit

Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

7,943

Create *beautiful* command-line interfaces with Python

15,584

Typer, build great CLIs. Easy to code. Based on Python type hints.

37,918

A Commander for modern Go CLI interactions

Quick Overview

FastAPI and Typer are two popular Python web frameworks that simplify the process of building APIs and command-line interfaces (CLIs), respectively. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python, while Typer is a Python library for building CLI applications with as little code as possible and with great type hints.

Pros

  • High Performance: Both FastAPI and Typer are built on top of the ASGI server, which allows them to handle high-traffic and low-latency applications.
  • Simplicity and Productivity: The frameworks provide a straightforward and intuitive API, allowing developers to build complex applications with minimal boilerplate code.
  • Automatic Documentation: FastAPI and Typer automatically generate interactive API documentation, making it easier for developers and users to understand and interact with the API.
  • Type Hints: Both frameworks heavily utilize type hints, which improve code readability, maintainability, and provide better IDE support.

Cons

  • Learning Curve: While the frameworks are relatively easy to use, they may have a steeper learning curve for developers who are new to the ASGI server or type hints.
  • Dependency on Third-Party Libraries: FastAPI and Typer rely on several third-party libraries, which can increase the complexity of the project and the potential for compatibility issues.
  • Limited Community: Compared to more established web frameworks like Flask or Django, FastAPI and Typer have a smaller community, which may result in fewer resources and support available.
  • Potential Performance Overhead: The use of type hints and the ASGI server may introduce some performance overhead, which could be a concern for certain high-performance applications.

Code Examples

FastAPI

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
def create_item(item: Item):
    return item

This code creates a simple FastAPI application that accepts a POST request to the /items/ endpoint. The request body is expected to be a JSON object that conforms to the Item Pydantic model, which has name and price fields.

Typer

import typer

app = typer.Typer()

@app.command()
def greet(name: str):
    """Greet a person by name."""
    print(f"Hello, {name}!")

if __name__ == "__main__":
    app()

This code creates a simple Typer CLI application with a single command, greet, that takes a name argument and prints a greeting message.

Getting Started

To get started with FastAPI, you can install the library using pip:

pip install fastapi

Then, you can create a basic FastAPI application like the one shown in the code example above. To run the application, you can use the built-in ASGI server:

uvicorn main:app --reload

To get started with Typer, you can install the library using pip:

pip install typer

Then, you can create a Typer CLI application like the one shown in the code example above. To run the application, you can execute the Python script:

python app.py greet --name John

Both FastAPI and Typer provide extensive documentation and examples to help you get started and learn more about the frameworks.

Competitor Comparisons

15,652

Python composable command line interface toolkit

Pros of Click

  • Simplicity: Click is known for its simplicity and ease of use, making it a great choice for building command-line interfaces (CLIs) with minimal boilerplate.
  • Flexibility: Click provides a flexible and extensible framework, allowing developers to create complex CLI applications with features like subcommands, options, and arguments.
  • Cross-platform Compatibility: Click is designed to be cross-platform, ensuring that your CLI applications can run on various operating systems without issues.

Cons of Click

  • Verbosity: Compared to Typer, Click can sometimes require more boilerplate code to achieve the same functionality, which can make the codebase more verbose.
  • Learning Curve: While Click is relatively easy to use, it may have a slightly steeper learning curve compared to Typer, especially for developers new to building CLI applications.

Code Comparison

Click:

import click

@click.command()
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(name):
    """Simple program that greets NAME."""
    click.echo(f'Hello, {name}!')

if __name__ == '__main__':
    hello()

Typer:

import typer

def main(name: str):
    """Simple program that greets NAME."""
    typer.echo(f'Hello, {name}!')

if __name__ == "__main__":
    typer.run(main)

Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.

Pros of Python Fire

  • Simplicity: Python Fire provides a straightforward way to turn any Python function into a command-line interface (CLI) with minimal boilerplate code.
  • Flexibility: Python Fire can handle a wide range of input types, including positional arguments, keyword arguments, and flags.
  • Automatic Documentation: Python Fire can automatically generate documentation for your CLI, making it easier to understand and use.

Cons of Python Fire

  • Limited Functionality: Compared to FastAPI/Typer, Python Fire may lack some of the more advanced features, such as built-in support for data validation, middleware, and dependency injection.
  • Lack of Opinionated Structure: Python Fire is more of a lightweight tool, which means it doesn't provide as much structure or guidance as some other CLI frameworks.

Code Comparison

Python Fire:

import fire

def greet(name):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    fire.run(greet)

FastAPI/Typer:

import typer

app = typer.Typer()

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

if __name__ == "__main__":
    app()
75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Pros of FastAPI

  • FastAPI provides a comprehensive set of features for building robust and scalable web applications, including automatic API documentation, data validation, and asynchronous support.
  • The framework has a strong focus on performance, leveraging the power of ASGI servers like Uvicorn and Gunicorn to deliver lightning-fast responses.
  • FastAPI's intuitive and Pythonic syntax makes it easy to learn and use, especially for developers familiar with the Flask or Django frameworks.

Cons of FastAPI

  • FastAPI has a steeper learning curve compared to Typer, as it requires a deeper understanding of ASGI servers and asynchronous programming.
  • The framework's extensive feature set may be overkill for smaller projects or simple command-line tools, where Typer's simplicity and focus on CLI development may be more suitable.

Code Comparison

FastAPI:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

Typer:

import typer

app = typer.Typer()

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

Create *beautiful* command-line interfaces with Python

Pros of docopt/docopt

  • Simplicity: docopt is a lightweight and straightforward library for parsing command-line arguments, making it a good choice for simple command-line tools.
  • Flexibility: docopt allows for the creation of complex command-line interfaces with minimal code, as the library handles the parsing and validation of arguments.
  • Readability: The docopt syntax is designed to be human-readable, making it easier to maintain and update the command-line interface over time.

Cons of docopt/docopt

  • Limited Functionality: Compared to Typer, docopt has a more limited set of features and functionality, which may not be suitable for more complex command-line applications.
  • Dependency on Parsing: docopt relies heavily on the parsing of the command-line interface definition, which can be error-prone and may require more manual validation.
  • Lack of Ecosystem: Typer has a larger and more active ecosystem, with more third-party libraries and tools available, which can make it easier to integrate with other components of a project.

Code Comparison

Typer:

import typer

app = typer.Typer()

@app.command()
def greet(name: str):
    typer.echo(f"Hello, {name}!")

if __name__ == "__main__":
    app.run()

docopt:

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <name> <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py -h | --help
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.
"""
from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)
15,584

Typer, build great CLIs. Easy to code. Based on Python type hints.

Pros of Typer

  • Typer provides a more intuitive and user-friendly command-line interface (CLI) experience compared to FastAPI's built-in CLI functionality.
  • Typer's declarative syntax makes it easier to define and manage CLI commands and options.
  • Typer integrates well with other Python libraries, making it a versatile choice for building CLI applications.

Cons of Typer

  • Typer is a separate library, while FastAPI's CLI functionality is built-in, which may add an extra dependency for some projects.
  • The learning curve for Typer may be slightly steeper than using FastAPI's built-in CLI, especially for developers already familiar with FastAPI.

Code Comparison

Typer:

import typer

app = typer.Typer()

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

if __name__ == "__main__":
    app.run()

FastAPI:

from fastapi import FastAPI

app = FastAPI()

@app.get("/greet/{name}")
def greet(name: str):
    return {"message": f"Hello, {name}!"}
37,918

A Commander for modern Go CLI interactions

Pros of Cobra

  • Cobra provides a more comprehensive set of features for building command-line interfaces, including support for flags, subcommands, and automatic generation of help and usage information.
  • Cobra has a larger and more active community, with more third-party libraries and integrations available.
  • Cobra is more flexible and customizable, allowing for more advanced use cases and complex command-line applications.

Cons of Cobra

  • Cobra has a steeper learning curve compared to Typer, as it requires more boilerplate code and configuration to set up a basic command-line application.
  • Cobra may be overkill for simpler command-line tools, where Typer's more lightweight and opinionated approach may be more suitable.

Code Comparison

Typer:

import typer

app = typer.Typer()

@app.command()
def greet(name: str):
    typer.echo(f"Hello, {name}!")

Cobra:

package main

import (
    "fmt"
    "github.com/spf13/cobra"
)

func main() {
    rootCmd := &cobra.Command{
        Use:   "myapp",
        Short: "A brief description of your application",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("Hello, World!")
        },
    }

    rootCmd.Execute()
}

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Typer

Typer, build great CLIs. Easy to code. Based on Python type hints.

Test Publish Coverage Package version


Documentation: https://typer.tiangolo.com

Source Code: https://github.com/fastapi/typer


Typer is a library for building CLI applications that users will love using and developers will love creating. Based on Python type hints.

It's also a command line tool to run scripts, automatically converting them to CLI applications.

The key features are:

  • Intuitive to write: Great editor support. Completion everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.
  • Easy to use: It's easy to use for the final users. Automatic help, and automatic completion for all shells.
  • Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
  • Start simple: The simplest example adds only 2 lines of code to your app: 1 import, 1 function call.
  • Grow large: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.
  • Run scripts: Typer includes a typer command/program that you can use to run scripts, automatically converting them to CLIs, even if they don't use Typer internally.

FastAPI of CLIs

Typer is FastAPI's little sibling, it's the FastAPI of CLIs.

Installation

Create and activate a virtual environment and then install Typer:

$ pip install typer
---> 100%
Successfully installed typer rich shellingham

Example

The absolute minimum

  • Create a file main.py with:
def main(name: str):
    print(f"Hello {name}")

This script doesn't even use Typer internally. But you can use the typer command to run it as a CLI application.

Run it

Run your application with the typer command:

// Run your application
$ typer main.py run

// You get a nice error, you are missing NAME
Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME
Try 'typer [PATH_OR_MODULE] run --help' for help.
╭─ Error ───────────────────────────────────────────╮
│ Missing argument 'NAME'.                          │
╰───────────────────────────────────────────────────╯


// You get a --help for free
$ typer main.py run --help

Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME

Run the provided Typer app.

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   |
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --help          Show this message and exit.       │
╰───────────────────────────────────────────────────╯

// Now pass the NAME argument
$ typer main.py run Camila

Hello Camila

// It works! 🎉

This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.

Note: auto-completion works when you create a Python package and run it with --install-completion or when you use the typer command.

Use Typer in your code

Now let's start using Typer in your own code, update main.py with:

import typer


def main(name: str):
    print(f"Hello {name}")


if __name__ == "__main__":
    typer.run(main)

Now you could run it with Python directly:

// Run your application
$ python main.py

// You get a nice error, you are missing NAME
Usage: main.py [OPTIONS] NAME
Try 'main.py --help' for help.
╭─ Error ───────────────────────────────────────────╮
│ Missing argument 'NAME'.                          │
╰───────────────────────────────────────────────────╯


// You get a --help for free
$ python main.py --help

Usage: main.py [OPTIONS] NAME

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   |
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --help          Show this message and exit.       │
╰───────────────────────────────────────────────────╯

// Now pass the NAME argument
$ python main.py Camila

Hello Camila

// It works! 🎉

Note: you can also call this same script with the typer command, but you don't need to.

Example upgrade

This was the simplest example possible.

Now let's see one a bit more complex.

An example with two subcommands

Modify the file main.py.

Create a typer.Typer() app, and create two subcommands with their parameters.

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()

And that will:

  • Explicitly create a typer.Typer app.
    • The previous typer.run actually creates one implicitly for you.
  • Add two subcommands with @app.command().
  • Execute the app() itself, as if it was a function (instead of typer.run).

Run the upgraded example

Check the new help:

$ python main.py --help

 Usage: main.py [OPTIONS] COMMAND [ARGS]...

╭─ Options ─────────────────────────────────────────╮
│ --install-completion          Install completion  │
│                               for the current     │
│                               shell.              │
│ --show-completion             Show completion for │
│                               the current shell,  │
│                               to copy it or       │
│                               customize the       │
│                               installation.       │
│ --help                        Show this message   │
│                               and exit.           │
╰───────────────────────────────────────────────────╯
╭─ Commands ────────────────────────────────────────╮
│ goodbye                                           │
│ hello                                             │
╰───────────────────────────────────────────────────╯

// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion

// You have 2 subcommands (the 2 functions): goodbye and hello

Now check the help for the hello command:

$ python main.py hello --help

 Usage: main.py hello [OPTIONS] NAME

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   │
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --help          Show this message and exit.       │
╰───────────────────────────────────────────────────╯

And now check the help for the goodbye command:

$ python main.py goodbye --help

 Usage: main.py goodbye [OPTIONS] NAME

╭─ Arguments ───────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]   │
╰───────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────╮
│ --formal    --no-formal      [default: no-formal] │
│ --help                       Show this message    │
│                              and exit.            │
╰───────────────────────────────────────────────────╯

// Automatic --formal and --no-formal for the bool option 🎉

Now you can try out the new command line application:

// Use it with the hello command

$ python main.py hello Camila

Hello Camila

// And with the goodbye command

$ python main.py goodbye Camila

Bye Camila!

// And with --formal

$ python main.py goodbye --formal Camila

Goodbye Ms. Camila. Have a good day.

Recap

In summary, you declare once the types of parameters (CLI arguments and CLI options) as function parameters.

You do that with standard modern Python types.

You don't have to learn a new syntax, the methods or classes of a specific library, etc.

Just standard Python.

For example, for an int:

total: int

or for a bool flag:

force: bool

And similarly for files, paths, enums (choices), etc. And there are tools to create groups of subcommands, add metadata, extra validation, etc.

You get: great editor support, including completion and type checks everywhere.

Your users get: automatic --help, auto-completion in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using the typer command.

For a more complete example including more features, see the Tutorial - User Guide.

Dependencies

Typer stands on the shoulders of a giant. Its only internal required dependency is Click.

By default it also comes with extra standard dependencies:

  • rich: to show nicely formatted errors automatically.
  • shellingham: to automatically detect the current shell when installing completion.
    • With shellingham you can just use --install-completion.
    • Without shellingham, you have to pass the name of the shell to install completion for, e.g. --install-completion bash.

typer-slim

If you don't want the extra standard optional dependencies, install typer-slim instead.

When you install with:

pip install typer

...it includes the same code and dependencies as:

pip install "typer-slim[standard]"

The standard extra dependencies are rich and shellingham.

Note: The typer command is only included in the typer package.

License

This project is licensed under the terms of the MIT license.