Skip to content
Myr

:memo: Add first version of docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sebastián Ramírez · committed by Sebastián Ramírez · parent 64d1a5f · Browse files · 8 files+1477 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+1477 added−0 removed

  • other:+1477 added−0 removed

8 files+1477 added−0 removed

added:docs/tutorial/first-steps.md+397 added
1## The simplest example23The simplest Typer file could look like this:45```Python6{!./src/first_steps/tutorial001.py!}7```89Copy that to a file `main.py`.1011Test it:1213```bash14python main.py15```1617You will see an output like:1819```hl_lines=""20Hello World21```2223It just prints "Hello World".2425If you type:2627```bash28python main.py --help29```3031it shows:3233```34Usage: main.py [OPTIONS]3536Options:37 --help Show this message and exit.38```3940...but this program is still not very useful. Let's increase that.4142## What is a **CLI argument**4344Here we will use the word **CLI argument** to refer to **CLI parameters** passed in some specific order to the CLI application. By default, they are *required*.4546If you go to your terminal and type:4748```bash49ls ./myproject50```5152`ls` will show the contents of the directory `./myproject`.5354* `ls` is the *command* (or "program", "CLI app").55* `./myproject` is a *CLI argument*.5657They are a bit different from **CLI options** that you will see later below.5859## Add a CLI argument6061Update the previous example with an argument `name`:6263```Python hl_lines="4 5"64{!./src/first_steps/tutorial002.py!}65```6667If you run it without the argument:6869```bash70python main.py71```7273it shows:7475```76Usage: main.py [OPTIONS] NAME77Try "main.py --help" for help.7879Error: Missing argument "NAME".80```8182Now pass that `name` *CLI argument*:8384```bash85python main.py Camila86```8788it shows:8990```91Hello Camila92```9394Here `Camila` is the *CLI argument*.9596## Two CLI arguments9798Now extend that to have 2 arguments, `name` and `lastname`:99100```Python hl_lines="4 5"101{!./src/first_steps/tutorial003.py!}102```103104Now get the help:105106```bash107python main.py --help108```109110it shows:111112```113Usage: main.py [OPTIONS] NAME LASTNAME114115Options:116 --help Show this message and exit.117```118119There are now 2 *CLI arguments*, `name` and `lastname`.120121Now pass a single `name` argument:122123```bash124python main.py Camila125```126127it shows:128129```130Usage: main.py [OPTIONS] NAME LASTNAME131Try "main.py --help" for help.132133Error: Missing argument "LASTNAME".134```135136These 2 arguments are required, so, pass both:137138```bash139python main.py Camila Gutiérrez140```141142it shows:143144```145Hello Camila Gutiérrez146```147148!!! tip149 Notice that the order is important. The last name has to go after the first name.150151 If you called it with:152153 ```bash154 python main.py Gutiérrez Camila155 ```156157 your app wouldn't have a way to know which is the `name` and which the `lastname`. It expects the first *CLI argument* to be the `name` and the second *CLI argument* to be the `lastname`.158159## What is a **CLI option**160161Here we will use the word **CLI option** to refer to **CLI parameters** passed to the CLI application with a specific name. Because they have a name they don't depend on the order. By default they are *optional* (not *required*).162163They are a bit different from **CLI arguments** that you already created.164165If you go to your terminal and type:166167```bash168ls ./myproject --size169```170171`ls` will show the contents of the directory `./myproject` with their `size`.172173* `ls` is the *command* (or "program", "CLI app").174* `./myproject` is a *CLI argument*.175* `--size` is an optional *CLI option*.176177A *CLI option* like `--size` doesn't depend on the order like a *CLI argument*.178179The program knows it has to show the size because it sees `--size`, not because of the order.180181So, if you put the `--size` *before* the *CLI argument*, it still works:182183```bash184ls --size ./myproject185```186187!!! tip188 In this example above the *CLI option* `--size` is just a "flag", it's a boolean value, `True` or `False`.189190 This one doesn't receive any values. But *CLI options* can also receive values like *CLI arguments*. You'll see how later.191192## Add one *CLI option*193194Now add a `--formal` *CLI option*:195196```Python hl_lines="4 5"197{!./src/first_steps/tutorial004.py!}198```199200Here `formal` is a `bool` that is `False` by default.201202If you get the help:203204```bash205python main.py --help206```207208it shows:209210```211Usage: main.py [OPTIONS] NAME LASTNAME212213Options:214 --formal / --no-formal215 --help Show this message and exit.216```217218!!! tip219 Notice that it automatically creates a `--formal` and a `--no-formal` because it detected that `formal` is a `bool`.220221Now call it normally:222223```bash224python main.py Camila Gutiérrez225```226227it still shows:228229```230Hello Camila Gutiérrez231```232233But if you pass `--formal`:234235```bash236python main.py Camila Gutiérrez --formal237```238239it shows:240241```242Good day Ms. Camila Gutiérrez.243```244245And as `formal` is a *CLI option*, you can put it anywhere in this command:246247```bash248python main.py Camila --formal Gutiérrez249```250251and:252253```bash254python main.py --formal Camila Gutiérrez255```256257both still show:258259```260Good day Ms. Camila Gutiérrez.261```262263## A **CLI option* with a value264265Let's convert the `lastname` from a *CLI argument* to a *CLI option*:266267```Python hl_lines="4"268{!./src/first_steps/tutorial005.py!}269```270271As `lastname` now has a default value of `""` (an empty string) it is no longer required in the function, and **Typer** will now by default make it an optional *CLI option*.272273If you get the help:274275```bash276python main.py --help277```278279it now shows:280281```282Usage: main.py [OPTIONS] NAME283284Options:285 --lastname TEXT286 --formal / --no-formal287 --help Show this message and exit.288```289290!!! tip291 Notice the `--lastname`, and notice that it takes a textual value.292293If you call it without a `--lastname`:294295```bash296python main.py Camila297```298299it shows:300301```302Hello Camila303```304305and you can pass the `--lastname`:306307```bash308python main.py Camila --lastname Gutiérrez309```310311and it shows:312313```314Hello Camila Gutiérrez315```316317And as `--lastname` is now a *CLI option* that doesn't depend on the order, you can pass it before the name:318319```bash320python main.py --lastname Gutiérrez Camila321```322323and it will still work normally:324325```326Hello Camila Gutiérrez327```328329## Arguments, options, parameters, optional, required330331Be aware that these terms refer to multiple things depending on the context, and sadly, those "contexts" mix frequently, so it's easy to get confused.332333### In Python334335In Python, the names of the variables in a function, like `name` and `lastname`:336337```Python338def main(name: str, lastname: str = ""):339 pass340```341342are called "Python function parameters" or "Python function arguments".343344!!! note "Technical Details"345 There's actually a very small distinction in Python between "parameter" and "argument".346347 It's quite technical... and somewhat pedantic.348349 One refers to the variable name in a function *declaration*. Like:350 351 ```Python352 def bring_person(name: str, lastname: str = ""):353 pass354 ```355356 The other refers to the value passed when *calling* a function. Like:357358 ```Python359 person = bring_person("Camila", lastname="Gutiérrez")360 ```361362 ...but you will probably see them used interchangeably in most of the places (including here).363364#### Python default values365366In Python, in a function, a parameter with a *default value* like `lastname` in:367368```Python369def main(name: str, lastname: str = ""):370 pass371```372373is considered an "optional parameter" (or "optional argument").374375The default value can be anything, like `""` or `None`.376377And a parameter like `name`, that doesn't have a default value, is considered *required*.378379### In CLIs380381When talking about command line interfaces/applications, the words "argument" and "parameter" are commonly used to refer to that data passed to a CLI app, those parameters.382383But those words don't imply anything about the data being required, needing to be passed in a certain order, nor having a flag like `--lastname`.384385The parameters that come with a flag like `--lastname` and a value (or when the flag itself is the value, like `--formal`) are commonly optional, not required. So, when talking about CLIs it's common to call them *optional arguments* or *optional parameters*.386387In reality, the parameters that require an order can be made *optional* too. And the ones that come with a flag (like `--lastname`) can be *required* too.388389### In **Typer**390391To try and make it a bit easier, we'll normally use the words "parameter" or "argument" to refer to Python functions.392393We'll use ***CLI argument*** to refer to those *CLI parameters* that depend on an order. That are **required** by default.394395And we'll use ***CLI option*** to refer to those *CLI parameters* that depend on a flag (like `--lastname`). That are **optional** by default.396397We will use ***CLI parameter*** to refer to both, *CLI arguments* and *CLI options*.
added:docs/tutorial/intro.md+60 added
added:docs/alternatives.md+417 added
1What inspired **Typer**, how it compares to other alternatives and what it learned from them.23Coming soon...45<!-- ## Intro67**FastAPI** wouldn't exist if not for the previous work of others.89There have been many tools created before that have helped inspire its creation.1011I have been avoiding the creation of a new framework for several years. First I tried to solve all the features covered by **FastAPI** using many different frameworks, plug-ins, and tools.1213But at some point, there was no other option than creating something that provided all these features, taking the best ideas from previous tools, and combining them in the best way possible, using language features that weren't even available before (Python 3.6+ type hints).1415## Previous tools1617### <a href="https://www.djangoproject.com/" target="_blank">Django</a>1819It's the most popular Python framework and is widely trusted. It is used to build systems like Instagram.2021It's relatively tightly coupled with relational databases (like MySQL or PostgreSQL), so, having a NoSQL database (like Couchbase, MongoDB, Cassandra, etc) as the main store engine is not very easy.2223It was created to generate the HTML in the backend, not to create APIs used by a modern frontend (like React, Vue.js and Angular) or by other systems (like <abbr title="Internet of Things">IoT</abbr> devices) communicating with it.2425### <a href="https://www.django-rest-framework.org/" target="_blank">Django REST Framework</a>2627Django REST framework was created to be a flexible toolkit for building Web APIs using Django underneath, to improve its API capabilities.2829It is used by many companies including Mozilla, Red Hat and Eventbrite.3031It was one of the first examples of **automatic API documentation**, and this was specifically one of the first ideas that inspired "the search for" **FastAPI**.3233!!! note34 Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based.353637!!! check "Inspired **FastAPI** to"38 Have an automatic API documentation web user interface.3940### <a href="http://flask.pocoo.org/" target="_blank">Flask</a>4142Flask is a "microframework", it doesn't include database integrations nor many of the things that come by default in Django.4344This simplicity and flexibility allow doing things like using NoSQL databases as the main data storage system.4546As it is very simple, it's relatively intuitive to learn, although the documentation gets somewhat technical at some points.4748It is also commonly used for other applications that don't necessarily need a database, user management, or any of the many features that come pre-built in Django. Although many of these features can be added with plug-ins.4950This decoupling of parts, and being a "microframework" that could be extended to cover exactly what is needed was a key feature that I wanted to keep.5152Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask.5354!!! check "Inspired **FastAPI** to"55 Be a micro-framework. Making it easy to mix and match the tools and parts needed.5657 Have a simple and easy to use routing system.585960### <a href="http://docs.python-requests.org" target="_blank">Requests</a>6162**FastAPI** is not actually an alternative to **Requests**. Their scope is very different.6364It would actually be common to use Requests *inside* of a FastAPI application.6566But still, FastAPI got quite some inspiration from Requests.6768**Requests** is a library to *interact* with APIs (as a client), while **FastAPI** is a library to *build* APIs (as a server).6970They are, more or less, at opposite ends, complementing each other.7172Requests has a very simple and intuitive design, it's very easy to use, with sensible defaults. But at the same time, it's very powerful and customizable.7374That's why, as said in the official website:7576> Requests is one of the most downloaded Python packages of all time7778The way you use it is very simple. For example, to do a `GET` request, you would write:7980```Python81response = requests.get("http://example.com/some/url")82```8384The FastAPI counterpart API path operation could look like:8586```Python hl_lines="1"87@app.get("/some/url")88def read_url():89 return {"message": "Hello World"}90```9192See the similarities in `requests.get(...)` and `@app.get(...)`.9394!!! check "Inspired **FastAPI** to"95 * Have a simple and intuitive API.96 * Use HTTP method names (operations) directly, in a straightforward and intuitive way.97 * Have sensible defaults, but powerful customizations.9899100### <a href="https://swagger.io/" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" target="_blank">OpenAPI</a>101102The main feature I wanted from Django REST Framework was the automatic API documentation.103104Then I found that there was a standard to document APIs, using JSON (or YAML, an extension of JSON) called Swagger.105106And there was a web user interface for Swagger APIs already created. So, being able to generate Swagger documentation for an API would allow using this web user interface automatically.107108At some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI.109110That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI".111112!!! check "Inspired **FastAPI** to"113 Adopt and use an open standard for API specifications, instead of a custom schema.114115 And integrate standards-based user interface tools:116117 * <a href="https://github.com/swagger-api/swagger-ui" target="_blank">Swagger UI</a>118 * <a href="https://github.com/Rebilly/ReDoc" target="_blank">ReDoc</a>119120 These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of additional alternative user interfaces for OpenAPI (that you can use with **FastAPI**).121122### Flask REST frameworks123124There are several Flask REST frameworks, but after investing the time and work into investigating them, I found that many are discontinued or abandoned, with several standing issues that made them unfit.125126### <a href="https://marshmallow.readthedocs.io/en/3.0/" target="_blank">Marshmallow</a>127128One of the main features needed by API systems is data "<abbr title="also called marshalling, conversion">serialization</abbr>" which is taking data from the code (Python) and converting it into something that can be sent through the network. For example, converting an object containing data from a database into a JSON object. Converting `datetime` objects into strings, etc.129130Another big feature needed by APIs is data validation, making sure that the data is valid, given certain parameters. For example, that some field is an `int`, and not some random string. This is especially useful for incoming data.131132Without a data validation system, you would have to do all the checks by hand, in code.133134These features are what Marshmallow was built to provide. It is a great library, and I have used it a lot before.135136But it was created before there existed Python type hints. So, to define every <abbr title="the definition of how data should be formed">schema</abbr> you need to use specific utils and classes provided by Marshmallow.137138!!! check "Inspired **FastAPI** to"139 Use code to define "schemas" that provide data types and validation, automatically.140141### <a href="https://webargs.readthedocs.io/en/latest/" target="_blank">Webargs</a>142143Another big feature required by APIs is <abbr title="reading and converting to Python data">parsing</abbr> data from incoming requests.144145Webargs is a tool that was made to provide that on top of several frameworks, including Flask.146147It uses Marshmallow underneath to do the data validation. And it was created by the same developers.148149It's a great tool and I have used it a lot too, before having **FastAPI**.150151!!! info152 Webargs was created by the same Marshmallow developers.153154!!! check "Inspired **FastAPI** to"155 Have automatic validation of incoming request data.156157### <a href="https://apispec.readthedocs.io/en/stable/" target="_blank">APISpec</a>158159Marshmallow and Webargs provide validation, parsing and serialization as plug-ins.160161But documentation is still missing. Then APISpec was created.162163It is a plug-in for many frameworks (and there's a plug-in for Starlette too).164165The way it works is that you write the definition of the schema using YAML format inside the docstring of each function handling a route.166167And it generates OpenAPI schemas.168169That's how it works in Flask, Starlette, Responder, etc.170171But then, we have again the problem of having a micro-syntax, inside of a Python string (a big YAML).172173The editor can't help much with that. And if we modify parameters or Marshmallow schemas and forget to also modify that YAML docstring, the generated schema would be obsolete.174175!!! info176 APISpec was created by the same Marshmallow developers.177178179!!! check "Inspired **FastAPI** to"180 Support the open standard for APIs, OpenAPI.181182### <a href="https://flask-apispec.readthedocs.io/en/latest/" target="_blank">Flask-apispec</a>183184It's a Flask plug-in, that ties together Webargs, Marshmallow and APISpec.185186It uses the information from Webargs and Marshmallow to automatically generate OpenAPI schemas, using APISpec.187188It's a great tool, very under-rated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract.189190This solved having to write YAML (another syntax) inside of Python docstrings.191192This combination of Flask, Flask-apispec with Marshmallow and Webargs was my favorite backend stack until building **FastAPI**.193194Using it led to the creation of several Flask full-stack generators. These are the main stack I (and several external teams) have been using up to now:195196* <a href="https://github.com/tiangolo/full-stack" target="_blank">https://github.com/tiangolo/full-stack</a>197* <a href="https://github.com/tiangolo/full-stack-flask-couchbase" target="_blank">https://github.com/tiangolo/full-stack-flask-couchbase</a>198* <a href="https://github.com/tiangolo/full-stack-flask-couchdb" target="_blank">https://github.com/tiangolo/full-stack-flask-couchdb</a>199200And these same full-stack generators were the base of the <a href="/project-generation/" target="_blank">**FastAPI** project generator</a>.201202!!! info203 Flask-apispec was created by the same Marshmallow developers.204205!!! check "Inspired **FastAPI** to"206 Generate the OpenAPI schema automatically, from the same code that defines serialization and validation.207208### <a href="https://nestjs.com/" target="_blank">NestJS</a> (and <a href="https://angular.io/" target="_blank">Angular</a>)209210This isn't even Python, NestJS is a JavaScript (TypeScript) NodeJS framework inspired by Angular.211212It achieves something somewhat similar to what can be done with Flask-apispec.213214It has an integrated dependency injection system, inspired by Angular two. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition.215216As the parameters are described with TypeScript types (similar to Python type hints), editor support is quite good.217218But as TypeScript data is not preserved after compilation to JavaScript, it cannot rely on the types to define validation, serialization and documentation at the same time. Due to this and some design decisions, to get validation, serialization and automatic schema generation, it's needed to add decorators in many places. So, it becomes quite verbose.219220It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated.221222!!! check "Inspired **FastAPI** to"223 Use Python types to have great editor support.224225 Have a powerful dependency injection system. Find a way to minimize code repetition.226227### <a href="https://sanic.readthedocs.io/en/latest/" target="_blank">Sanic</a>228229It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask.230231!!! note "Technical Details"232 It used <a href="https://github.com/MagicStack/uvloop" target="_blank">`uvloop`</a> instead of the default Python `asyncio` loop. That's what made it so fast.233234 It <a href="https://github.com/huge-success/sanic/issues/761" target="_blank">still doesn't implement the ASGI spec for Python asynchronous web development</a>, but it clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks.235236!!! check "Inspired **FastAPI** to"237 Find a way to have a crazy performance.238 239 That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks).240241### <a href="https://falconframework.org/" target="_blank">Falcon</a>242243Falcon is another high performance Python framework, it is designed to be minimal, and work as the foundation of other frameworks like Hug.244245It uses the previous standard for Python web frameworks (WSGI) which is synchronous, so it can't handle WebSockets and other use cases. Nevertheless, it also has a very good performance.246247It is designed to have functions that receive two parameters, one "request" and one "response". Then you "read" parts from the request, and "write" parts to the response. Because of this design, it is not possible to declare request parameters and bodies with standard Python type hints as function parameters.248249So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters.250251!!! check "Inspired **FastAPI** to"252 Find ways to get great performance.253254 Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions.255256 Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes.257258### <a href="https://moltenframework.com/" target="_blank">Molten</a>259260I discovered Molten in the first stages of building **FastAPI**. And it has quite similar ideas:261262* Based on Python type hints.263* Validation and documentation from these types.264* Dependency Injection system.265266It doesn't use a data validation, serialization and documentation third-party library like Pydantic, it has its own. So, these data type definitions would not be reusable as easily.267268It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high-performance provided by tools like Uvicorn, Starlette and Sanic.269270The dependency injection system requires pre-registration of the dependencies and the dependencies are solved based on the declared types. So, it's not possible to declare more than one "component" that provides a certain type.271272Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled.273274!!! check "Inspired **FastAPI** to"275 Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before.276277 This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic).278279### <a href="http://www.hug.rest/" target="_blank">Hug</a>280281Hug was one of the first frameworks to implement the declaration of API parameter types using Python type hints. This was a great idea that inspired other tools to do the same.282283It used custom types in its declarations instead of standard Python types, but it was still a huge step forward.284285It also was one of the first frameworks to generate a custom schema declaring the whole API in JSON.286287It was not based on a standard like OpenAPI and JSON Schema. So it wouldn't be straightforward to integrate it with other tools, like Swagger UI. But again, it was a very innovative idea.288289It has an interesting, uncommon feature: using the same framework, it's possible to create APIs and also CLIs.290291As it is based on the previous standard for synchronous Python web frameworks (WSGI), it can't handle Websockets and other things, although it still has high performance too.292293!!! info294 Hug was created by Timothy Crosley, the same creator of <a href="https://github.com/timothycrosley/isort" target="_blank">`isort`</a>, a great tool to automatically sort imports in Python files.295296!!! check "Ideas inspired in **FastAPI**"297 Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.298299 Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.300301 Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies.302303### <a href="https://github.com/encode/apistar" target="_blank">APIStar</a> (<= 0.5)304305Right before deciding to build **FastAPI** I found **APIStar** server. It had almost everything I was looking for and had a great design.306307It was one of the first implementations of a framework using Python type hints to declare parameters and requests that I ever saw (before NestJS and Molten). I found it more or less at the same time as Hug. But APIStar used the OpenAPI standard.308309It had automatic data validation, data serialization and OpenAPI schema generation based on the same type hints in several places.310311Body schema definitions didn't use the same Python type hints like Pydantic, it was a bit more similar to Marshmallow, so, editor support wouldn't be as good, but still, APIStar was the best available option.312313It had the best performance benchmarks at the time (only surpassed by Starlette).314315At first, it didn't have an automatic API documentation web UI, but I knew I could add Swagger UI to it.316317It had a dependency injection system. It required pre-registration of components, as other tools discussed above. But still, it was a great feature.318319I was never able to use it in a full project, as it didn't have security integration, so, I couldn't replace all the features I was having with the full-stack generators based on Flask-apispec. I had in my backlog of projects to create a pull request adding that functionality.320321But then, the project's focus shifted.322323It was no longer an API web framework, as the creator needed to focus on Starlette.324325Now APIStar is a set of tools to validate OpenAPI specifications, not a web framework.326327!!! info328 APIStar was created by Tom Christie. The same guy that created:329330 * Django REST Framework331 * Starlette (in which **FastAPI** is based)332 * Uvicorn (used by Starlette and **FastAPI**)333334!!! check "Inspired **FastAPI** to"335 Exist.336337 The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea.338 339 And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.340341 Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.342343 I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools.344345## Used by **FastAPI**346347### <a href="https://pydantic-docs.helpmanual.io/" target="_blank">Pydantic</a>348349Pydantic is a library to define data validation, serialization and documentation (using JSON Schema) based on Python type hints.350351That makes it extremely intuitive.352353It is comparable to Marshmallow. Although it's faster than Marshmallow in benchmarks. And as it is based on the same Python type hints, the editor support is great.354355!!! check "**FastAPI** uses it to"356 Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema).357358 **FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does.359360### <a href="https://www.starlette.io/" target="_blank">Starlette</a>361362Starlette is a lightweight <abbr title="The new standard for building asynchronous Python web">ASGI</abbr> framework/toolkit, which is ideal for building high-performance asyncio services.363364It is very simple and intuitive. It's designed to be easily extensible, and have modular components.365366It has:367368* Seriously impressive performance.369* WebSocket support.370* GraphQL support.371* In-process background tasks.372* Startup and shutdown events.373* Test client built on requests.374* CORS, GZip, Static Files, Streaming responses.375* Session and Cookie support.376* 100% test coverage.377* 100% type annotated codebase.378* Zero hard dependencies.379380Starlette is currently the fastest Python framework tested. Only surpassed by Uvicorn, which is not a framework, but a server.381382Starlette provides all the basic web microframework functionality.383384But it doesn't provide automatic data validation, serialization or documentation.385386That's one of the main things that **FastAPI** adds on top, all based on Python type hints (using Pydantic). That, plus the dependency injection system, security utilities, OpenAPI schema generation, etc.387388!!! note "Technical Details"389 ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that.390391 Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`.392393!!! check "**FastAPI** uses it to"394 Handle all the core web parts. Adding features on top.395396 The class `FastAPI` itself inherits directly from the class `Starlette`.397 398 So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.399400### <a href="https://www.uvicorn.org/" target="_blank">Uvicorn</a>401402Uvicorn is a lightning-fast ASGI server, built on uvloop and httptools.403404It is not a web framework, but a server. For example, it doesn't provide tools for routing by paths. That's something that a framework like Starlette (or **FastAPI**) would provide on top.405406It is the recommended server for Starlette and **FastAPI**.407408!!! check "**FastAPI** recommends it as"409 The main web server to run **FastAPI** applications.410411 You can combine it with Gunicorn, to have an asynchronous multi-process server.412413 Check more details in the <a href="/deployment/" target="_blank">Deployment</a> section.414415## Benchmarks and speed416417To understand, compare, and see the difference between Uvicorn, Starlette and FastAPI, check the section about [Benchmarks](/benchmarks/). -->
added:docs/contributing.md+125 added
1First, you might want to see the basic ways to <a href="https://typer.tiangolo.com/help-typer/" target="_blank">help Typer and get help</a>.23Coming soon...45<!-- ## Developing67If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment.8910### Pipenv1112If you are using <a href="https://pipenv.readthedocs.io/en/latest/" target="_blank">Pipenv</a>, you can create a virtual environment and install the packages with:1314```bash15pipenv install --dev16```1718Then you can activate that virtual environment with:1920```bash21pipenv shell22```232425### No Pipenv2627If you are not using Pipenv, you can create a virtual environment with your preferred tool, and install the packages listed in the file `Pipfile`.282930### Flit3132**FastAPI** uses <a href="https://flit.readthedocs.io/en/latest/index.html" target="_blank">Flit</a> to build, package and publish the project.3334If you installed the development dependencies with one of the methods above, you already have the `flit` command.3536To install your local version of FastAPI as a package in your local environment, run:3738```bash39flit install --symlink40```4142It will install your local FastAPI in your local environment.434445#### Using your local FastAPI4647If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code.4849And if you update that local FastAPI source code, as it is installed with `--symlink`, when you run that Python file again, it will use the fresh version of FastAPI you just edited.5051That way, you don't have to "install" your local version to be able to test every change.525354### Format5556There is a script that you can run that will format and clean all your code:5758```bash59bash scripts/lint.sh60```6162It will also auto-sort all your imports.6364For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above:6566```bash67flit install --symlink68```697071### Docs7273The documentation uses <a href="https://www.mkdocs.org/" target="_blank">MkDocs</a>.7475All the documentation is in Markdown format in the directory `./docs`.7677Many of the tutorials have blocks of code.7879In most of the cases, these blocks of code are actual complete applications that can be run as is.8081In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs/src/` directory.8283And those Python files are included/injected in the documentation when generating the site.848586#### Docs for tests8788Most of the tests actually run against the example source files in the documentation.8990This helps making sure that:9192* The documentation is up to date.93* The documentation examples can be run as is.94* Most of the features are covered by the documentation, ensured by the coverage tests.9596During local development, there is a script that builds the site and checks for any changes, live-reloading:9798```bash99bash scripts/docs-live.sh100```101102It will serve the documentation on `http://0.0.0.0:8008`.103104That way, you can edit the documentation/source files and see the changes live.105106#### Apps and docs at the same time107108And if you run the examples with, e.g.:109110```bash111uvicorn tutorial001:app --reload112```113114as Uvicorn by default will use the port `8000`, the documentation on port `8008` won't clash.115116117### Tests118119There is a script that you can run locally to test all the code and generate coverage reports in HTML:120121```bash122bash scripts/test-cov-html.sh123```124125This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. -->
added:docs/features.md+74 added
added:docs/help-typer.md+92 added
1Are you liking **Typer**?23Would you like to help Typer, other users, and the author?45Or would you like to get help with **Typer**?67There are very simple ways to help (several involve just one or two clicks).89And there are several ways to get help too.1011## Star **Typer** in GitHub1213You can "star" Typer in GitHub (clicking the star button at the top right): <a href="https://github.com/tiangolo/typer" target="_blank">https://github.com/tiangolo/typer</a>.1415By adding a star, other users will be able to find it more easily and see that it has been already useful for others.1617## Watch the GitHub repository for releases1819You can "watch" Typer in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/tiangolo/typer" target="_blank">https://github.com/tiangolo/typer</a>.2021There you can select "Releases only".2223Doing it, you will receive notifications (in your email) whenever there's a new release (a new version) of **Typer** with bug fixes and new features.2425## Connect with the author2627You can connect with <a href="https://tiangolo.com" target="_blank">me (Sebastián Ramírez / `tiangolo`)</a>, the author.2829You can:3031* <a href="https://github.com/tiangolo" target="_blank">Follow me on **GitHub**</a>.32 * See other Open Source projects I have created that could help you.33 * Follow me to see when I create a new Open Source project.34* <a href="https://twitter.com/tiangolo" target="_blank">Follow me on **Twitter**</a>.35 * Tell me how you use Typer (I love to hear that).36 * Ask questions.37* <a href="https://www.linkedin.com/in/tiangolo/" target="_blank">Connect with me on **Linkedin**</a>.38 * Talk to me.39 * Endorse me or recommend me :)40* Read what I write (or follow me):41 * Read other ideas, articles and tools I have created.42 * Follow me to see when I publish something new.43 * On <a href="https://dev.to/tiangolo" target="_blank">**Dev.to**</a>.44 * On <a href="https://medium.com/@tiangolo" target="_blank">**Medium**</a>.4546## Tweet about **Typer**4748<a href="http://twitter.com/home/?status=I'm loving Typer because... https://github.com/tiangolo/typer cc @tiangolo" target="_blank">Tweet about **Typer**</a> and let me and others know why you like it.4950## Let me know how are you using **Typer**5152I love to hear about how **Typer** is being used, what have you liked in it, in which project/company you are using it, etc.5354You can let me know:5556* <a href="http://twitter.com/home/?status=Hey @tiangolo, I'm using Typer at..." target="_blank">On **Twitter**</a>.57* <a href="https://www.linkedin.com/in/tiangolo/" target="_blank">On **Linkedin**</a>.58* <a href="https://dev.to/tiangolo" target="_blank">On **Dev.to**</a>.59* <a href="https://medium.com/@tiangolo" target="_blank">On **Medium**</a>.6061## Help others with issues in GitHub6263You can see <a href="https://github.com/tiangolo/typer/issues" target="_blank">existing issues</a> and try and help others.6465## Watch the GitHub repository6667You can "watch" Typer in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/tiangolo/typer" target="_blank">https://github.com/tiangolo/typer</a>.6869If you select "Watching" instead of "Releases only", you will receive notifications when someone creates a new issue.7071Then you can try and help them solving those issues.7273## Create issues7475You can <a href="https://github.com/tiangolo/typer/issues/new/choose" target="_blank">create a new issue</a> in the GitHub repository, for example to:7677* Report a bug/issue.78* Suggest a new feature.79* Ask a question.8081## Create a Pull Request8283You can <a href="https://github.com/tiangolo/typer" target="_blank">create a Pull Request</a>, for example:8485* To fix a typo you found on the documentation.86* To propose new documentation sections.87* To fix an existing issue/bug.88* To add a new feature.8990---9192Thanks!
added:docs/index.md+305 added
1<p align="center">2 <a href="https://typer.tiangolo.com"><img src="/img/logo-margin/logo-margin-vector.svg" alt="Typer"></a>3</p>4<p align="center">5 <em>Typer: CLIs with autocompletion. While developing and using.</em>6</p>7<p align="center">8<a href="https://travis-ci.org/tiangolo/typer" target="_blank">9 <img src="https://travis-ci.org/tiangolo/typer.svg?branch=master" alt="Build Status">10</a>11<a href="https://codecov.io/gh/tiangolo/typer" target="_blank">12 <img src="https://codecov.io/gh/tiangolo/typer/branch/master/graph/badge.svg" alt="Coverage">13</a>14<a href="https://pypi.org/project/typer" target="_blank">15 <img src="https://badge.fury.io/py/typer.svg" alt="Package version">16</a>17</p>1819---2021**Documentation**: <a href="https://typer.tiangolo.com" target="_blank">https://typer.tiangolo.com</a>2223**Source Code**: <a href="https://github.com/tiangolo/typer" target="_blank">https://github.com/tiangolo/typer</a>2425---2627Typer is library to build <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users love using and developers love creating. Based on Python 3.6+ type hints.2829**Typer** is the little sibling of <a href="https://fastapi.tiangolo.com" target="_blank">FastAPI</a>. And it's intended to be the FastAPI of CLIs.3031The key features are:3233* **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.34* **Easy to use**: It's easy to use for the final users. Automatic help commands, and (optional) automatic completion for all shells.35* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.36* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.37* **Grow large**: Grow in complexity as much as you want create arbitrarily complex trees of commands and groups sub-commands, with options and arguments.3839## Requirements4041Python 3.6+4243Typer stands on the shoulders of a giant. Internally it uses <a href="https://click.palletsprojects.com/" target="_blank">Click</a>, that's the only dependency.4445## Installation4647```bash48pip install typer49```5051## Example5253### The absolute minimum5455* Create a file `main.py` with:5657```Python58import typer596061def main(name: str):62 typer.echo(f"Hello {name}")636465if __name__ == "__main__":66 typer.run(main)67```6869### Run it7071Run your application:7273```bash74python main.py75```7677you will get a response like:7879```80Usage: main.py [OPTIONS] NAME81Try "main.py --help" for help.8283Error: Missing argument "NAME".84```8586Now pass the `NAME` *argument*:8788```bash89python main.py Camila90```9192You will get a response like:9394```95Hello Camila96```9798And you automatically get a `--help` command:99100```bash101python main.py --help102```103104shows:105106```107Usage: main.py [OPTIONS] NAME108109Options:110 --help Show this message and exit.111```112113## Example upgrade114115The previous example was the extreme in terms of simplicity.116117Now let's see one a bit more complex.118119### An example with two sub-commands120121Modify the file `main.py`.122123Create a `typer.Typer()` app, and create two sub-commands with their parameters.124125```Python hl_lines="3 6 11 20"126import typer127128app = typer.Typer()129130131@app.command()132def hello(name: str):133 typer.echo(f"Hello {name}")134135136@app.command()137def goodbye(name: str, formal: bool = False):138 if formal:139 typer.echo(f"Goodbye Ms. {name}. Have a good day.")140 else:141 typer.echo(f"Bye {name}!")142143144if __name__ == "__main__":145 app()146```147148And that will:149150* Explicitly create a `typer.Typer` app.151 * The previous `typer.run` actually creates one implicitly for you.152* Add two sub-commands with `@app.command()`.153* Execute the `app()` itself, as if it was a function (instead of `typer.run`).154155### Run the upgraded example156157Get the main `--help`:158159```bash160python main.py --help161```162163shows:164165```166Usage: main.py [OPTIONS] COMMAND [ARGS]...167168Options:169 --help Show this message and exit.170171Commands:172 goodbye173 hello174```175176You have 2 sub-commands (the 2 functions), `goodbye` and `hello`.177178Now get the help for `hello`:179180```bash181python main.py hello --help182```183184shows:185186```187Usage: main.py hello [OPTIONS] NAME188189Options:190 --help Show this message and exit.191```192193And now get the help for `goodbye`:194195```bash196python main.py goodbye --help197```198199shows:200201```202Usage: main.py goodbye [OPTIONS] NAME203204Options:205 --formal / --no-formal206 --help Show this message and exit.207```208209Notice how it automatically creates a `--formal` and `--no-formal` for your `bool` *option*.210211---212213And of course, if you use it, it does what you expect:214215```bash216python main.py hello Camila217```218219shows:220221```222Hello Camila223```224225Then:226227```bash228python main.py goodbye Camila229```230231shows:232233```234Bye Camila!235```236237And:238239```bash240python main.py goodbye --formal Camila241```242243shows:244245```246Goodbye Ms. Camila. Have a good day.247```248249### Recap250251In summary, you declare **once** the types of parameters (*arguments* and *options*) as function parameters.252253You do that with standard modern Python types.254255You don't have to learn a new syntax, the methods or classes of a specific library, etc.256257Just standard **Python 3.6+**.258259For example, for an `int`:260261```Python262total: int263```264265or for a `bool` flag:266267```Python268force: bool269```270271And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of sub-commands**, add metadata, extra **validation**, etc.272273**You get**: great editor support, including **completion** and **type checks** everywhere.274275**Your users get**: automatic **`--help`**, (optional) **autocompletion** in their terminal (Bash, Zsh, Fish, PowerShell).276277For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/intro/">Tutorial - User Guide</a>.278279## Optional Dependencies280281Typer uses <a href="https://click.palletsprojects.com/" target="_blank">Click</a> internally. That's the only dependency.282283But you can install extras:284285* <a href="https://pypi.org/project/colorama/" target="_blank"><code>colorama</code></a>: and Click will automatically use it to make sure colors always work correctly, even in Windows.286 * Then you can use any tool you want to output colors in all the systems, including the integrated `typer.style()` and `typer.secho()` (provided by Click).287 * Or any other tool, e.g. <a href="https://pypi.org/project/wasabi/" target="_blank"><code>wasabi</code></a>, <a href="https://github.com/erikrose/blessings" target="_blank"><code>blessings</code></a>.288* <a href="https://github.com/click-contrib/click-completion" target="_blank"><code>click-completion</code></a>: and Typer will automatically configure it to provide completion for all the shells, including installation commands.289290You can install `typer` with `colorama` and `click-completion` with `pip3 install typer[all]`.291292## Other tools and plug-ins293294Click has many plug-ins available that you can use. And there are many tools that help with command line applications that you can use as well, even if they are not related to Typer or Click.295296For example:297298* <a href="https://github.com/click-contrib/click-spinner" target="_blank"><code>click-spinner</code></a>: to show the user that you are loading data. A Click plug-in.299 * * There are several other Click plug-ins at <a href="https://github.com/click-contrib" target="_blank">click-contrib</a> that you can explore.300* <a href="https://pypi.org/project/tabulate/" target="_blank"><code>tabulate</code></a>: to automatically display tabular data nicely. Independent of Click or typer.301* etc... you can re-use many of the great available tools for building CLIs.302303## License304305This project is licensed under the terms of the MIT license.
added:docs/release-notes.md+7 added