+ * @version 0.0.1
+ * @license MIT
+ */
+
+'use strict';
+
+/** Generate a terminal widget. */
+class Termynal {
+ /**
+ * Construct the widget's settings.
+ * @param {(string|Node)=} container - Query selector or container element.
+ * @param {Object=} options - Custom settings.
+ * @param {string} options.prefix - Prefix to use for data attributes.
+ * @param {number} options.startDelay - Delay before animation, in ms.
+ * @param {number} options.typeDelay - Delay between each typed character, in ms.
+ * @param {number} options.lineDelay - Delay between each line, in ms.
+ * @param {number} options.progressLength - Number of characters displayed as progress bar.
+ * @param {string} options.progressChar – Character to use for progress bar, defaults to █.
+ * @param {number} options.progressPercent - Max percent of progress.
+ * @param {string} options.cursor – Character to use for cursor, defaults to ▋.
+ * @param {Object[]} lineData - Dynamically loaded line data objects.
+ * @param {boolean} options.noInit - Don't initialise the animation.
+ */
+ constructor(container = '#termynal', options = {}) {
+ this.container = (typeof container === 'string') ? document.querySelector(container) : container;
+ this.pfx = `data-${options.prefix || 'ty'}`;
+ this.originalStartDelay = this.startDelay = options.startDelay
+ || parseFloat(this.container.getAttribute(`${this.pfx}-startDelay`)) || 600;
+ this.originalTypeDelay = this.typeDelay = options.typeDelay
+ || parseFloat(this.container.getAttribute(`${this.pfx}-typeDelay`)) || 90;
+ this.originalLineDelay = this.lineDelay = options.lineDelay
+ || parseFloat(this.container.getAttribute(`${this.pfx}-lineDelay`)) || 1500;
+ this.progressLength = options.progressLength
+ || parseFloat(this.container.getAttribute(`${this.pfx}-progressLength`)) || 40;
+ this.progressChar = options.progressChar
+ || this.container.getAttribute(`${this.pfx}-progressChar`) || '█';
+ this.progressPercent = options.progressPercent
+ || parseFloat(this.container.getAttribute(`${this.pfx}-progressPercent`)) || 100;
+ this.cursor = options.cursor
+ || this.container.getAttribute(`${this.pfx}-cursor`) || '▋';
+ this.lineData = this.lineDataToElements(options.lineData || []);
+ this.loadLines()
+ if (!options.noInit) this.init()
+ }
+
+ loadLines() {
+ // Load all the lines and create the container so that the size is fixed
+ // Otherwise it would be changing and the user viewport would be constantly
+ // moving as she/he scrolls
+ const finish = this.generateFinish()
+ finish.style.visibility = 'hidden'
+ this.container.appendChild(finish)
+ // Appends dynamically loaded lines to existing line elements.
+ this.lines = [...this.container.querySelectorAll(`[${this.pfx}]`)].concat(this.lineData);
+ for (let line of this.lines) {
+ line.style.visibility = 'hidden'
+ this.container.appendChild(line)
+ }
+ const restart = this.generateRestart()
+ restart.style.visibility = 'hidden'
+ this.container.appendChild(restart)
+ this.container.setAttribute('data-termynal', '');
+ }
+
+ /**
+ * Initialise the widget, get lines, clear container and start animation.
+ */
+ init() {
+ /**
+ * Calculates width and height of Termynal container.
+ * If container is empty and lines are dynamically loaded, defaults to browser `auto` or CSS.
+ */
+ const containerStyle = getComputedStyle(this.container);
+ this.container.style.width = containerStyle.width !== '0px' ?
+ containerStyle.width : undefined;
+ this.container.style.minHeight = containerStyle.height !== '0px' ?
+ containerStyle.height : undefined;
+
+ this.container.setAttribute('data-termynal', '');
+ this.container.innerHTML = '';
+ for (let line of this.lines) {
+ line.style.visibility = 'visible'
+ }
+ this.start();
+ }
+
+ /**
+ * Start the animation and rener the lines depending on their data attributes.
+ */
+ async start() {
+ this.addFinish()
+ await this._wait(this.startDelay);
+
+ for (let line of this.lines) {
+ const type = line.getAttribute(this.pfx);
+ const delay = line.getAttribute(`${this.pfx}-delay`) || this.lineDelay;
+
+ if (type == 'input') {
+ line.setAttribute(`${this.pfx}-cursor`, this.cursor);
+ await this.type(line);
+ await this._wait(delay);
+ }
+
+ else if (type == 'progress') {
+ await this.progress(line);
+ await this._wait(delay);
+ }
+
+ else {
+ this.container.appendChild(line);
+ await this._wait(delay);
+ }
+
+ line.removeAttribute(`${this.pfx}-cursor`);
+ }
+ this.addRestart()
+ this.finishElement.style.visibility = 'hidden'
+ this.lineDelay = this.originalLineDelay
+ this.typeDelay = this.originalTypeDelay
+ this.startDelay = this.originalStartDelay
+ }
+
+ generateRestart() {
+ const restart = document.createElement('a')
+ restart.onclick = (e) => {
+ e.preventDefault()
+ this.container.innerHTML = ''
+ this.init()
+ }
+ restart.href = '#'
+ restart.setAttribute('data-terminal-control', '')
+ restart.innerHTML = "restart ↻"
+ return restart
+ }
+
+ generateFinish() {
+ const finish = document.createElement('a')
+ finish.onclick = (e) => {
+ e.preventDefault()
+ this.lineDelay = 0
+ this.typeDelay = 0
+ this.startDelay = 0
+ }
+ finish.href = '#'
+ finish.setAttribute('data-terminal-control', '')
+ finish.innerHTML = "fast →"
+ this.finishElement = finish
+ return finish
+ }
+
+ addRestart() {
+ const restart = this.generateRestart()
+ this.container.appendChild(restart)
+ }
+
+ addFinish() {
+ const finish = this.generateFinish()
+ this.container.appendChild(finish)
+ }
+
+ /**
+ * Animate a typed line.
+ * @param {Node} line - The line element to render.
+ */
+ async type(line) {
+ const chars = [...line.textContent];
+ line.textContent = '';
+ this.container.appendChild(line);
+
+ for (let char of chars) {
+ const delay = line.getAttribute(`${this.pfx}-typeDelay`) || this.typeDelay;
+ await this._wait(delay);
+ line.textContent += char;
+ }
+ }
+
+ /**
+ * Animate a progress bar.
+ * @param {Node} line - The line element to render.
+ */
+ async progress(line) {
+ const progressLength = line.getAttribute(`${this.pfx}-progressLength`)
+ || this.progressLength;
+ const progressChar = line.getAttribute(`${this.pfx}-progressChar`)
+ || this.progressChar;
+ const chars = progressChar.repeat(progressLength);
+ const progressPercent = line.getAttribute(`${this.pfx}-progressPercent`)
+ || this.progressPercent;
+ line.textContent = '';
+ this.container.appendChild(line);
+
+ for (let i = 1; i < chars.length + 1; i++) {
+ await this._wait(this.typeDelay);
+ const percent = Math.round(i / chars.length * 100);
+ line.textContent = `${chars.slice(0, i)} ${percent}%`;
+ if (percent>progressPercent) {
+ break;
+ }
+ }
+ }
+
+ /**
+ * Helper function for animation delays, called with `await`.
+ * @param {number} time - Timeout, in ms.
+ */
+ _wait(time) {
+ return new Promise(resolve => setTimeout(resolve, time));
+ }
+
+ /**
+ * Converts line data objects into line elements.
+ *
+ * @param {Object[]} lineData - Dynamically loaded lines.
+ * @param {Object} line - Line data object.
+ * @returns {Element[]} - Array of line elements.
+ */
+ lineDataToElements(lineData) {
+ return lineData.map(line => {
+ let div = document.createElement('div');
+ div.innerHTML = `${line.value || ''}`;
+
+ return div.firstElementChild;
+ });
+ }
+
+ /**
+ * Helper function for generating attributes string.
+ *
+ * @param {Object} line - Line data object.
+ * @returns {string} - String of attributes.
+ */
+ _attributes(line) {
+ let attrs = '';
+ for (let prop in line) {
+ // Custom add class
+ if (prop === 'class') {
+ attrs += ` class=${line[prop]} `
+ continue
+ }
+ if (prop === 'type') {
+ attrs += `${this.pfx}="${line[prop]}" `
+ } else if (prop !== 'value') {
+ attrs += `${this.pfx}-${prop}="${line[prop]}" `
+ }
+ }
+
+ return attrs;
+ }
+}
+
+/**
+* HTML API: If current script has container(s) specified, initialise Termynal.
+*/
+if (document.currentScript.hasAttribute('data-termynal-container')) {
+ const containers = document.currentScript.getAttribute('data-termynal-container');
+ containers.split('|')
+ .forEach(container => new Termynal(container))
+}
diff --git a/docs/en/docs/project-generation.md b/docs/en/docs/project-generation.md
new file mode 100644
index 0000000000000..2cc2159fc8126
--- /dev/null
+++ b/docs/en/docs/project-generation.md
@@ -0,0 +1,71 @@
+# Project Generation - Template
+
+You can use a project generator to get started, as it includes a lot of the initial set up, security, database and first API endpoints already done for you.
+
+A project generator will always have a very opinionated setup that you should update and adapt for your own needs, but it might be a good starting point for your project.
+
+## Full Stack FastAPI PostgreSQL
+
+GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql
+
+### Full Stack FastAPI PostgreSQL - Features
+
+* Full **Docker** integration (Docker based).
+* Docker Swarm Mode deployment.
+* **Docker Compose** integration and optimization for local development.
+* **Production ready** Python web server using Uvicorn and Gunicorn.
+* Python **FastAPI** backend:
+ * **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic).
+ * **Intuitive**: Great editor support. Completion everywhere. Less time debugging.
+ * **Easy**: Designed to be easy to use and learn. Less time reading docs.
+ * **Short**: Minimize code duplication. Multiple features from each parameter declaration.
+ * **Robust**: Get production-ready code. With automatic interactive documentation.
+ * **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI and JSON Schema.
+ * **Many other features** including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc.
+* **Secure password** hashing by default.
+* **JWT token** authentication.
+* **SQLAlchemy** models (independent of Flask extensions, so they can be used with Celery workers directly).
+* Basic starting models for users (modify and remove as you need).
+* **Alembic** migrations.
+* **CORS** (Cross Origin Resource Sharing).
+* **Celery** worker that can import and use models and code from the rest of the backend selectively.
+* REST backend tests based on **Pytest**, integrated with Docker, so you can test the full API interaction, independent on the database. As it runs in Docker, it can build a new data store from scratch each time (so you can use ElasticSearch, MongoDB, CouchDB, or whatever you want, and just test that the API works).
+* Easy Python integration with **Jupyter Kernels** for remote or in-Docker development with extensions like Atom Hydrogen or Visual Studio Code Jupyter.
+* **Vue** frontend:
+ * Generated with Vue CLI.
+ * **JWT Authentication** handling.
+ * Login view.
+ * After login, main dashboard view.
+ * Main dashboard with user creation and edition.
+ * Self user edition.
+ * **Vuex**.
+ * **Vue-router**.
+ * **Vuetify** for beautiful material design components.
+ * **TypeScript**.
+ * Docker server based on **Nginx** (configured to play nicely with Vue-router).
+ * Docker multi-stage building, so you don't need to save or commit compiled code.
+ * Frontend tests ran at build time (can be disabled too).
+ * Made as modular as possible, so it works out of the box, but you can re-generate with Vue CLI or create it as you need, and re-use what you want.
+* **PGAdmin** for PostgreSQL database, you can modify it to use PHPMyAdmin and MySQL easily.
+* **Flower** for Celery jobs monitoring.
+* Load balancing between frontend and backend with **Traefik**, so you can have both under the same domain, separated by path, but served by different containers.
+* Traefik integration, including Let's Encrypt **HTTPS** certificates automatic generation.
+* GitLab **CI** (continuous integration), including frontend and backend testing.
+
+## Full Stack FastAPI Couchbase
+
+GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase
+
+⚠️ **WARNING** ⚠️
+
+If you are starting a new project from scratch, check the alternatives here.
+
+For example, the project generator Full Stack FastAPI PostgreSQL might be a better alternative, as it is actively maintained and used. And it includes all the new features and improvements.
+
+You are still free to use the Couchbase-based generator if you want to, it should probably still work fine, and if you already have a project generated with it that's fine as well (and you probably already updated it to suit your needs).
+
+You can read more about it in the docs for the repo.
+
+## Full Stack FastAPI MongoDB
+
+...might come later, depending on my time availability and other factors. 😅 🎉
diff --git a/docs/python-types.md b/docs/en/docs/python-types.md
similarity index 91%
rename from docs/python-types.md
rename to docs/en/docs/python-types.md
index 5d25e18165978..46420362c8de4 100644
--- a/docs/python-types.md
+++ b/docs/en/docs/python-types.md
@@ -1,3 +1,5 @@
+# Python Types Intro
+
**Python 3.6+** has support for optional "type hints".
These **"type hints"** are a new syntax (since Python 3.6+) that allow declaring the type of a variable.
@@ -18,7 +20,7 @@ But even if you never use **FastAPI**, you would benefit from learning a bit abo
Let's start with a simple example:
```Python
-{!./src/python_types/tutorial001.py!}
+{!../../../docs_src/python_types/tutorial001.py!}
```
Calling this program outputs:
@@ -34,7 +36,7 @@ The function does the following:
* Concatenates them with a space in the middle.
```Python hl_lines="2"
-{!./src/python_types/tutorial001.py!}
+{!../../../docs_src/python_types/tutorial001.py!}
```
### Edit it
@@ -78,7 +80,7 @@ That's it.
Those are the "type hints":
```Python hl_lines="1"
-{!./src/python_types/tutorial002.py!}
+{!../../../docs_src/python_types/tutorial002.py!}
```
That is not the same as declaring default values like would be with:
@@ -108,7 +110,7 @@ With that, you can scroll, seeing the options, until you find the one that "ring
Check this function, it already has type hints:
```Python hl_lines="1"
-{!./src/python_types/tutorial003.py!}
+{!../../../docs_src/python_types/tutorial003.py!}
```
Because the editor knows the types of the variables, you don't only get completion, you also get error checks:
@@ -118,7 +120,7 @@ Because the editor knows the types of the variables, you don't only get completi
Now you know that you have to fix it, convert `age` to a string with `str(age)`:
```Python hl_lines="2"
-{!./src/python_types/tutorial004.py!}
+{!../../../docs_src/python_types/tutorial004.py!}
```
## Declaring types
@@ -139,7 +141,7 @@ You can use, for example:
* `bytes`
```Python hl_lines="1"
-{!./src/python_types/tutorial005.py!}
+{!../../../docs_src/python_types/tutorial005.py!}
```
### Types with subtypes
@@ -157,7 +159,7 @@ For example, let's define a variable to be a `list` of `str`.
From `typing`, import `List` (with a capital `L`):
```Python hl_lines="1"
-{!./src/python_types/tutorial006.py!}
+{!../../../docs_src/python_types/tutorial006.py!}
```
Declare the variable, with the same colon (`:`) syntax.
@@ -167,7 +169,7 @@ As the type, put the `List`.
As the list is a type that takes a "subtype", you put the subtype in square brackets:
```Python hl_lines="4"
-{!./src/python_types/tutorial006.py!}
+{!../../../docs_src/python_types/tutorial006.py!}
```
That means: "the variable `items` is a `list`, and each of the items in this list is a `str`".
@@ -187,12 +189,12 @@ And still, the editor knows it is a `str`, and provides support for that.
You would do the same to declare `tuple`s and `set`s:
```Python hl_lines="1 4"
-{!./src/python_types/tutorial007.py!}
+{!../../../docs_src/python_types/tutorial007.py!}
```
This means:
-* The variable `items_t` is a `tuple`, and each of its items is an `int`.
+* The variable `items_t` is a `tuple` with 3 items, an `int`, another `int`, and a `str`.
* The variable `items_s` is a `set`, and each of its items is of type `bytes`.
#### Dicts
@@ -204,7 +206,7 @@ The first subtype is for the keys of the `dict`.
The second subtype is for the values of the `dict`:
```Python hl_lines="1 4"
-{!./src/python_types/tutorial008.py!}
+{!../../../docs_src/python_types/tutorial008.py!}
```
This means:
@@ -220,13 +222,13 @@ You can also declare a class as the type of a variable.
Let's say you have a class `Person`, with a name:
```Python hl_lines="1 2 3"
-{!./src/python_types/tutorial009.py!}
+{!../../../docs_src/python_types/tutorial009.py!}
```
Then you can declare a variable to be of type `Person`:
```Python hl_lines="6"
-{!./src/python_types/tutorial009.py!}
+{!../../../docs_src/python_types/tutorial009.py!}
```
And then, again, you get all the editor support:
@@ -248,7 +250,7 @@ And you get all the editor support with that resulting object.
Taken from the official Pydantic docs:
```Python
-{!./src/python_types/tutorial010.py!}
+{!../../../docs_src/python_types/tutorial010.py!}
```
!!! info
diff --git a/docs/release-notes.md b/docs/en/docs/release-notes.md
similarity index 80%
rename from docs/release-notes.md
rename to docs/en/docs/release-notes.md
index 49095f66e03f4..9b26f2c534c07 100644
--- a/docs/release-notes.md
+++ b/docs/en/docs/release-notes.md
@@ -1,5 +1,129 @@
+# Release Notes
+
## Latest changes
+## 0.56.0
+
+* Add support for ASGI `root_path`:
+ * Use `root_path` internally for mounted applications, so that OpenAPI and the docs UI works automatically without extra configurations and parameters.
+ * Add new `root_path` parameter for `FastAPI` applications to provide it in cases where it can be set with the command line (e.g. for Uvicorn and Hypercorn, with the parameter `--root-path`).
+ * Deprecate `openapi_prefix` parameter in favor of the new `root_path` parameter.
+ * Add new/updated docs for [Sub Applications - Mounts](https://fastapi.tiangolo.com/advanced/sub-applications/), without `openapi_prefix` (as it is now handled automatically).
+ * Add new/updated docs for [Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/), including how to setup a local testing proxy with Traefik and using `root_path`.
+ * Update docs for [Extending OpenAPI](https://fastapi.tiangolo.com/advanced/extending-openapi/) with the new `openapi_prefix` parameter passed (internally generated from `root_path`).
+ * Original PR [#1199](https://github.com/tiangolo/fastapi/pull/1199) by [@iksteen](https://github.com/iksteen).
+* Update new issue templates and docs: [Help FastAPI - Get Help](https://fastapi.tiangolo.com/help-fastapi/). PR [#1531](https://github.com/tiangolo/fastapi/pull/1531).
+* Update GitHub action issue-manager. PR [#1520](https://github.com/tiangolo/fastapi/pull/1520).
+* Add new links:
+ * **English articles**:
+ * [Real-time Notifications with Python and Postgres](https://wuilly.com/2019/10/real-time-notifications-with-python-and-postgres/) by [Guillermo Cruz](https://wuilly.com/).
+ * [Microservice in Python using FastAPI](https://dev.to/paurakhsharma/microservice-in-python-using-fastapi-24cc) by [Paurakh Sharma Humagain](https://twitter.com/PaurakhSharma).
+ * [Build simple API service with Python FastAPI — Part 1](https://dev.to/cuongld2/build-simple-api-service-with-python-fastapi-part-1-581o) by [cuongld2](https://dev.to/cuongld2).
+ * [FastAPI + Zeit.co = 🚀](https://paulsec.github.io/posts/fastapi_plus_zeit_serverless_fu/) by [Paul Sec](https://twitter.com/PaulWebSec).
+ * [Build a web API from scratch with FastAPI - the workshop](https://dev.to/tiangolo/build-a-web-api-from-scratch-with-fastapi-the-workshop-2ehe) by [Sebastián Ramírez (tiangolo)](https://twitter.com/tiangolo).
+ * [Build a Secure Twilio Webhook with Python and FastAPI](https://www.twilio.com/blog/build-secure-twilio-webhook-python-fastapi) by [Twilio](https://www.twilio.com).
+ * [Using FastAPI with Django](https://www.stavros.io/posts/fastapi-with-django/) by [Stavros Korokithakis](https://twitter.com/Stavros).
+ * [Introducing Dispatch](https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072) by [Netflix](https://netflixtechblog.com/).
+ * **Podcasts**:
+ * [Build The Next Generation Of Python Web Applications With FastAPI - Episode 259 - interview to Sebastían Ramírez (tiangolo)](https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/) by [Podcast.`__init__`](https://www.pythonpodcast.com/).
+ * **Talks**:
+ * [PyConBY 2020: Serve ML models easily with FastAPI](https://www.youtube.com/watch?v=z9K5pwb0rt8) by [Sebastián Ramírez (tiangolo)](https://twitter.com/tiangolo).
+ * [[VIRTUAL] Py.Amsterdam's flying Software Circus: Intro to FastAPI](https://www.youtube.com/watch?v=PnpTY1f4k2U) by [Sebastián Ramírez (tiangolo)](https://twitter.com/tiangolo).
+ * PR [#1467](https://github.com/tiangolo/fastapi/pull/1467).
+* Add translation to Chinese for [Python Types Intro - Python 类型提示简介](https://fastapi.tiangolo.com/zh/python-types/). PR [#1197](https://github.com/tiangolo/fastapi/pull/1197) by [@waynerv](https://github.com/waynerv).
+
+## 0.55.1
+
+* Fix handling of enums with their own schema in path parameters. To support [samuelcolvin/pydantic#1432](https://github.com/samuelcolvin/pydantic/pull/1432) in FastAPI. PR [#1463](https://github.com/tiangolo/fastapi/pull/1463).
+
+## 0.55.0
+
+* Allow enums to allow them to have their own schemas in OpenAPI. To support [samuelcolvin/pydantic#1432](https://github.com/samuelcolvin/pydantic/pull/1432) in FastAPI. PR [#1461](https://github.com/tiangolo/fastapi/pull/1461).
+* Add links for funding through [GitHub sponsors](https://github.com/sponsors/tiangolo). PR [#1425](https://github.com/tiangolo/fastapi/pull/1425).
+* Update issue template for for questions. PR [#1344](https://github.com/tiangolo/fastapi/pull/1344) by [@retnikt](https://github.com/retnikt).
+* Update warning about storing passwords in docs. PR [#1336](https://github.com/tiangolo/fastapi/pull/1336) by [@skorokithakis](https://github.com/skorokithakis).
+* Fix typo. PR [#1326](https://github.com/tiangolo/fastapi/pull/1326) by [@chenl](https://github.com/chenl).
+* Add translation to Portuguese for [Alternatives, Inspiration and Comparisons - Alternativas, Inspiração e Comparações](https://fastapi.tiangolo.com/pt/alternatives/). PR [#1325](https://github.com/tiangolo/fastapi/pull/1325) by [@Serrones](https://github.com/Serrones).
+* Fix 2 typos in docs. PR [#1324](https://github.com/tiangolo/fastapi/pull/1324) by [@waynerv](https://github.com/waynerv).
+* Update CORS docs, fix correct default of `max_age=600`. PR [#1301](https://github.com/tiangolo/fastapi/pull/1301) by [@derekbekoe](https://github.com/derekbekoe).
+* Add translation of [main page to Portuguese](https://fastapi.tiangolo.com/pt/). PR [#1300](https://github.com/tiangolo/fastapi/pull/1300) by [@Serrones](https://github.com/Serrones).
+* Re-word and clarify docs for extra info in fields. PR [#1299](https://github.com/tiangolo/fastapi/pull/1299) by [@chris-allnutt](https://github.com/chris-allnutt).
+* Make sure the `*` in short features in the docs is consistent (after `.`) in all languages. PR [#1424](https://github.com/tiangolo/fastapi/pull/1424).
+* Update order of execution for `get_db` in SQLAlchemy tutorial. PR [#1293](https://github.com/tiangolo/fastapi/pull/1293) by [@bcb](https://github.com/bcb).
+* Fix typos in Async docs. PR [#1423](https://github.com/tiangolo/fastapi/pull/1423).
+
+## 0.54.2
+
+* Add translation to Spanish for [Concurrency and async / await - Concurrencia y async / await](https://fastapi.tiangolo.com/es/async/). PR [#1290](https://github.com/tiangolo/fastapi/pull/1290) by [@alvaropernas](https://github.com/alvaropernas).
+* Remove obsolete vote link. PR [#1289](https://github.com/tiangolo/fastapi/pull/1289) by [@donhui](https://github.com/donhui).
+* Allow disabling docs UIs by just disabling OpenAPI with `openapi_url=None`. New example in docs: [Advanced: Conditional OpenAPI](https://fastapi.tiangolo.com/advanced/conditional-openapi/). PR [#1421](https://github.com/tiangolo/fastapi/pull/1421).
+* Add translation to Portuguese for [Benchmarks - Comparações](https://fastapi.tiangolo.com/pt/benchmarks/). PR [#1274](https://github.com/tiangolo/fastapi/pull/1274) by [@Serrones](https://github.com/Serrones).
+* Add translation to Portuguese for [Tutorial - User Guide - Intro - Tutorial - Guia de Usuário - Introdução](https://fastapi.tiangolo.com/pt/tutorial/). PR [#1259](https://github.com/tiangolo/fastapi/pull/1259) by [@marcosmmb](https://github.com/marcosmmb).
+* Allow using Unicode in MkDocs for translations. PR [#1419](https://github.com/tiangolo/fastapi/pull/1419).
+* Add translation to Spanish for [Advanced User Guide - Intro - Guía de Usuario Avanzada - Introducción](https://fastapi.tiangolo.com/es/advanced/). PR [#1250](https://github.com/tiangolo/fastapi/pull/1250) by [@jfunez](https://github.com/jfunez).
+* Add translation to Portuguese for [History, Design and Future - História, Design e Futuro](https://fastapi.tiangolo.com/pt/history-design-future/). PR [#1249](https://github.com/tiangolo/fastapi/pull/1249) by [@marcosmmb](https://github.com/marcosmmb).
+* Add translation to Portuguese for [Features - Recursos](https://fastapi.tiangolo.com/pt/features/). PR [#1248](https://github.com/tiangolo/fastapi/pull/1248) by [@marcosmmb](https://github.com/marcosmmb).
+* Add translation to Spanish for [Tutorial - User Guide - Intro - Tutorial - Guía de Usuario - Introducción](https://fastapi.tiangolo.com/es/tutorial/). PR [#1244](https://github.com/tiangolo/fastapi/pull/1244) by [@MartinEliasQ](https://github.com/MartinEliasQ).
+* Add translation to Chinese for [Deployment - 部署](https://fastapi.tiangolo.com/zh/deployment/). PR [#1203](https://github.com/tiangolo/fastapi/pull/1203) by [@RunningIkkyu](https://github.com/RunningIkkyu).
+* Add translation to Chinese for [Tutorial - User Guide - Intro - 教程 - 用户指南 - 简介](https://fastapi.tiangolo.com/zh/tutorial/). PR [#1202](https://github.com/tiangolo/fastapi/pull/1202) by [@waynerv](https://github.com/waynerv).
+* Add translation to Chinese for [Features - 特性](https://fastapi.tiangolo.com/zh/features/). PR [#1192](https://github.com/tiangolo/fastapi/pull/1192) by [@Dustyposa](https://github.com/Dustyposa).
+* Add translation for [main page to Chinese](https://fastapi.tiangolo.com/zh/) PR [#1191](https://github.com/tiangolo/fastapi/pull/1191) by [@waynerv](https://github.com/waynerv).
+* Update docs for project generation. PR [#1287](https://github.com/tiangolo/fastapi/pull/1287).
+* Add Spanish translation for [Introducción a los Tipos de Python (Python Types Intro)](https://fastapi.tiangolo.com/es/python-types/). PR [#1237](https://github.com/tiangolo/fastapi/pull/1237) by [@mariacamilagl](https://github.com/mariacamilagl).
+* Add Spanish translation for [Características (Features)](https://fastapi.tiangolo.com/es/features/). PR [#1220](https://github.com/tiangolo/fastapi/pull/1220) by [@mariacamilagl](https://github.com/mariacamilagl).
+
+## 0.54.1
+
+* Update database test setup. PR [#1226](https://github.com/tiangolo/fastapi/pull/1226).
+* Improve test debugging by showing response text in failing tests. PR [#1222](https://github.com/tiangolo/fastapi/pull/1222) by [@samuelcolvin](https://github.com/samuelcolvin).
+
+## 0.54.0
+
+* Fix grammatical mistakes in async docs. PR [#1188](https://github.com/tiangolo/fastapi/pull/1188) by [@mickeypash](https://github.com/mickeypash).
+* Add support for `response_model_exclude_defaults` and `response_model_exclude_none`:
+ * Deprecate the parameter `include_none` in `jsonable_encoder` and add the inverted `exclude_none`, to keep in sync with Pydantic.
+ * PR [#1166](https://github.com/tiangolo/fastapi/pull/1166) by [@voegtlel](https://github.com/voegtlel).
+* Add example about [Testing a Database](https://fastapi.tiangolo.com/advanced/testing-database/). Initial PR [#1144](https://github.com/tiangolo/fastapi/pull/1144) by [@duganchen](https://github.com/duganchen).
+* Update docs for [Development - Contributing: Translations](https://fastapi.tiangolo.com/contributing/#translations) including note about reviewing translation PRs. [#1215](https://github.com/tiangolo/fastapi/pull/1215).
+* Update log style in README.md for GitHub Markdown compatibility. PR [#1200](https://github.com/tiangolo/fastapi/pull/1200) by [#geekgao](https://github.com/geekgao).
+* Add Python venv `env` to `.gitignore`. PR [#1212](https://github.com/tiangolo/fastapi/pull/1212) by [@cassiobotaro](https://github.com/cassiobotaro).
+* Start Portuguese translations. PR [#1210](https://github.com/tiangolo/fastapi/pull/1210) by [@cassiobotaro](https://github.com/cassiobotaro).
+* Update docs for Pydantic's `Settings` using a dependency with `@lru_cache()`. PR [#1214](https://github.com/tiangolo/fastapi/pull/1214).
+* Add first translation to Spanish [FastAPI](https://fastapi.tiangolo.com/es/). PR [#1201](https://github.com/tiangolo/fastapi/pull/1201) by [@mariacamilagl](https://github.com/mariacamilagl).
+* Add docs about [Settings and Environment Variables](https://fastapi.tiangolo.com/advanced/settings/). Initial PR [1118](https://github.com/tiangolo/fastapi/pull/1118) by [@alexmitelman](https://github.com/alexmitelman).
+
+## 0.53.2
+
+* Fix automatic embedding of body fields for dependencies and sub-dependencies. Original PR [#1079](https://github.com/tiangolo/fastapi/pull/1079) by [@Toad2186](https://github.com/Toad2186).
+* Fix dependency overrides in WebSocket testing. PR [#1122](https://github.com/tiangolo/fastapi/pull/1122) by [@amitlissack](https://github.com/amitlissack).
+* Fix docs script to ensure languages are always sorted. PR [#1189](https://github.com/tiangolo/fastapi/pull/1189).
+* Start translations for Chinese. PR [#1187](https://github.com/tiangolo/fastapi/pull/1187) by [@RunningIkkyu](https://github.com/RunningIkkyu).
+* Add docs for [Schema Extra - Example](https://fastapi.tiangolo.com/tutorial/schema-extra-example/). PR [#1185](https://github.com/tiangolo/fastapi/pull/1185).
+
+## 0.53.1
+
+* Fix included example after translations refactor. PR [#1182](https://github.com/tiangolo/fastapi/pull/1182).
+* Add docs example for `example` in `Field`. Docs at [Body - Fields: JSON Schema extras](https://fastapi.tiangolo.com/tutorial/body-fields/#json-schema-extras). PR [#1106](https://github.com/tiangolo/fastapi/pull/1106) by [@JohnPaton](https://github.com/JohnPaton).
+* Fix using recursive models in `response_model`. PR [#1164](https://github.com/tiangolo/fastapi/pull/1164) by [@voegtlel](https://github.com/voegtlel).
+* Add docs for [Pycharm Debugging](https://fastapi.tiangolo.com/tutorial/debugging/). PR [#1096](https://github.com/tiangolo/fastapi/pull/1096) by [@youngquan](https://github.com/youngquan).
+* Fix typo in docs. PR [#1148](https://github.com/tiangolo/fastapi/pull/1148) by [@PLNech](https://github.com/PLNech).
+* Update Windows development environment instructions. PR [#1179](https://github.com/tiangolo/fastapi/pull/1179).
+
+## 0.53.0
+
+* Update test coverage badge. PR [#1175](https://github.com/tiangolo/fastapi/pull/1175).
+* Add `orjson` to `pip install fastapi[all]`. PR [#1161](https://github.com/tiangolo/fastapi/pull/1161) by [@michael0liver](https://github.com/michael0liver).
+* Fix included example for `GZipMiddleware`. PR [#1138](https://github.com/tiangolo/fastapi/pull/1138) by [@arimbr](https://github.com/arimbr).
+* Fix class name in docstring for `OAuth2PasswordRequestFormStrict`. PR [#1126](https://github.com/tiangolo/fastapi/pull/1126) by [@adg-mh](https://github.com/adg-mh).
+* Clarify function name in example in docs. PR [#1121](https://github.com/tiangolo/fastapi/pull/1121) by [@tmsick](https://github.com/tmsick).
+* Add external link [Apache Kafka producer and consumer with FastAPI and aiokafka](https://iwpnd.pw/articles/2020-03/apache-kafka-fastapi-geostream) to docs. PR [#1112](https://github.com/tiangolo/fastapi/pull/1112) by [@iwpnd](https://github.com/iwpnd).
+* Fix serialization when using `by_alias` or `exclude_unset` and returning data with Pydantic models. PR [#1074](https://github.com/tiangolo/fastapi/pull/1074) by [@juhovh-aiven](https://github.com/juhovh-aiven).
+* Add Gitter chat to docs. PR [#1061](https://github.com/tiangolo/fastapi/pull/1061) by [@aakashnand](https://github.com/aakashnand).
+* Update and simplify translations docs. PR [#1171](https://github.com/tiangolo/fastapi/pull/1171).
+* Update development of FastAPI docs, set address to `127.0.0.1` to improve Windows support. PR [#1169](https://github.com/tiangolo/fastapi/pull/1169) by [@mariacamilagl](https://github.com/mariacamilagl).
+* Add support for docs translations. New docs: [Development - Contributing: Docs: Translations](https://fastapi.tiangolo.com/contributing/#translations). PR [#1168](https://github.com/tiangolo/fastapi/pull/1168).
+* Update terminal styles in docs and add note about [**Typer**, the FastAPI of CLIs](https://typer.tiangolo.com/). PR [#1139](https://github.com/tiangolo/fastapi/pull/1139).
+
## 0.52.0
* Add new high-performance JSON response class using `orjson`. New docs: [Custom Response - HTML, Stream, File, others: `ORJSONResponse`](https://fastapi.tiangolo.com/advanced/custom-response/#use-orjsonresponse). PR [#1065](https://github.com/tiangolo/fastapi/pull/1065).
diff --git a/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md
similarity index 95%
rename from docs/tutorial/background-tasks.md
rename to docs/en/docs/tutorial/background-tasks.md
index 15b92e8f5ae0f..3771eff7129a2 100644
--- a/docs/tutorial/background-tasks.md
+++ b/docs/en/docs/tutorial/background-tasks.md
@@ -1,3 +1,5 @@
+# Background Tasks
+
You can define background tasks to be run *after* returning a response.
This is useful for operations that need to happen after a request, but that the client doesn't really have to be waiting for the operation to complete before receiving his response.
@@ -14,7 +16,7 @@ This includes, for example:
First, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`:
```Python hl_lines="1 13"
-{!./src/background_tasks/tutorial001.py!}
+{!../../../docs_src/background_tasks/tutorial001.py!}
```
**FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter.
@@ -32,7 +34,7 @@ In this case, the task function will write to a file (simulating sending an emai
And as the write operation doesn't use `async` and `await`, we define the function with normal `def`:
```Python hl_lines="6 7 8 9"
-{!./src/background_tasks/tutorial001.py!}
+{!../../../docs_src/background_tasks/tutorial001.py!}
```
## Add the background task
@@ -40,7 +42,7 @@ And as the write operation doesn't use `async` and `await`, we define the functi
Inside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`:
```Python hl_lines="14"
-{!./src/background_tasks/tutorial001.py!}
+{!../../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` receives as arguments:
@@ -56,7 +58,7 @@ Using `BackgroundTasks` also works with the dependency injection system, you can
**FastAPI** knows what to do in each case and how to re-use the same object, so that all the background tasks are merged together and are run in the background afterwards:
```Python hl_lines="11 14 20 23"
-{!./src/background_tasks/tutorial002.py!}
+{!../../../docs_src/background_tasks/tutorial002.py!}
```
In this example, the messages will be written to the `log.txt` file *after* the response is sent.
diff --git a/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md
similarity index 93%
rename from docs/tutorial/bigger-applications.md
rename to docs/en/docs/tutorial/bigger-applications.md
index 6ee298337fe4f..0d3be0f16538c 100644
--- a/docs/tutorial/bigger-applications.md
+++ b/docs/en/docs/tutorial/bigger-applications.md
@@ -1,3 +1,5 @@
+# Bigger Applications - Multiple Files
+
If you are building an application or a web API, it's rarely the case that you can put everything on a single file.
**FastAPI** provides a convenience tool to structure your application while keeping all the flexibility.
@@ -59,7 +61,7 @@ You can create the *path operations* for that module using `APIRouter`.
You import it and create an "instance" the same way you would with the class `FastAPI`:
```Python hl_lines="1 3"
-{!./src/bigger_applications/app/routers/users.py!}
+{!../../../docs_src/bigger_applications/app/routers/users.py!}
```
### *Path operations* with `APIRouter`
@@ -69,7 +71,7 @@ And then you use it to declare your *path operations*.
Use it the same way you would use the `FastAPI` class:
```Python hl_lines="6 11 16"
-{!./src/bigger_applications/app/routers/users.py!}
+{!../../../docs_src/bigger_applications/app/routers/users.py!}
```
You can think of `APIRouter` as a "mini `FastAPI`" class.
@@ -99,7 +101,7 @@ But let's say that this time we are more lazy.
And we don't want to have to explicitly type `/items/` and `tags=["items"]` in every *path operation* (we will be able to do it later):
```Python hl_lines="6 11"
-{!./src/bigger_applications/app/routers/items.py!}
+{!../../../docs_src/bigger_applications/app/routers/items.py!}
```
### Add some custom `tags`, `responses`, and `dependencies`
@@ -109,7 +111,7 @@ We are not adding the prefix `/items/` nor the `tags=["items"]` to add them late
But we can add custom `tags` and `responses` that will be applied to a specific *path operation*:
```Python hl_lines="18 19"
-{!./src/bigger_applications/app/routers/items.py!}
+{!../../../docs_src/bigger_applications/app/routers/items.py!}
```
## The main `FastAPI`
@@ -125,7 +127,7 @@ This will be the main file in your application that ties everything together.
You import and create a `FastAPI` class as normally:
```Python hl_lines="1 5"
-{!./src/bigger_applications/app/main.py!}
+{!../../../docs_src/bigger_applications/app/main.py!}
```
### Import the `APIRouter`
@@ -135,7 +137,7 @@ But this time we are not adding *path operations* directly with the `FastAPI` `a
We import the other submodules that have `APIRouter`s:
```Python hl_lines="3"
-{!./src/bigger_applications/app/main.py!}
+{!../../../docs_src/bigger_applications/app/main.py!}
```
As the file `app/routers/items.py` is part of the same Python package, we can import it using "dot notation".
@@ -187,7 +189,7 @@ The `router` from `users` would overwrite the one from `items` and we wouldn't b
So, to be able to use both of them in the same file, we import the submodules directly:
```Python hl_lines="3"
-{!./src/bigger_applications/app/main.py!}
+{!../../../docs_src/bigger_applications/app/main.py!}
```
### Include an `APIRouter`
@@ -195,7 +197,7 @@ So, to be able to use both of them in the same file, we import the submodules di
Now, let's include the `router` from the submodule `users`:
```Python hl_lines="13"
-{!./src/bigger_applications/app/main.py!}
+{!../../../docs_src/bigger_applications/app/main.py!}
```
!!! info
@@ -244,7 +246,7 @@ And we can add predefined `responses` that will be included in all the *path ope
And we can add a list of `dependencies` that will be added to all the *path operations* in the router and will be executed/solved for each request made to them. Note that, much like dependencies in *path operation decorators*, no value will be passed to your *path operation function*.
```Python hl_lines="8 9 10 14 15 16 17 18 19 20"
-{!./src/bigger_applications/app/main.py!}
+{!../../../docs_src/bigger_applications/app/main.py!}
```
The end result is that the item paths are now:
@@ -292,10 +294,16 @@ The end result is that the item paths are now:
Now, run `uvicorn`, using the module `app.main` and the variable `app`:
-```bash
-uvicorn app.main:app --reload
+
+
+```console
+$ uvicorn app.main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
+
+
And open the docs at http://127.0.0.1:8000/docs.
You will see the automatic API docs, including the paths from all the submodules, using the correct paths (and prefixes) and the correct tags:
diff --git a/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md
similarity index 62%
rename from docs/tutorial/body-fields.md
rename to docs/en/docs/tutorial/body-fields.md
index f54ed4eb83f38..91e6b1a101a8d 100644
--- a/docs/tutorial/body-fields.md
+++ b/docs/en/docs/tutorial/body-fields.md
@@ -1,3 +1,5 @@
+# Body - Fields
+
The same way you can declare additional validation and metadata in *path operation function* parameters with `Query`, `Path` and `Body`, you can declare validation and metadata inside of Pydantic models using Pydantic's `Field`.
## Import `Field`
@@ -5,7 +7,7 @@ The same way you can declare additional validation and metadata in *path operati
First, you have to import it:
```Python hl_lines="2"
-{!./src/body_fields/tutorial001.py!}
+{!../../../docs_src/body_fields/tutorial001.py!}
```
!!! warning
@@ -16,7 +18,7 @@ First, you have to import it:
You can then use `Field` with model attributes:
```Python hl_lines="9 10"
-{!./src/body_fields/tutorial001.py!}
+{!../../../docs_src/body_fields/tutorial001.py!}
```
`Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc.
@@ -33,26 +35,11 @@ You can then use `Field` with model attributes:
!!! tip
Notice how each model's attribute with a type, default value and `Field` has the same structure as a *path operation function's* parameter, with `Field` instead of `Path`, `Query` and `Body`.
-## JSON Schema extras
-
-In `Field`, `Path`, `Query`, `Body` and others you'll see later, you can declare extra parameters apart from those described before.
-
-Those parameters will be added as-is to the output JSON Schema.
-
-If you know JSON Schema and want to add extra information apart from what we have discussed here, you can pass that as extra keyword arguments.
-
-!!! warning
- Have in mind that extra parameters passed won't add any validation, only annotation, for documentation purposes.
-
-For example, you can use that functionality to pass a JSON Schema example field to a body request JSON Schema:
-
-```Python hl_lines="20 21 22 23 24 25"
-{!./src/body_fields/tutorial002.py!}
-```
+## Add extra information
-And it would look in the `/docs` like this:
+You can declare extra information in `Field`, `Query`, `Body`, etc. And it will be included in the generated JSON Schema.
-
+You will learn more about adding extra information later in the docs, when learning to declare examples.
## Recap
diff --git a/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md
similarity index 93%
rename from docs/tutorial/body-multiple-params.md
rename to docs/en/docs/tutorial/body-multiple-params.md
index 5009c21bfdb22..6d5e6e39deed3 100644
--- a/docs/tutorial/body-multiple-params.md
+++ b/docs/en/docs/tutorial/body-multiple-params.md
@@ -1,3 +1,5 @@
+# Body - Multiple Parameters
+
Now that we have seen how to use `Path` and `Query`, let's see more advanced uses of request body declarations.
## Mix `Path`, `Query` and body parameters
@@ -7,7 +9,7 @@ First, of course, you can mix `Path`, `Query` and request body parameter declara
And you can also declare body parameters as optional, by setting the default to `None`:
```Python hl_lines="17 18 19"
-{!./src/body_multiple_params/tutorial001.py!}
+{!../../../docs_src/body_multiple_params/tutorial001.py!}
```
!!! note
@@ -29,7 +31,7 @@ In the previous example, the *path operations* would expect a JSON body with the
But you can also declare multiple body parameters, e.g. `item` and `user`:
```Python hl_lines="20"
-{!./src/body_multiple_params/tutorial002.py!}
+{!../../../docs_src/body_multiple_params/tutorial002.py!}
```
In this case, **FastAPI** will notice that there are more than one body parameters in the function (two parameters that are Pydantic models).
@@ -71,7 +73,7 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`:
```Python hl_lines="21"
-{!./src/body_multiple_params/tutorial003.py!}
+{!../../../docs_src/body_multiple_params/tutorial003.py!}
```
In this case, **FastAPI** will expect a body like:
@@ -108,7 +110,7 @@ q: str = None
as in:
```Python hl_lines="25"
-{!./src/body_multiple_params/tutorial004.py!}
+{!../../../docs_src/body_multiple_params/tutorial004.py!}
```
!!! info
@@ -130,7 +132,7 @@ item: Item = Body(..., embed=True)
as in:
```Python hl_lines="15"
-{!./src/body_multiple_params/tutorial005.py!}
+{!../../../docs_src/body_multiple_params/tutorial005.py!}
```
In this case **FastAPI** will expect a body like:
diff --git a/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md
similarity index 90%
rename from docs/tutorial/body-nested-models.md
rename to docs/en/docs/tutorial/body-nested-models.md
index d5c5c95756e55..993389c903c96 100644
--- a/docs/tutorial/body-nested-models.md
+++ b/docs/en/docs/tutorial/body-nested-models.md
@@ -1,3 +1,5 @@
+# Body - Nested Models
+
With **FastAPI**, you can define, validate, document, and use arbitrarily deeply nested models (thanks to Pydantic).
## List fields
@@ -5,7 +7,7 @@ With **FastAPI**, you can define, validate, document, and use arbitrarily deeply
You can define an attribute to be a subtype. For example, a Python `list`:
```Python hl_lines="12"
-{!./src/body_nested_models/tutorial001.py!}
+{!../../../docs_src/body_nested_models/tutorial001.py!}
```
This will make `tags` be a list of items. Although it doesn't declare the type of each of the items.
@@ -19,7 +21,7 @@ But Python has a specific way to declare lists with subtypes:
First, import `List` from standard Python's `typing` module:
```Python hl_lines="1"
-{!./src/body_nested_models/tutorial002.py!}
+{!../../../docs_src/body_nested_models/tutorial002.py!}
```
### Declare a `List` with a subtype
@@ -42,7 +44,7 @@ Use that same standard syntax for model attributes with subtypes.
So, in our example, we can make `tags` be specifically a "list of strings":
```Python hl_lines="14"
-{!./src/body_nested_models/tutorial002.py!}
+{!../../../docs_src/body_nested_models/tutorial002.py!}
```
## Set types
@@ -54,7 +56,7 @@ And Python has a special data type for sets of unique items, the `set`.
Then we can import `Set` and declare `tags` as a `set` of `str`:
```Python hl_lines="1 14"
-{!./src/body_nested_models/tutorial003.py!}
+{!../../../docs_src/body_nested_models/tutorial003.py!}
```
With this, even if you receive a request with duplicate data, it will be converted to a set of unique items.
@@ -78,7 +80,7 @@ All that, arbitrarily nested.
For example, we can define an `Image` model:
```Python hl_lines="9 10 11"
-{!./src/body_nested_models/tutorial004.py!}
+{!../../../docs_src/body_nested_models/tutorial004.py!}
```
### Use the submodel as a type
@@ -86,7 +88,7 @@ For example, we can define an `Image` model:
And then we can use it as the type of an attribute:
```Python hl_lines="20"
-{!./src/body_nested_models/tutorial004.py!}
+{!../../../docs_src/body_nested_models/tutorial004.py!}
```
This would mean that **FastAPI** would expect a body similar to:
@@ -121,7 +123,7 @@ To see all the options you have, checkout the docs for HTTP `PUT` operation.
@@ -5,7 +7,7 @@ To update an item you can use the CORS or "Cross-Origin Resource Sharing" refers to the situations when a frontend running in a browser has JavaScript code that communicates with a backend, and the backend is in a different "origin" than the frontend.
## Origin
@@ -45,7 +47,7 @@ You can also specify if your backend allows:
* Specific HTTP headers or all of them with the wildcard `"*"`.
```Python hl_lines="2 6 7 8 9 10 11 13 14 15 16 17 18 19"
-{!./src/cors/tutorial001.py!}
+{!../../../docs_src/cors/tutorial001.py!}
```
The default parameters used by the `CORSMiddleware` implementation are restrictive by default, so you'll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context.
@@ -58,7 +60,7 @@ The following arguments are supported:
* `allow_headers` - A list of HTTP request headers that should be supported for cross-origin requests. Defaults to `[]`. You can use `['*']` to allow all headers. The `Accept`, `Accept-Language`, `Content-Language` and `Content-Type` headers are always allowed for CORS requests.
* `allow_credentials` - Indicate that cookies should be supported for cross-origin requests. Defaults to `False`.
* `expose_headers` - Indicate any response headers that should be made accessible to the browser. Defaults to `[]`.
-* `max_age` - Sets a maximum time in seconds for browsers to cache CORS responses. Defaults to `60`.
+* `max_age` - Sets a maximum time in seconds for browsers to cache CORS responses. Defaults to `600`.
The middleware responds to two particular types of HTTP request...
diff --git a/docs/tutorial/debugging.md b/docs/en/docs/tutorial/debugging.md
similarity index 78%
rename from docs/tutorial/debugging.md
rename to docs/en/docs/tutorial/debugging.md
index 3800abd1b70ee..22893073bbe66 100644
--- a/docs/tutorial/debugging.md
+++ b/docs/en/docs/tutorial/debugging.md
@@ -1,3 +1,5 @@
+# Debugging
+
You can connect the debugger in your editor, for example with Visual Studio Code or PyCharm.
## Call `uvicorn`
@@ -5,17 +7,21 @@ You can connect the debugger in your editor, for example with Visual Studio Code
In your FastAPI application, import and run `uvicorn` directly:
```Python hl_lines="1 15"
-{!./src/debugging/tutorial001.py!}
+{!../../../docs_src/debugging/tutorial001.py!}
```
### About `__name__ == "__main__"`
The main purpose of the `__name__ == "__main__"` is to have some code that is executed when your file is called with:
-```bash
-python myapp.py
+
+
+```console
+$ python myapp.py
```
+
+
but is not called when another file imports it, like in:
```Python
@@ -28,10 +34,14 @@ Let's say your file is named `myapp.py`.
If you run it with:
-```bash
-python myapp.py
+
+
+```console
+$ python myapp.py
```
+
+
then the internal variable `__name__` in your file, created automatically by Python, will have as value the string `"__main__"`.
So, the section:
@@ -85,3 +95,18 @@ It will then start the server with your **FastAPI** code, stop at your breakpoin
Here's how it might look:
+
+---
+
+If you use Pycharm, you can:
+
+* Open the "Run" menu.
+* Select the option "Debug...".
+* Then a context menu shows up.
+* Select the file to debug (in this case, `main.py`).
+
+It will then start the server with your **FastAPI** code, stop at your breakpoints, etc.
+
+Here's how it might look:
+
+
diff --git a/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
similarity index 93%
rename from docs/tutorial/dependencies/classes-as-dependencies.md
rename to docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
index 674615410832a..b4d78af84e4b4 100644
--- a/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -1,3 +1,5 @@
+# Classes as Dependencies
+
Before diving deeper into the **Dependency Injection** system, let's upgrade the previous example.
## A `dict` from the previous example
@@ -5,7 +7,7 @@ Before diving deeper into the **Dependency Injection** system, let's upgrade the
In the previous example, we were returning a `dict` from our dependency ("dependable"):
```Python hl_lines="7"
-{!./src/dependencies/tutorial001.py!}
+{!../../../docs_src/dependencies/tutorial001.py!}
```
But then we get a `dict` in the parameter `commons` of the *path operation function*.
@@ -70,19 +72,19 @@ That also applies to callables with no parameters at all. The same as it would b
Then, we can change the dependency "dependable" `common_parameters` from above to the class `CommonQueryParameters`:
```Python hl_lines="9 10 11 12 13"
-{!./src/dependencies/tutorial002.py!}
+{!../../../docs_src/dependencies/tutorial002.py!}
```
Pay attention to the `__init__` method used to create the instance of the class:
```Python hl_lines="10"
-{!./src/dependencies/tutorial002.py!}
+{!../../../docs_src/dependencies/tutorial002.py!}
```
...it has the same parameters as our previous `common_parameters`:
```Python hl_lines="6"
-{!./src/dependencies/tutorial001.py!}
+{!../../../docs_src/dependencies/tutorial001.py!}
```
Those parameters are what **FastAPI** will use to "solve" the dependency.
@@ -102,7 +104,7 @@ Now you can declare your dependency using this class.
And as when **FastAPI** calls that class the value that will be passed as `commons` to your function will be an "instance" of the class, you can declare that parameter `commons` to be of type of the class, `CommonQueryParams`.
```Python hl_lines="17"
-{!./src/dependencies/tutorial002.py!}
+{!../../../docs_src/dependencies/tutorial002.py!}
```
## Type annotation vs `Depends`
@@ -142,7 +144,7 @@ commons = Depends(CommonQueryParams)
..as in:
```Python hl_lines="17"
-{!./src/dependencies/tutorial003.py!}
+{!../../../docs_src/dependencies/tutorial003.py!}
```
But declaring the type is encouraged as that way your editor will know what will be passed as the parameter `commons`, and then it can help you with code completion, type checks, etc:
@@ -178,7 +180,7 @@ So, you can declare the dependency as the type of the variable, and use `Depends
So, the same example would look like:
```Python hl_lines="17"
-{!./src/dependencies/tutorial004.py!}
+{!../../../docs_src/dependencies/tutorial004.py!}
```
...and **FastAPI** will know what to do.
diff --git a/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
similarity index 89%
rename from docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
rename to docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 7e774d5209ce1..64e03139c96ad 100644
--- a/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -1,3 +1,5 @@
+# Dependencies in path operation decorators
+
In some cases you don't really need the return value of a dependency inside your *path operation function*.
Or the dependency doesn't return a value.
@@ -13,7 +15,7 @@ The *path operation decorator* receives an optional argument `dependencies`.
It should be a `list` of `Depends()`:
```Python hl_lines="17"
-{!./src/dependencies/tutorial006.py!}
+{!../../../docs_src/dependencies/tutorial006.py!}
```
These dependencies will be executed/solved the same way normal dependencies. But their value (if they return any) won't be passed to your *path operation function*.
@@ -34,7 +36,7 @@ You can use the same dependency *functions* you use normally.
They can declare request requirements (like headers) or other sub-dependencies:
```Python hl_lines="6 11"
-{!./src/dependencies/tutorial006.py!}
+{!../../../docs_src/dependencies/tutorial006.py!}
```
### Raise exceptions
@@ -42,7 +44,7 @@ They can declare request requirements (like headers) or other sub-dependencies:
These dependencies can `raise` exceptions, the same as normal dependencies:
```Python hl_lines="8 13"
-{!./src/dependencies/tutorial006.py!}
+{!../../../docs_src/dependencies/tutorial006.py!}
```
### Return values
@@ -52,7 +54,7 @@ And they can return values or not, the values won't be used.
So, you can re-use a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed:
```Python hl_lines="9 14"
-{!./src/dependencies/tutorial006.py!}
+{!../../../docs_src/dependencies/tutorial006.py!}
```
## Dependencies for a group of *path operations*
diff --git a/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
similarity index 96%
rename from docs/tutorial/dependencies/dependencies-with-yield.md
rename to docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
index 08d600a5aee4d..1c8cdba65a2a1 100644
--- a/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,4 +1,4 @@
-# Dependencies with `yield`
+# Dependencies with yield
FastAPI supports dependencies that do some extra steps after finishing.
@@ -33,19 +33,19 @@ For example, you could use this to create a database session and close it after
Only the code prior to and including the `yield` statement is executed before sending a response:
```Python hl_lines="2 3 4"
-{!./src/dependencies/tutorial007.py!}
+{!../../../docs_src/dependencies/tutorial007.py!}
```
The yielded value is what is injected into *path operations* and other dependencies:
```Python hl_lines="4"
-{!./src/dependencies/tutorial007.py!}
+{!../../../docs_src/dependencies/tutorial007.py!}
```
The code following the `yield` statement is executed after the response has been delivered:
```Python hl_lines="5 6"
-{!./src/dependencies/tutorial007.py!}
+{!../../../docs_src/dependencies/tutorial007.py!}
```
!!! tip
@@ -64,7 +64,7 @@ So, you can look for that specific exception inside the dependency with `except
In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not.
```Python hl_lines="3 5"
-{!./src/dependencies/tutorial007.py!}
+{!../../../docs_src/dependencies/tutorial007.py!}
```
## Sub-dependencies with `yield`
@@ -76,7 +76,7 @@ You can have sub-dependencies and "trees" of sub-dependencies of any size and sh
For example, `dependency_c` can have a dependency on `dependency_b`, and `dependency_b` on `dependency_a`:
```Python hl_lines="4 12 20"
-{!./src/dependencies/tutorial008.py!}
+{!../../../docs_src/dependencies/tutorial008.py!}
```
And all of them can use `yield`.
@@ -86,7 +86,7 @@ In this case `dependency_c`, to execute its exit code, needs the value from `dep
And, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code.
```Python hl_lines="16 17 24 25"
-{!./src/dependencies/tutorial008.py!}
+{!../../../docs_src/dependencies/tutorial008.py!}
```
The same way, you could have dependencies with `yield` and `return` mixed.
@@ -208,7 +208,7 @@ You can also use them inside of **FastAPI** dependencies with `yield` by using
`with` or `async with` statements inside of the dependency function:
```Python hl_lines="1 2 3 4 5 6 7 8 9 13"
-{!./src/dependencies/tutorial010.py!}
+{!../../../docs_src/dependencies/tutorial010.py!}
```
!!! tip
diff --git a/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md
similarity index 97%
rename from docs/tutorial/dependencies/index.md
rename to docs/en/docs/tutorial/dependencies/index.md
index c92dcebf6d7b2..5b8d11ea765ae 100644
--- a/docs/tutorial/dependencies/index.md
+++ b/docs/en/docs/tutorial/dependencies/index.md
@@ -1,3 +1,5 @@
+# Dependencies - First Steps
+
**FastAPI** has a very powerful but intuitive **Dependency Injection** system.
It is designed to be very simple to use, and to make it very easy for any developer to integrate other components with **FastAPI**.
@@ -30,7 +32,7 @@ Let's first focus on the dependency.
It is just a function that can take all the same parameters that a *path operation function* can take:
```Python hl_lines="6 7"
-{!./src/dependencies/tutorial001.py!}
+{!../../../docs_src/dependencies/tutorial001.py!}
```
That's it.
@@ -54,7 +56,7 @@ And then it just returns a `dict` containing those values.
### Import `Depends`
```Python hl_lines="1"
-{!./src/dependencies/tutorial001.py!}
+{!../../../docs_src/dependencies/tutorial001.py!}
```
### Declare the dependency, in the "dependant"
@@ -62,7 +64,7 @@ And then it just returns a `dict` containing those values.
The same way you use `Body`, `Query`, etc. with your *path operation function* parameters, use `Depends` with a new parameter:
```Python hl_lines="11 16"
-{!./src/dependencies/tutorial001.py!}
+{!../../../docs_src/dependencies/tutorial001.py!}
```
Although you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently.
diff --git a/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
similarity index 95%
rename from docs/tutorial/dependencies/sub-dependencies.md
rename to docs/en/docs/tutorial/dependencies/sub-dependencies.md
index 3407733808cce..71b1404d6f860 100644
--- a/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
@@ -1,3 +1,5 @@
+# Sub-dependencies
+
You can create dependencies that have **sub-dependencies**.
They can be as **deep** as you need them to be.
@@ -9,7 +11,7 @@ They can be as **deep** as you need them to be.
You could create a first dependency ("dependable") like:
```Python hl_lines="6 7"
-{!./src/dependencies/tutorial005.py!}
+{!../../../docs_src/dependencies/tutorial005.py!}
```
It declares an optional query parameter `q` as a `str`, and then it just returns it.
@@ -21,7 +23,7 @@ This is quite simple (not very useful), but will help us focus on how the sub-de
Then you can create another dependency function (a "dependable") that at the same time declares a dependency of its own (so it is a "dependant" too):
```Python hl_lines="11"
-{!./src/dependencies/tutorial005.py!}
+{!../../../docs_src/dependencies/tutorial005.py!}
```
Let's focus on the parameters declared:
@@ -36,7 +38,7 @@ Let's focus on the parameters declared:
Then we can use the dependency with:
```Python hl_lines="19"
-{!./src/dependencies/tutorial005.py!}
+{!../../../docs_src/dependencies/tutorial005.py!}
```
!!! info
diff --git a/docs/tutorial/encoder.md b/docs/en/docs/tutorial/encoder.md
similarity index 95%
rename from docs/tutorial/encoder.md
rename to docs/en/docs/tutorial/encoder.md
index 4ce940eca1227..3879f976af6e1 100644
--- a/docs/tutorial/encoder.md
+++ b/docs/en/docs/tutorial/encoder.md
@@ -1,3 +1,5 @@
+# JSON Compatible Encoder
+
There are some cases where you might need to convert a data type (like a Pydantic model) to something compatible with JSON (like a `dict`, `list`, etc).
For example, if you need to store it in a database.
@@ -19,7 +21,7 @@ You can use `jsonable_encoder` for that.
It receives an object, like a Pydantic model, and returns a JSON compatible version:
```Python hl_lines="4 21"
-{!./src/encoder/tutorial001.py!}
+{!../../../docs_src/encoder/tutorial001.py!}
```
In this example, it would convert the Pydantic model to a `dict`, and the `datetime` to a `str`.
diff --git a/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md
similarity index 94%
rename from docs/tutorial/extra-data-types.md
rename to docs/en/docs/tutorial/extra-data-types.md
index 7534be86da81b..07c1ed06f792d 100644
--- a/docs/tutorial/extra-data-types.md
+++ b/docs/en/docs/tutorial/extra-data-types.md
@@ -1,3 +1,5 @@
+# Extra Data Types
+
Up to now, you have been using common data types, like:
* `int`
@@ -53,11 +55,11 @@ Here are some of the additional data types you can use:
Here's an example *path operation* with parameters using some of the above types.
```Python hl_lines="1 2 11 12 13 14 15"
-{!./src/extra_data_types/tutorial001.py!}
+{!../../../docs_src/extra_data_types/tutorial001.py!}
```
Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like:
```Python hl_lines="17 18"
-{!./src/extra_data_types/tutorial001.py!}
+{!../../../docs_src/extra_data_types/tutorial001.py!}
```
diff --git a/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md
similarity index 95%
rename from docs/tutorial/extra-models.md
rename to docs/en/docs/tutorial/extra-models.md
index 731a73f3d18e7..5b8bf5a2b84ba 100644
--- a/docs/tutorial/extra-models.md
+++ b/docs/en/docs/tutorial/extra-models.md
@@ -1,3 +1,5 @@
+# Extra Models
+
Continuing with the previous example, it will be common to have more than one related model.
This is especially the case for user models, because:
@@ -16,7 +18,7 @@ This is especially the case for user models, because:
Here's a general idea of how the models could look like with their password fields and the places where they are used:
```Python hl_lines="7 9 14 20 22 27 28 31 32 33 38 39"
-{!./src/extra_models/tutorial001.py!}
+{!../../../docs_src/extra_models/tutorial001.py!}
```
### About `**user_in.dict()`
@@ -149,7 +151,7 @@ All the data conversion, validation, documentation, etc. will still work as norm
That way, we can declare just the differences between the models (with plaintext `password`, with `hashed_password` and without password):
```Python hl_lines="7 13 14 17 18 21 22"
-{!./src/extra_models/tutorial002.py!}
+{!../../../docs_src/extra_models/tutorial002.py!}
```
## `Union` or `anyOf`
@@ -161,7 +163,7 @@ It will be defined in OpenAPI with `anyOf`.
To do that, use the standard Python type hint `typing.Union`:
```Python hl_lines="1 14 15 18 19 20 33"
-{!./src/extra_models/tutorial003.py!}
+{!../../../docs_src/extra_models/tutorial003.py!}
```
## List of models
@@ -171,7 +173,7 @@ The same way, you can declare responses of lists of objects.
For that, use the standard Python `typing.List`:
```Python hl_lines="1 20"
-{!./src/extra_models/tutorial004.py!}
+{!../../../docs_src/extra_models/tutorial004.py!}
```
## Response with arbitrary `dict`
@@ -183,7 +185,7 @@ This is useful if you don't know the valid field/attribute names (that would be
In this case, you can use `typing.Dict`:
```Python hl_lines="1 8"
-{!./src/extra_models/tutorial005.py!}
+{!../../../docs_src/extra_models/tutorial005.py!}
```
## Recap
diff --git a/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md
similarity index 83%
rename from docs/tutorial/first-steps.md
rename to docs/en/docs/tutorial/first-steps.md
index dd916f3304a80..11a9d16e09129 100644
--- a/docs/tutorial/first-steps.md
+++ b/docs/en/docs/tutorial/first-steps.md
@@ -1,17 +1,29 @@
+# First Steps
+
The simplest FastAPI file could look like this:
```Python
-{!./src/first_steps/tutorial001.py!}
+{!../../../docs_src/first_steps/tutorial001.py!}
```
Copy that to a file `main.py`.
Run the live server:
-```bash
-uvicorn main:app --reload
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
```
+
+
!!! note
The command `uvicorn main:app` refers to:
@@ -19,16 +31,13 @@ uvicorn main:app --reload
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
* `--reload`: make the server restart after code changes. Only use for development.
-You will see an output like:
+In the output, there's a line with something like:
```hl_lines="4"
-INFO: Started reloader process [17961]
-INFO: Started server process [17962]
-INFO: Waiting for application startup.
-INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
-That last line shows the URL where your app is being served, in your local machine.
+That line shows the URL where your app is being served, in your local machine.
### Check it
@@ -122,7 +131,7 @@ You could also use it to generate code automatically, for clients that communica
### Step 1: import `FastAPI`
```Python hl_lines="1"
-{!./src/first_steps/tutorial001.py!}
+{!../../../docs_src/first_steps/tutorial001.py!}
```
`FastAPI` is a Python class that provides all the functionality for your API.
@@ -135,7 +144,7 @@ You could also use it to generate code automatically, for clients that communica
### Step 2: create a `FastAPI` "instance"
```Python hl_lines="3"
-{!./src/first_steps/tutorial001.py!}
+{!../../../docs_src/first_steps/tutorial001.py!}
```
Here the `app` variable will be an "instance" of the class `FastAPI`.
@@ -144,22 +153,34 @@ This will be the main point of interaction to create all your API.
This `app` is the same one referred by `uvicorn` in the command:
-```bash
-uvicorn main:app --reload
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
+
+
If you create your app like:
```Python hl_lines="3"
-{!./src/first_steps/tutorial002.py!}
+{!../../../docs_src/first_steps/tutorial002.py!}
```
And put it in a file `main.py`, then you would call `uvicorn` like:
-```bash
-uvicorn main:my_awesome_api --reload
+
+
+```console
+$ uvicorn main:my_awesome_api --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
+
+
### Step 3: create a *path operation*
#### Path
@@ -218,10 +239,10 @@ So, in OpenAPI, each of the HTTP methods is called an "operation".
We are going to call them "**operations**" too.
-#### Define a *path operation function*
+#### Define a *path operation decorator*
```Python hl_lines="6"
-{!./src/first_steps/tutorial001.py!}
+{!../../../docs_src/first_steps/tutorial001.py!}
```
The `@app.get("/")` tells **FastAPI** that the function right below is in charge of handling requests that go to:
@@ -271,7 +292,7 @@ This is our "**path operation function**":
* **function**: is the function below the "decorator" (below `@app.get("/")`).
```Python hl_lines="7"
-{!./src/first_steps/tutorial001.py!}
+{!../../../docs_src/first_steps/tutorial001.py!}
```
This is a Python function.
@@ -285,7 +306,7 @@ In this case, it is an `async` function.
You could also define it as a normal function instead of `async def`:
```Python hl_lines="7"
-{!./src/first_steps/tutorial003.py!}
+{!../../../docs_src/first_steps/tutorial003.py!}
```
!!! note
@@ -294,7 +315,7 @@ You could also define it as a normal function instead of `async def`:
### Step 5: return the content
```Python hl_lines="8"
-{!./src/first_steps/tutorial001.py!}
+{!../../../docs_src/first_steps/tutorial001.py!}
```
You can return a `dict`, `list`, singular values as `str`, `int`, etc.
diff --git a/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md
similarity index 94%
rename from docs/tutorial/handling-errors.md
rename to docs/en/docs/tutorial/handling-errors.md
index 8ae9ff47ea97b..19a6c568491fb 100644
--- a/docs/tutorial/handling-errors.md
+++ b/docs/en/docs/tutorial/handling-errors.md
@@ -1,3 +1,5 @@
+# Handling Errors
+
There are many situations in where you need to notify an error to a client that is using your API.
This client could be a browser with a frontend, a code from someone else, an IoT device, etc.
@@ -24,7 +26,7 @@ To return HTTP responses with errors to the client you use `HTTPException`.
### Import `HTTPException`
```Python hl_lines="1"
-{!./src/handling_errors/tutorial001.py!}
+{!../../../docs_src/handling_errors/tutorial001.py!}
```
### Raise an `HTTPException` in your code
@@ -40,7 +42,7 @@ The benefit of raising an exception over `return`ing a value will be more eviden
In this example, when the client request an item by an ID that doesn't exist, raise an exception with a status code of `404`:
```Python hl_lines="11"
-{!./src/handling_errors/tutorial001.py!}
+{!../../../docs_src/handling_errors/tutorial001.py!}
```
### The resulting response
@@ -77,7 +79,7 @@ You probably won't need to use it directly in your code.
But in case you needed it for an advanced scenario, you can add custom headers:
```Python hl_lines="14"
-{!./src/handling_errors/tutorial002.py!}
+{!../../../docs_src/handling_errors/tutorial002.py!}
```
## Install custom exception handlers
@@ -91,7 +93,7 @@ And you want to handle this exception globally with FastAPI.
You could add a custom exception handler with `@app.exception_handler()`:
```Python hl_lines="5 6 7 13 14 15 16 17 18 24"
-{!./src/handling_errors/tutorial003.py!}
+{!../../../docs_src/handling_errors/tutorial003.py!}
```
Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`.
@@ -113,7 +115,7 @@ So, you will receive a clean error, with an HTTP status code of `418` and a JSON
**FastAPI** has some default exception handlers.
-These handlers are in charge or returning the default JSON responses when you `raise` an `HTTPException` and when the request has invalid data.
+These handlers are in charge of returning the default JSON responses when you `raise` an `HTTPException` and when the request has invalid data.
You can override these exception handlers with your own.
@@ -128,7 +130,7 @@ To override it, import the `RequestValidationError` and use it with `@app.except
The exception handler will receive a `Request` and the exception.
```Python hl_lines="2 14 15 16"
-{!./src/handling_errors/tutorial004.py!}
+{!../../../docs_src/handling_errors/tutorial004.py!}
```
Now, if you go to `/items/foo`, instead of getting the default JSON error with:
@@ -178,7 +180,7 @@ The same way, you can override the `HTTPException` handler.
For example, you could want to return a plain text response instead of JSON for these errors:
```Python hl_lines="3 4 9 10 11 22"
-{!./src/handling_errors/tutorial004.py!}
+{!../../../docs_src/handling_errors/tutorial004.py!}
```
!!! note "Technical Details"
@@ -193,7 +195,7 @@ The `RequestValidationError` contains the `body` it received with invalid data.
You could use it while developing your app to log the body and debug it, return it to the user, etc.
```Python hl_lines="14"
-{!./src/handling_errors/tutorial005.py!}
+{!../../../docs_src/handling_errors/tutorial005.py!}
```
Now try sending an invalid item like:
@@ -256,7 +258,7 @@ You could also just want to use the exception somehow, but then use the same def
You can import and re-use the default exception handlers from `fastapi.exception_handlers`:
```Python hl_lines="2 3 4 5 15 21"
-{!./src/handling_errors/tutorial006.py!}
+{!../../../docs_src/handling_errors/tutorial006.py!}
```
In this example, you are just `print`ing the error with a very expressive message.
diff --git a/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md
similarity index 92%
rename from docs/tutorial/header-params.md
rename to docs/en/docs/tutorial/header-params.md
index 46c349bd11ff0..738d2a559ea90 100644
--- a/docs/tutorial/header-params.md
+++ b/docs/en/docs/tutorial/header-params.md
@@ -1,3 +1,5 @@
+# Header Parameters
+
You can define Header parameters the same way you define `Query`, `Path` and `Cookie` parameters.
## Import `Header`
@@ -5,7 +7,7 @@ You can define Header parameters the same way you define `Query`, `Path` and `Co
First import `Header`:
```Python hl_lines="1"
-{!./src/header_params/tutorial001.py!}
+{!../../../docs_src/header_params/tutorial001.py!}
```
## Declare `Header` parameters
@@ -15,7 +17,7 @@ Then declare the header parameters using the same structure as with `Path`, `Que
The first value is the default value, you can pass all the extra validation or annotation parameters:
```Python hl_lines="7"
-{!./src/header_params/tutorial001.py!}
+{!../../../docs_src/header_params/tutorial001.py!}
```
!!! note "Technical Details"
@@ -43,7 +45,7 @@ So, you can use `user_agent` as you normally would in Python code, instead of ne
If for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter `convert_underscores` of `Header` to `False`:
```Python hl_lines="7"
-{!./src/header_params/tutorial002.py!}
+{!../../../docs_src/header_params/tutorial002.py!}
```
!!! warning
@@ -61,7 +63,7 @@ You will receive all the values from the duplicate header as a Python `list`.
For example, to declare a header of `X-Token` that can appear more than once, you can write:
```Python hl_lines="9"
-{!./src/header_params/tutorial003.py!}
+{!../../../docs_src/header_params/tutorial003.py!}
```
If you communicate with that *path operation* sending two HTTP headers like:
diff --git a/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md
similarity index 72%
rename from docs/tutorial/index.md
rename to docs/en/docs/tutorial/index.md
index 0aa572c88e9d4..107961d3b2de3 100644
--- a/docs/tutorial/index.md
+++ b/docs/en/docs/tutorial/index.md
@@ -1,3 +1,5 @@
+# Tutorial - User Guide - Intro
+
This tutorial shows you how to use **FastAPI** with most of its features, step by step.
Each section gradually builds on the previous ones, but it's structured to separate topics, so that you can go directly to any specific one to solve your specific API needs.
@@ -12,10 +14,20 @@ All the code blocks can be copied and used directly (they are actually tested Py
To run any of the examples, copy the code to a file `main.py`, and start `uvicorn` with:
-```bash
-uvicorn main:app --reload
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
```
+
+
It is **HIGHLY encouraged** that you write or copy the code, edit it and run it locally.
Using it in your editor is what really shows you the benefits of FastAPI, seeing how little code you have to write, all the type checks, autocompletion, etc.
@@ -28,10 +40,16 @@ The first step is to install FastAPI.
For the tutorial, you might want to install it with all the optional dependencies and features:
-```bash
-pip install fastapi[all]
+
+
+```console
+$ pip install fastapi[all]
+
+---> 100%
```
+
+
...that also includes `uvicorn`, that you can use as the server that runs your code.
!!! note
@@ -57,6 +75,6 @@ There is also an **Advanced User Guide** that you can read later after this **Tu
The **Advanced User Guide**, builds on this, uses the same concepts, and teaches you some extra features.
-But you should first read the **Tutorial - User guide** (what you are reading right now).
+But you should first read the **Tutorial - User Guide** (what you are reading right now).
-It's designed so that you can build a complete application with just the **Tutorial - User guide**, and then extend it in different ways, depending on your needs, using some of the additional ideas from the **Advanced User Guide**.
+It's designed so that you can build a complete application with just the **Tutorial - User Guide**, and then extend it in different ways, depending on your needs, using some of the additional ideas from the **Advanced User Guide**.
diff --git a/docs/tutorial/application-configuration.md b/docs/en/docs/tutorial/metadata.md
similarity index 65%
rename from docs/tutorial/application-configuration.md
rename to docs/en/docs/tutorial/metadata.md
index 706ecd3483b46..666fa7648b1c3 100644
--- a/docs/tutorial/application-configuration.md
+++ b/docs/en/docs/tutorial/metadata.md
@@ -1,23 +1,25 @@
-There are several things that you can configure in your FastAPI application.
+# Metadata and Docs URLs
+
+You can customize several metadata configurations in your **FastAPI** application.
## Title, description, and version
You can set the:
-* Title: used as your API's title/name, in OpenAPI and the automatic API docs UIs.
-* Description: the description of your API, in OpenAPI and the automatic API docs UIs.
-* Version: the version of your API, e.g. `v2` or `2.5.0`.
+* **Title**: used as your API's title/name, in OpenAPI and the automatic API docs UIs.
+* **Description**: the description of your API, in OpenAPI and the automatic API docs UIs.
+* **Version**: the version of your API, e.g. `v2` or `2.5.0`.
* Useful for example if you had a previous version of the application, also using OpenAPI.
To set them, use the parameters `title`, `description`, and `version`:
```Python hl_lines="4 5 6"
-{!./src/application_configuration/tutorial001.py!}
+{!../../../docs_src/metadata/tutorial001.py!}
```
With this configuration, the automatic API docs would look like:
-
+
## OpenAPI URL
@@ -28,10 +30,10 @@ But you can configure it with the parameter `openapi_url`.
For example, to set it to be served at `/api/v1/openapi.json`:
```Python hl_lines="3"
-{!./src/application_configuration/tutorial002.py!}
+{!../../../docs_src/metadata/tutorial002.py!}
```
-If you want to disable the OpenAPI schema completely you can set `openapi_url=None`.
+If you want to disable the OpenAPI schema completely you can set `openapi_url=None`, that will also disable the documentation user interfaces that use it.
## Docs URLs
@@ -47,5 +49,5 @@ You can configure the two documentation user interfaces included:
For example, to set Swagger UI to be served at `/documentation` and disable ReDoc:
```Python hl_lines="3"
-{!./src/application_configuration/tutorial003.py!}
+{!../../../docs_src/metadata/tutorial003.py!}
```
diff --git a/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md
similarity index 96%
rename from docs/tutorial/middleware.md
rename to docs/en/docs/tutorial/middleware.md
index 5dd779189abc5..6f7ca000addf9 100644
--- a/docs/tutorial/middleware.md
+++ b/docs/en/docs/tutorial/middleware.md
@@ -1,3 +1,5 @@
+# Middleware
+
You can add middleware to **FastAPI** applications.
A "middleware" is a function that works with every **request** before it is processed by any specific *path operation*. And also with every **response** before returning it.
@@ -27,7 +29,7 @@ The middleware function receives:
* You can then modify further the `response` before returning it.
```Python hl_lines="8 9 11 14"
-{!./src/middleware/tutorial001.py!}
+{!../../../docs_src/middleware/tutorial001.py!}
```
!!! tip
@@ -49,7 +51,7 @@ And also after the `response` is generated, before returning it.
For example, you could add a custom header `X-Process-Time` containing the time in seconds that it took to process the request and generate a response:
```Python hl_lines="10 12 13"
-{!./src/middleware/tutorial001.py!}
+{!../../../docs_src/middleware/tutorial001.py!}
```
## Other middlewares
diff --git a/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md
similarity index 88%
rename from docs/tutorial/path-operation-configuration.md
rename to docs/en/docs/tutorial/path-operation-configuration.md
index cfc970b7a9005..c2c3008944157 100644
--- a/docs/tutorial/path-operation-configuration.md
+++ b/docs/en/docs/tutorial/path-operation-configuration.md
@@ -1,3 +1,5 @@
+# Path Operation Configuration
+
There are several parameters that you can pass to your *path operation decorator* to configure it.
!!! warning
@@ -12,7 +14,7 @@ You can pass directly the `int` code, like `404`.
But if you don't remember what each number code is for, you can use the shortcut constants in `status`:
```Python hl_lines="3 17"
-{!./src/path_operation_configuration/tutorial001.py!}
+{!../../../docs_src/path_operation_configuration/tutorial001.py!}
```
That status code will be used in the response and will be added to the OpenAPI schema.
@@ -27,7 +29,7 @@ That status code will be used in the response and will be added to the OpenAPI s
You can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`):
```Python hl_lines="17 22 27"
-{!./src/path_operation_configuration/tutorial002.py!}
+{!../../../docs_src/path_operation_configuration/tutorial002.py!}
```
They will be added to the OpenAPI schema and used by the automatic documentation interfaces:
@@ -39,7 +41,7 @@ They will be added to the OpenAPI schema and used by the automatic documentation
You can add a `summary` and `description`:
```Python hl_lines="20 21"
-{!./src/path_operation_configuration/tutorial003.py!}
+{!../../../docs_src/path_operation_configuration/tutorial003.py!}
```
## Description from docstring
@@ -49,7 +51,7 @@ As descriptions tend to be long and cover multiple lines, you can declare the *p
You can write Markdown in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation).
```Python hl_lines="19 20 21 22 23 24 25 26 27"
-{!./src/path_operation_configuration/tutorial004.py!}
+{!../../../docs_src/path_operation_configuration/tutorial004.py!}
```
It will be used in the interactive docs:
@@ -61,7 +63,7 @@ It will be used in the interactive docs:
You can specify the response description with the parameter `response_description`:
```Python hl_lines="21"
-{!./src/path_operation_configuration/tutorial005.py!}
+{!../../../docs_src/path_operation_configuration/tutorial005.py!}
```
!!! info
@@ -79,7 +81,7 @@ You can specify the response description with the parameter `response_descriptio
If you need to mark a *path operation* as deprecated, but without removing it, pass the parameter `deprecated`:
```Python hl_lines="16"
-{!./src/path_operation_configuration/tutorial006.py!}
+{!../../../docs_src/path_operation_configuration/tutorial006.py!}
```
It will be clearly marked as deprecated in the interactive docs:
diff --git a/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md
similarity index 89%
rename from docs/tutorial/path-params-numeric-validations.md
rename to docs/en/docs/tutorial/path-params-numeric-validations.md
index 5fe638f5f3351..9ae4c8b1a480b 100644
--- a/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/en/docs/tutorial/path-params-numeric-validations.md
@@ -1,3 +1,5 @@
+# Path Parameters and Numeric Validations
+
The same way you can declare more validations and metadata for query parameters with `Query`, you can declare the same type of validations and metadata for path parameters with `Path`.
## Import Path
@@ -5,7 +7,7 @@ The same way you can declare more validations and metadata for query parameters
First, import `Path` from `fastapi`:
```Python hl_lines="1"
-{!./src/path_params_numeric_validations/tutorial001.py!}
+{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
## Declare metadata
@@ -15,7 +17,7 @@ You can declare all the same parameters as for `Query`.
For example, to declare a `title` metadata value for the path parameter `item_id` you can type:
```Python hl_lines="8"
-{!./src/path_params_numeric_validations/tutorial001.py!}
+{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
!!! note
@@ -42,7 +44,7 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names,
So, you can declare your function as:
```Python hl_lines="8"
-{!./src/path_params_numeric_validations/tutorial002.py!}
+{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
```
## Order the parameters as you need, tricks
@@ -54,7 +56,7 @@ Pass `*`, as the first parameter of the function.
Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs
. Even if they don't have a default value.
```Python hl_lines="8"
-{!./src/path_params_numeric_validations/tutorial003.py!}
+{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
## Number validations: greater than or equal
@@ -64,7 +66,7 @@ With `Query` and `Path` (and other's you'll see later) you can declare string co
Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`.
```Python hl_lines="8"
-{!./src/path_params_numeric_validations/tutorial004.py!}
+{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
```
## Number validations: greater than and less than or equal
@@ -75,7 +77,7 @@ The same applies for:
* `le`: `l`ess than or `e`qual
```Python hl_lines="9"
-{!./src/path_params_numeric_validations/tutorial005.py!}
+{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
```
## Number validations: floats, greater than and less than
@@ -89,7 +91,7 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not.
And the same for lt
.
```Python hl_lines="11"
-{!./src/path_params_numeric_validations/tutorial006.py!}
+{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
```
## Recap
diff --git a/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md
similarity index 94%
rename from docs/tutorial/path-params.md
rename to docs/en/docs/tutorial/path-params.md
index b4c4054551a3b..1c32108bb6a3e 100644
--- a/docs/tutorial/path-params.md
+++ b/docs/en/docs/tutorial/path-params.md
@@ -1,7 +1,9 @@
+# Path Parameters
+
You can declare path "parameters" or "variables" with the same syntax used by Python format strings:
```Python hl_lines="6 7"
-{!./src/path_params/tutorial001.py!}
+{!../../../docs_src/path_params/tutorial001.py!}
```
The value of the path parameter `item_id` will be passed to your function as the argument `item_id`.
@@ -17,7 +19,7 @@ So, if you run this example and go to regular expression that the parameter should match:
```Python hl_lines="8"
-{!./src/query_params_str_validations/tutorial004.py!}
+{!../../../docs_src/query_params_str_validations/tutorial004.py!}
```
This specific regular expression checks that the received parameter value:
@@ -85,7 +87,7 @@ The same way that you can pass `None` as the first argument to be used as the de
Let's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `"fixedquery"`:
```Python hl_lines="7"
-{!./src/query_params_str_validations/tutorial005.py!}
+{!../../../docs_src/query_params_str_validations/tutorial005.py!}
```
!!! note
@@ -114,7 +116,7 @@ q: str = Query(None, min_length=3)
So, when you need to declare a value as required while using `Query`, you can use `...` as the first argument:
```Python hl_lines="7"
-{!./src/query_params_str_validations/tutorial006.py!}
+{!../../../docs_src/query_params_str_validations/tutorial006.py!}
```
!!! info
@@ -129,7 +131,7 @@ When you define a query parameter explicitly with `Query` you can also declare i
For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write:
```Python hl_lines="9"
-{!./src/query_params_str_validations/tutorial011.py!}
+{!../../../docs_src/query_params_str_validations/tutorial011.py!}
```
Then, with a URL like:
@@ -163,7 +165,7 @@ The interactive API docs will update accordingly, to allow multiple values:
And you can also define a default `list` of values if none are provided:
```Python hl_lines="9"
-{!./src/query_params_str_validations/tutorial012.py!}
+{!../../../docs_src/query_params_str_validations/tutorial012.py!}
```
If you go to:
@@ -188,7 +190,7 @@ the default of `q` will be: `["foo", "bar"]` and your response will be:
You can also use `list` directly instead of `List[str]`:
```Python hl_lines="7"
-{!./src/query_params_str_validations/tutorial013.py!}
+{!../../../docs_src/query_params_str_validations/tutorial013.py!}
```
!!! note
@@ -210,13 +212,13 @@ That information will be included in the generated OpenAPI and used by the docum
You can add a `title`:
```Python hl_lines="7"
-{!./src/query_params_str_validations/tutorial007.py!}
+{!../../../docs_src/query_params_str_validations/tutorial007.py!}
```
And a `description`:
```Python hl_lines="11"
-{!./src/query_params_str_validations/tutorial008.py!}
+{!../../../docs_src/query_params_str_validations/tutorial008.py!}
```
## Alias parameters
@@ -238,7 +240,7 @@ But you still need it to be exactly `item-query`...
Then you can declare an `alias`, and that alias is what will be used to find the parameter value:
```Python hl_lines="7"
-{!./src/query_params_str_validations/tutorial009.py!}
+{!../../../docs_src/query_params_str_validations/tutorial009.py!}
```
## Deprecating parameters
@@ -250,7 +252,7 @@ You have to leave it there a while because there are clients using it, but you w
Then pass the parameter `deprecated=True` to `Query`:
```Python hl_lines="16"
-{!./src/query_params_str_validations/tutorial010.py!}
+{!../../../docs_src/query_params_str_validations/tutorial010.py!}
```
The docs will show it like this:
diff --git a/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md
similarity index 92%
rename from docs/tutorial/query-params.md
rename to docs/en/docs/tutorial/query-params.md
index 5e72301105ad3..0efc57e1b87e1 100644
--- a/docs/tutorial/query-params.md
+++ b/docs/en/docs/tutorial/query-params.md
@@ -1,7 +1,9 @@
+# Query Parameters
+
When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters.
```Python hl_lines="9"
-{!./src/query_params/tutorial001.py!}
+{!../../../docs_src/query_params/tutorial001.py!}
```
The query is the set of key-value pairs that go after the `?` in a URL, separated by `&` characters.
@@ -62,7 +64,7 @@ The parameter values in your function will be:
The same way, you can declare optional query parameters, by setting their default to `None`:
```Python hl_lines="7"
-{!./src/query_params/tutorial002.py!}
+{!../../../docs_src/query_params/tutorial002.py!}
```
In this case, the function parameter `q` will be optional, and will be `None` by default.
@@ -75,7 +77,7 @@ In this case, the function parameter `q` will be optional, and will be `None` by
You can also declare `bool` types, and they will be converted:
```Python hl_lines="7"
-{!./src/query_params/tutorial003.py!}
+{!../../../docs_src/query_params/tutorial003.py!}
```
In this case, if you go to:
@@ -120,7 +122,7 @@ And you don't have to declare them in any specific order.
They will be detected by name:
```Python hl_lines="6 8"
-{!./src/query_params/tutorial004.py!}
+{!../../../docs_src/query_params/tutorial004.py!}
```
## Required query parameters
@@ -132,7 +134,7 @@ If you don't want to add a specific value but just make it optional, set the def
But when you want to make a query parameter required, you can just not declare any default value:
```Python hl_lines="6 7"
-{!./src/query_params/tutorial005.py!}
+{!../../../docs_src/query_params/tutorial005.py!}
```
Here the query parameter `needy` is a required query parameter of type `str`.
@@ -178,7 +180,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
And of course, you can define some parameters as required, some as having a default value, and some entirely optional:
```Python hl_lines="7"
-{!./src/query_params/tutorial006.py!}
+{!../../../docs_src/query_params/tutorial006.py!}
```
In this case, there are 3 query parameters:
@@ -220,5 +222,5 @@ limit: Optional[int] = None
In a *path operation* that could look like:
```Python hl_lines="9"
-{!./src/query_params/tutorial007.py!}
+{!../../../docs_src/query_params/tutorial007.py!}
```
diff --git a/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md
similarity index 96%
rename from docs/tutorial/request-files.md
rename to docs/en/docs/tutorial/request-files.md
index b14f45c702f22..260a5e1905aeb 100644
--- a/docs/tutorial/request-files.md
+++ b/docs/en/docs/tutorial/request-files.md
@@ -1,3 +1,5 @@
+# Request Files
+
You can define files to be uploaded by the client using `File`.
!!! info
@@ -12,7 +14,7 @@ You can define files to be uploaded by the client using `File`.
Import `File` and `UploadFile` from `fastapi`:
```Python hl_lines="1"
-{!./src/request_files/tutorial001.py!}
+{!../../../docs_src/request_files/tutorial001.py!}
```
## Define `File` parameters
@@ -20,7 +22,7 @@ Import `File` and `UploadFile` from `fastapi`:
Create file parameters the same way you would for `Body` or `Form`:
```Python hl_lines="7"
-{!./src/request_files/tutorial001.py!}
+{!../../../docs_src/request_files/tutorial001.py!}
```
!!! info
@@ -44,7 +46,7 @@ But there are several cases in where you might benefit from using `UploadFile`.
Define a `File` parameter with a type of `UploadFile`:
```Python hl_lines="12"
-{!./src/request_files/tutorial001.py!}
+{!../../../docs_src/request_files/tutorial001.py!}
```
Using `UploadFile` has several advantages over `bytes`:
@@ -120,7 +122,7 @@ They would be associated to the same "form field" sent using "form data".
To use that, declare a `List` of `bytes` or `UploadFile`:
```Python hl_lines="10 15"
-{!./src/request_files/tutorial002.py!}
+{!../../../docs_src/request_files/tutorial002.py!}
```
You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
diff --git a/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md
similarity index 88%
rename from docs/tutorial/request-forms-and-files.md
rename to docs/en/docs/tutorial/request-forms-and-files.md
index 51ba786386c0c..6844f8c658f2b 100644
--- a/docs/tutorial/request-forms-and-files.md
+++ b/docs/en/docs/tutorial/request-forms-and-files.md
@@ -1,3 +1,5 @@
+# Request Forms and Files
+
You can define files and form fields at the same time using `File` and `Form`.
!!! info
@@ -8,7 +10,7 @@ You can define files and form fields at the same time using `File` and `Form`.
## Import `File` and `Form`
```Python hl_lines="1"
-{!./src/request_forms_and_files/tutorial001.py!}
+{!../../../docs_src/request_forms_and_files/tutorial001.py!}
```
## Define `File` and `Form` parameters
@@ -16,7 +18,7 @@ You can define files and form fields at the same time using `File` and `Form`.
Create file and form parameters the same way you would for `Body` or `Query`:
```Python hl_lines="8"
-{!./src/request_forms_and_files/tutorial001.py!}
+{!../../../docs_src/request_forms_and_files/tutorial001.py!}
```
The files and form fields will be uploaded as form data and you will receive the files and form fields.
diff --git a/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md
similarity index 95%
rename from docs/tutorial/request-forms.md
rename to docs/en/docs/tutorial/request-forms.md
index edb9af64174ef..b5495a4005610 100644
--- a/docs/tutorial/request-forms.md
+++ b/docs/en/docs/tutorial/request-forms.md
@@ -1,3 +1,5 @@
+# Form Data
+
When you need to receive form fields instead of JSON, you can use `Form`.
!!! info
@@ -10,7 +12,7 @@ When you need to receive form fields instead of JSON, you can use `Form`.
Import `Form` from `fastapi`:
```Python hl_lines="1"
-{!./src/request_forms/tutorial001.py!}
+{!../../../docs_src/request_forms/tutorial001.py!}
```
## Define `Form` parameters
@@ -18,7 +20,7 @@ Import `Form` from `fastapi`:
Create form parameters the same way you would for `Body` or `Query`:
```Python hl_lines="7"
-{!./src/request_forms/tutorial001.py!}
+{!../../../docs_src/request_forms/tutorial001.py!}
```
For example, in one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a `username` and `password` as form fields.
diff --git a/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
similarity index 91%
rename from docs/tutorial/response-model.md
rename to docs/en/docs/tutorial/response-model.md
index 1f1288ca7c4d1..9dd0b6dee6624 100644
--- a/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -1,3 +1,5 @@
+# Response Model
+
You can declare the model used for the response with the parameter `response_model` in any of the *path operations*:
* `@app.get()`
@@ -7,7 +9,7 @@ You can declare the model used for the response with the parameter `response_mod
* etc.
```Python hl_lines="17"
-{!./src/response_model/tutorial001.py!}
+{!../../../docs_src/response_model/tutorial001.py!}
```
!!! note
@@ -34,13 +36,13 @@ But most importantly:
Here we are declaring a `UserIn` model, it will contain a plaintext password:
```Python hl_lines="7 9"
-{!./src/response_model/tutorial002.py!}
+{!../../../docs_src/response_model/tutorial002.py!}
```
And we are using this model to declare our input and the same model to declare our output:
```Python hl_lines="15 16"
-{!./src/response_model/tutorial002.py!}
+{!../../../docs_src/response_model/tutorial002.py!}
```
Now, whenever a browser is creating a user with a password, the API will return the same password in the response.
@@ -50,26 +52,26 @@ In this case, it might not be a problem, because the user himself is sending the
But if we use the same model for another *path operation*, we could be sending our user's passwords to every client.
!!! danger
- Never send the plain password of a user in a response.
+ Never store the plain password of a user or send it in a response.
## Add an output model
We can instead create an input model with the plaintext password and an output model without it:
```Python hl_lines="7 9 14"
-{!./src/response_model/tutorial003.py!}
+{!../../../docs_src/response_model/tutorial003.py!}
```
Here, even though our *path operation function* is returning the same input user that contains the password:
```Python hl_lines="22"
-{!./src/response_model/tutorial003.py!}
+{!../../../docs_src/response_model/tutorial003.py!}
```
...we declared the `response_model` to be our model `UserOut`, that doesn't include the password:
```Python hl_lines="20"
-{!./src/response_model/tutorial003.py!}
+{!../../../docs_src/response_model/tutorial003.py!}
```
So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).
@@ -89,7 +91,7 @@ And both models will be used for the interactive API documentation:
Your response model could have default values, like:
```Python hl_lines="11 13 14"
-{!./src/response_model/tutorial004.py!}
+{!../../../docs_src/response_model/tutorial004.py!}
```
* `description: str = None` has a default of `None`.
@@ -105,7 +107,7 @@ For example, if you have models with many optional attributes in a NoSQL databas
You can set the *path operation decorator* parameter `response_model_exclude_unset=True`:
```Python hl_lines="24"
-{!./src/response_model/tutorial004.py!}
+{!../../../docs_src/response_model/tutorial004.py!}
```
and those default values won't be included in the response, only the values actually set.
@@ -174,7 +176,7 @@ This can be used as a quick shortcut if you have only one Pydantic model and wan
This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes.
```Python hl_lines="29 35"
-{!./src/response_model/tutorial005.py!}
+{!../../../docs_src/response_model/tutorial005.py!}
```
!!! tip
@@ -187,7 +189,7 @@ This can be used as a quick shortcut if you have only one Pydantic model and wan
If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly:
```Python hl_lines="29 35"
-{!./src/response_model/tutorial006.py!}
+{!../../../docs_src/response_model/tutorial006.py!}
```
## Recap
diff --git a/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md
similarity index 94%
rename from docs/tutorial/response-status-code.md
rename to docs/en/docs/tutorial/response-status-code.md
index 3f77272de3f58..29b8521fc737f 100644
--- a/docs/tutorial/response-status-code.md
+++ b/docs/en/docs/tutorial/response-status-code.md
@@ -1,3 +1,5 @@
+# Response Status Code
+
The same way you can specify a response model, you can also declare the HTTP status code used for the response with the parameter `status_code` in any of the *path operations*:
* `@app.get()`
@@ -7,7 +9,7 @@ The same way you can specify a response model, you can also declare the HTTP sta
* etc.
```Python hl_lines="6"
-{!./src/response_status_code/tutorial001.py!}
+{!../../../docs_src/response_status_code/tutorial001.py!}
```
!!! note
@@ -57,7 +59,7 @@ In short:
Let's see the previous example again:
```Python hl_lines="6"
-{!./src/response_status_code/tutorial001.py!}
+{!../../../docs_src/response_status_code/tutorial001.py!}
```
`201` is the status code for "Created".
@@ -67,7 +69,7 @@ But you don't have to memorize what each of these codes mean.
You can use the convenience variables from `fastapi.status`.
```Python hl_lines="1 6"
-{!./src/response_status_code/tutorial002.py!}
+{!../../../docs_src/response_status_code/tutorial002.py!}
```
They are just a convenience, they hold the same number, but that way you can use the editor's autocomplete to find them:
diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md
new file mode 100644
index 0000000000000..70c3d184669b4
--- /dev/null
+++ b/docs/en/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,58 @@
+# Schema Extra - Example
+
+You can define extra information to go in JSON Schema.
+
+A common use case is to add an `example` that will be shown in the docs.
+
+There are several ways you can declare extra JSON Schema information.
+
+## Pydantic `schema_extra`
+
+You can declare an example for a Pydantic model using `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization:
+
+```Python hl_lines="13 14 15 16 17 18 19 20 21"
+{!../../../docs_src/schema_extra_example/tutorial001.py!}
+```
+
+That extra info will be added as-is to the output JSON Schema.
+
+## `Field` additional arguments
+
+In `Field`, `Path`, `Query`, `Body` and others you'll see later, you can also declare extra info for the JSON Schema by passing any other arbitrary arguments to the function, for example, to add an `example`:
+
+```Python hl_lines="2 8 9 10 11"
+{!../../../docs_src/schema_extra_example/tutorial002.py!}
+```
+
+!!! warning
+ Have in mind that those extra arguments passed won't add any validation, only annotation, for documentation purposes.
+
+## `Body` additional arguments
+
+The same way you can pass extra info to `Field`, you can do the same with `Path`, `Query`, `Body`, etc.
+
+For example, you can pass an `example` for a body request to `Body`:
+
+```Python hl_lines="20 21 22 23 24 25"
+{!../../../docs_src/schema_extra_example/tutorial003.py!}
+```
+
+## Example in the docs UI
+
+With any of the methods above it would look like this in the `/docs`:
+
+
+
+## Technical Details
+
+About `example` vs `examples`...
+
+JSON Schema defines a field `examples` in the most recent versions, but OpenAPI is based on an older version of JSON Schema that didn't have `examples`.
+
+So, OpenAPI defined its own `example` for the same purpose (as `example`, not `examples`), and that's what is used by the docs UI (using Swagger UI).
+
+So, although `example` is not part of JSON Schema, it is part of OpenAPI, and that's what will be used by the docs UI.
+
+## Other info
+
+The same way, you could add your own custom extra info that would be added to the JSON Schema for each model, for example to customize a frontend user interface, etc.
diff --git a/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md
similarity index 94%
rename from docs/tutorial/security/first-steps.md
rename to docs/en/docs/tutorial/security/first-steps.md
index 5d215bdd0540a..287e92c23ef39 100644
--- a/docs/tutorial/security/first-steps.md
+++ b/docs/en/docs/tutorial/security/first-steps.md
@@ -1,3 +1,5 @@
+# Security - First Steps
+
Let's imagine that you have your **backend** API in some domain.
And you have a **frontend** in another domain or in a different path of the same domain (or in a mobile application).
@@ -19,7 +21,7 @@ Let's first just use the code and see how it works, and then we'll come back to
Copy the example in a file `main.py`:
```Python
-{!./src/security/tutorial001.py!}
+{!../../../docs_src/security/tutorial001.py!}
```
## Run it
@@ -33,10 +35,16 @@ Copy the example in a file `main.py`:
Run the example with:
-```bash
-uvicorn main:app --reload
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
+
+
## Check it
Go to the interactive docs at: http://127.0.0.1:8000/docs.
@@ -46,7 +54,7 @@ You will see something like this:
!!! check "Authorize button!"
- You already have a shinny new "Authorize" button.
+ You already have a shiny new "Authorize" button.
And your *path operation* has a little lock in the top-right corner that you can click.
@@ -109,7 +117,7 @@ In this example we are going to use **OAuth2**, with the **Password** flow, usin
`OAuth2PasswordBearer` is a class that we create passing a parameter of the URL in where the client (the frontend running in the user's browser) can use to send the `username` and `password` and get a token.
```Python hl_lines="6"
-{!./src/security/tutorial001.py!}
+{!../../../docs_src/security/tutorial001.py!}
```
It doesn't create that endpoint / *path operation*, but declares that that URL is the one that the client should use to get the token. That information is used in OpenAPI, and then in the interactive API documentation systems.
@@ -134,7 +142,7 @@ So, it can be used with `Depends`.
Now you can pass that `oauth2_scheme` in a dependency with `Depends`.
```Python hl_lines="10"
-{!./src/security/tutorial001.py!}
+{!../../../docs_src/security/tutorial001.py!}
```
This dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*.
diff --git a/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md
similarity index 92%
rename from docs/tutorial/security/get-current-user.md
rename to docs/en/docs/tutorial/security/get-current-user.md
index e2d6b7924cacd..3fc0164c3263f 100644
--- a/docs/tutorial/security/get-current-user.md
+++ b/docs/en/docs/tutorial/security/get-current-user.md
@@ -1,7 +1,9 @@
+# Get Current User
+
In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`:
```Python hl_lines="10"
-{!./src/security/tutorial001.py!}
+{!../../../docs_src/security/tutorial001.py!}
```
But that is still not that useful.
@@ -15,7 +17,7 @@ First, let's create a Pydantic user model.
The same way we use Pydantic to declare bodies, we can use it anywhere else:
```Python hl_lines="5 12 13 14 15 16"
-{!./src/security/tutorial002.py!}
+{!../../../docs_src/security/tutorial002.py!}
```
## Create a `get_current_user` dependency
@@ -29,7 +31,7 @@ Remember that dependencies can have sub-dependencies?
The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`:
```Python hl_lines="25"
-{!./src/security/tutorial002.py!}
+{!../../../docs_src/security/tutorial002.py!}
```
## Get the user
@@ -37,7 +39,7 @@ The same as we were doing before in the *path operation* directly, our new depen
`get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model:
```Python hl_lines="19 20 21 22 26 27"
-{!./src/security/tutorial002.py!}
+{!../../../docs_src/security/tutorial002.py!}
```
## Inject the current user
@@ -45,7 +47,7 @@ The same as we were doing before in the *path operation* directly, our new depen
So now we can use the same `Depends` with our `get_current_user` in the *path operation*:
```Python hl_lines="31"
-{!./src/security/tutorial002.py!}
+{!../../../docs_src/security/tutorial002.py!}
```
Notice that we declare the type of `current_user` as the Pydantic model `User`.
@@ -97,7 +99,7 @@ And all of them (or any portion of them that you want) can take the advantage of
And all these thousands of *path operations* can be as small as 3 lines:
```Python hl_lines="30 31 32"
-{!./src/security/tutorial002.py!}
+{!../../../docs_src/security/tutorial002.py!}
```
## Recap
diff --git a/docs/tutorial/security/index.md b/docs/en/docs/tutorial/security/index.md
similarity index 99%
rename from docs/tutorial/security/index.md
rename to docs/en/docs/tutorial/security/index.md
index 96c941dd58297..9aed2adb5d3a5 100644
--- a/docs/tutorial/security/index.md
+++ b/docs/en/docs/tutorial/security/index.md
@@ -1,3 +1,5 @@
+# Security Intro
+
There are many ways to handle security, authentication and authorization.
And it normally is a complex and "difficult" topic.
diff --git a/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md
similarity index 94%
rename from docs/tutorial/security/oauth2-jwt.md
rename to docs/en/docs/tutorial/security/oauth2-jwt.md
index 70945f2368bb3..18b4e0e300c1a 100644
--- a/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/en/docs/tutorial/security/oauth2-jwt.md
@@ -1,3 +1,5 @@
+# OAuth2 with Password (and hashing), Bearer with JWT tokens
+
Now that we have all the security flow, let's make the application actually secure, using JWT tokens and secure password hashing.
This code is something you can actually use in your application, save the password hashes in your database, etc.
@@ -28,10 +30,16 @@ If you want to play with JWT tokens and see how they work, check
+
+```console
+$ pip install pyjwt
+
+---> 100%
```
+
+
## Password hashing
"Hashing" means converting some content (a password in this case) into a sequence of bytes (just a string) that looks like gibberish.
@@ -56,10 +64,16 @@ The recommended algorithm is "Bcrypt".
So, install PassLib with Bcrypt:
-```bash
-pip install passlib[bcrypt]
+
+
+```console
+$ pip install passlib[bcrypt]
+
+---> 100%
```
+
+
!!! tip
With `passlib`, you could even configure it to be able to read passwords created by **Django**, a **Flask** security plug-in or many others.
@@ -87,7 +101,7 @@ And another utility to verify if a received password matches the hash stored.
And another one to authenticate and return a user.
```Python hl_lines="7 48 55 56 59 60 69 70 71 72 73 74 75"
-{!./src/security/tutorial004.py!}
+{!../../../docs_src/security/tutorial004.py!}
```
!!! note
@@ -101,10 +115,16 @@ Create a random secret key that will be used to sign the JWT tokens.
To generate a secure random secret key use the command:
-```bash
-openssl rand -hex 32
+
+
+```console
+$ openssl rand -hex 32
+
+09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7
```
+
+
And copy the output to the variable `SECRET_KEY` (don't use the one in the example).
Create a variable `ALGORITHM` with the algorithm used to sign the JWT token and set it to `"HS256"`.
@@ -116,7 +136,7 @@ Define a Pydantic Model that will be used in the token endpoint for the response
Create a utility function to generate a new access token.
```Python hl_lines="3 6 12 13 14 28 29 30 78 79 80 81 82 83 84 85 86"
-{!./src/security/tutorial004.py!}
+{!../../../docs_src/security/tutorial004.py!}
```
## Update the dependencies
@@ -128,7 +148,7 @@ Decode the received token, verify it, and return the current user.
If the token is invalid, return an HTTP error right away.
```Python hl_lines="89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106"
-{!./src/security/tutorial004.py!}
+{!../../../docs_src/security/tutorial004.py!}
```
## Update the `/token` *path operation*
@@ -138,7 +158,7 @@ Create a `timedelta` with the expiration time of the token.
Create a real JWT access token and return it.
```Python hl_lines="115 116 117 118 119 120 121 122 123 124 125 126 127 128"
-{!./src/security/tutorial004.py!}
+{!../../../docs_src/security/tutorial004.py!}
```
### Technical details about the JWT "subject" `sub`
diff --git a/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md
similarity index 97%
rename from docs/tutorial/security/simple-oauth2.md
rename to docs/en/docs/tutorial/security/simple-oauth2.md
index d7507a1ec8183..c95c6aa6b62c6 100644
--- a/docs/tutorial/security/simple-oauth2.md
+++ b/docs/en/docs/tutorial/security/simple-oauth2.md
@@ -1,3 +1,5 @@
+# Simple OAuth2 with Password and Bearer
+
Now let's build from the previous chapter and add the missing parts to have a complete security flow.
## Get the `username` and `password`
@@ -48,7 +50,7 @@ Now let's use the utilities provided by **FastAPI** to handle this.
First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` for the path `/token`:
```Python hl_lines="2 74"
-{!./src/security/tutorial003.py!}
+{!../../../docs_src/security/tutorial003.py!}
```
`OAuth2PasswordRequestForm` is a class dependency that declares a form body with:
@@ -89,7 +91,7 @@ If there is no such user, we return an error saying "incorrect username or passw
For the error, we use the exception `HTTPException`:
```Python hl_lines="1 75 76 77"
-{!./src/security/tutorial003.py!}
+{!../../../docs_src/security/tutorial003.py!}
```
### Check the password
@@ -117,7 +119,7 @@ If your database is stolen, the thief won't have your users' plaintext passwords
So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous).
```Python hl_lines="78 79 80 81"
-{!./src/security/tutorial003.py!}
+{!../../../docs_src/security/tutorial003.py!}
```
#### About `**user_dict`
@@ -155,7 +157,7 @@ For this simple example, we are going to just be completely insecure and return
But for now, let's focus on the specific details we need.
```Python hl_lines="83"
-{!./src/security/tutorial003.py!}
+{!../../../docs_src/security/tutorial003.py!}
```
!!! tip
@@ -180,7 +182,7 @@ Both of these dependencies will just return an HTTP error if the user doesn't ex
So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active:
```Python hl_lines="56 57 58 59 60 61 62 63 64 65 67 68 69 70 88"
-{!./src/security/tutorial003.py!}
+{!../../../docs_src/security/tutorial003.py!}
```
!!! info
diff --git a/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md
similarity index 92%
rename from docs/tutorial/sql-databases.md
rename to docs/en/docs/tutorial/sql-databases.md
index 77fd2c8f46ab5..c60eda0f80d73 100644
--- a/docs/tutorial/sql-databases.md
+++ b/docs/en/docs/tutorial/sql-databases.md
@@ -1,3 +1,5 @@
+# SQL (Relational) Databases
+
**FastAPI** doesn't require you to use a SQL (relational) database.
But you can use any relational database that you want.
@@ -85,20 +87,20 @@ Let's refer to the file `sql_app/database.py`.
### Import the SQLAlchemy parts
```Python hl_lines="1 2 3"
-{!./src/sql_databases/sql_app/database.py!}
+{!../../../docs_src/sql_databases/sql_app/database.py!}
```
### Create a database URL for SQLAlchemy
```Python hl_lines="5 6"
-{!./src/sql_databases/sql_app/database.py!}
+{!../../../docs_src/sql_databases/sql_app/database.py!}
```
In this example, we are "connecting" to a SQLite database (opening a file with the SQLite database).
-The file will be located at the same directory in the file `test.db`.
+The file will be located at the same directory in the file `sql_app.db`.
-That's why the last part is `./test.db`.
+That's why the last part is `./sql_app.db`.
If you were using a **PostgreSQL** database instead, you would just have to uncomment the line:
@@ -119,7 +121,7 @@ The first step is to create a SQLAlchemy "engine".
We will later use this `engine` in other places.
```Python hl_lines="8 9 10"
-{!./src/sql_databases/sql_app/database.py!}
+{!../../../docs_src/sql_databases/sql_app/database.py!}
```
#### Note
@@ -155,7 +157,7 @@ We will use `Session` (the one imported from SQLAlchemy) later.
To create the `SessionLocal` class, use the function `sessionmaker`:
```Python hl_lines="11"
-{!./src/sql_databases/sql_app/database.py!}
+{!../../../docs_src/sql_databases/sql_app/database.py!}
```
### Create a `Base` class
@@ -165,7 +167,7 @@ Now we will use the function `declarative_base()` that returns a class.
Later we will inherit from this class to create each of the database models or classes (the ORM models):
```Python hl_lines="13"
-{!./src/sql_databases/sql_app/database.py!}
+{!../../../docs_src/sql_databases/sql_app/database.py!}
```
## Create the database models
@@ -188,7 +190,7 @@ Create classes that inherit from it.
These classes are the SQLAlchemy models.
```Python hl_lines="4 7 8 18 19"
-{!./src/sql_databases/sql_app/models.py!}
+{!../../../docs_src/sql_databases/sql_app/models.py!}
```
The `__tablename__` attribute tells SQLAlchemy the name of the table to use in the database for each of these models.
@@ -204,7 +206,7 @@ We use `Column` from SQLAlchemy as the default value.
And we pass a SQLAlchemy class "type", as `Integer`, `String`, and `Boolean`, that defines the type in the database, as an argument.
```Python hl_lines="1 10 11 12 13 21 22 23 24"
-{!./src/sql_databases/sql_app/models.py!}
+{!../../../docs_src/sql_databases/sql_app/models.py!}
```
### Create the relationships
@@ -216,7 +218,7 @@ For this, we use `relationship` provided by SQLAlchemy ORM.
This will become, more or less, a "magic" attribute that will contain the values from other tables related to this one.
```Python hl_lines="2 15 26"
-{!./src/sql_databases/sql_app/models.py!}
+{!../../../docs_src/sql_databases/sql_app/models.py!}
```
When accessing the attribute `items` in a `User`, as in `my_user.items`, it will have a list of `Item` SQLAlchemy models (from the `items` table) that have a foreign key pointing to this record in the `users` table.
@@ -247,7 +249,7 @@ So, the user will also have a `password` when creating it.
But for security, the `password` won't be in other Pydantic *models*, for example, it won't be sent from the API when reading a user.
```Python hl_lines="3 6 7 8 11 12 23 24 27 28"
-{!./src/sql_databases/sql_app/schemas.py!}
+{!../../../docs_src/sql_databases/sql_app/schemas.py!}
```
#### SQLAlchemy style and Pydantic style
@@ -277,7 +279,7 @@ The same way, when reading a user, we can now declare that `items` will contain
Not only the IDs of those items, but all the data that we defined in the Pydantic *model* for reading items: `Item`.
```Python hl_lines="15 16 17 31 32 33 34"
-{!./src/sql_databases/sql_app/schemas.py!}
+{!../../../docs_src/sql_databases/sql_app/schemas.py!}
```
!!! tip
@@ -292,7 +294,7 @@ This the `alembic` directory in the source code.
+
### Create a dependency
!!! info
For this to work, you need to use **Python 3.7** or above, or in **Python 3.6**, install the "backports":
- ```bash
- pip install async-exit-stack async-generator
+ ```console
+ $ pip install async-exit-stack async-generator
```
This installs async-exit-stack and async-generator.
@@ -459,7 +463,7 @@ For that, we will create a new dependency with `yield`, as explained before in t
Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in a single request, and then close it once the request is finished.
```Python hl_lines="15 16 17 18 19 20"
-{!./src/sql_databases/sql_app/main.py!}
+{!../../../docs_src/sql_databases/sql_app/main.py!}
```
!!! info
@@ -476,7 +480,7 @@ And then, when using the dependency in a *path operation function*, we declare i
This will then give us better editor support inside the *path operation function*, because the editor will know that the `db` parameter is of type `Session`:
```Python hl_lines="24 32 38 47 53"
-{!./src/sql_databases/sql_app/main.py!}
+{!../../../docs_src/sql_databases/sql_app/main.py!}
```
!!! info "Technical Details"
@@ -489,7 +493,7 @@ This will then give us better editor support inside the *path operation function
Now, finally, here's the standard **FastAPI** *path operations* code.
```Python hl_lines="23 24 25 26 27 28 31 32 33 34 37 38 39 40 41 42 45 46 47 48 49 52 53 54 55"
-{!./src/sql_databases/sql_app/main.py!}
+{!../../../docs_src/sql_databases/sql_app/main.py!}
```
We are creating the database session before each request in the dependency with `yield`, and then closing it afterwards.
@@ -559,31 +563,31 @@ For example, in a background task worker with
+
+```console
+$ uvicorn sql_app.main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
+
+
And then, you can open your browser at http://127.0.0.1:8000/docs.
And you will be able to interact with your **FastAPI** application, reading data from a real database:
@@ -627,7 +638,7 @@ A "middleware" is basically a function that is always executed for each request,
The middleware we'll add (just a function) will create a new SQLAlchemy `SessionLocal` for each request, add it to the request and then close it once the request is finished.
```Python hl_lines="14 15 16 17 18 19 20 21 22"
-{!./src/sql_databases/sql_app/alt_main.py!}
+{!../../../docs_src/sql_databases/sql_app/alt_main.py!}
```
!!! info
diff --git a/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md
similarity index 92%
rename from docs/tutorial/static-files.md
rename to docs/en/docs/tutorial/static-files.md
index 1b0725291311d..dd239e6f0da57 100644
--- a/docs/tutorial/static-files.md
+++ b/docs/en/docs/tutorial/static-files.md
@@ -1,20 +1,28 @@
+# Static Files
+
You can serve static files automatically from a directory using `StaticFiles`.
## Install `aiofiles`
First you need to install `aiofiles`:
-```bash
-pip install aiofiles
+
+
+```console
+$ pip install aiofiles
+
+---> 100%
```
+
+
## Use `StaticFiles`
* Import `StaticFiles`.
* "Mount" a `StaticFiles()` instance in a specific path.
```Python hl_lines="2 6"
-{!./src/static_files/tutorial001.py!}
+{!../../../docs_src/static_files/tutorial001.py!}
```
!!! note "Technical Details"
diff --git a/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md
similarity index 81%
rename from docs/tutorial/testing.md
rename to docs/en/docs/tutorial/testing.md
index 1b1da2ab28a9f..9296a20b7b2b0 100644
--- a/docs/tutorial/testing.md
+++ b/docs/en/docs/tutorial/testing.md
@@ -1,3 +1,5 @@
+# Testing
+
Thanks to Starlette, testing **FastAPI** applications is easy and enjoyable.
It is based on Requests, so it's very familiar and intuitive.
@@ -17,7 +19,7 @@ Use the `TestClient` object the same way as you do with `requests`.
Write simple `assert` statements with the standard Python expressions that you need to check (again, standard `pytest`).
```Python hl_lines="2 12 15 16 17 18"
-{!./src/app_testing/tutorial001.py!}
+{!../../../docs_src/app_testing/tutorial001.py!}
```
!!! tip
@@ -43,7 +45,7 @@ And your **FastAPI** application might also be composed of several files/modules
Let's say you have a file `main.py` with your **FastAPI** app:
```Python
-{!./src/app_testing/main.py!}
+{!../../../docs_src/app_testing/main.py!}
```
### Testing file
@@ -51,7 +53,7 @@ Let's say you have a file `main.py` with your **FastAPI** app:
Then you could have a file `test_main.py` with your tests, and import your `app` from the `main` module (`main.py`):
```Python
-{!./src/app_testing/test_main.py!}
+{!../../../docs_src/app_testing/test_main.py!}
```
## Testing: extended example
@@ -69,7 +71,7 @@ It has a `POST` operation that could return several errors.
Both *path operations* require an `X-Token` header.
```Python
-{!./src/app_testing/main_b.py!}
+{!../../../docs_src/app_testing/main_b.py!}
```
### Extended testing file
@@ -77,7 +79,7 @@ Both *path operations* require an `X-Token` header.
You could then have a `test_main_b.py`, the same as before, with the extended tests:
```Python
-{!./src/app_testing/test_main_b.py!}
+{!../../../docs_src/app_testing/test_main_b.py!}
```
Whenever you need the client to pass information in the request and you don't know how to, you can search (Google) how to do it in `requests`.
@@ -103,14 +105,36 @@ For more information about how to pass data to the backend (using `requests` or
After that, you just need to install `pytest`:
-```bash
-pip install pytest
+
+
+```console
+$ pip install pytest
+
+---> 100%
```
+
+
It will detect the files and tests automatically, execute them, and report the results back to you.
Run the tests with:
-```bash
-pytest
+
+
+```console
+$ pytest
+
+================ test session starts ================
+platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
+rootdir: /home/user/code/superawesome-cli/app
+plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1
+collected 6 items
+
+---> 100%
+
+test_main.py ...... [100%]
+
+================= 1 passed in 0.03s =================
```
+
+
diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml
new file mode 100644
index 0000000000000..ee500318efba7
--- /dev/null
+++ b/docs/en/mkdocs.yml
@@ -0,0 +1,159 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/
+theme:
+ name: material
+ palette:
+ primary: teal
+ accent: amber
+ icon:
+ repo: fontawesome/brands/github-alt
+ logo: img/icon-white.svg
+ favicon: img/favicon.png
+ language: en
+repo_name: tiangolo/fastapi
+repo_url: https://github.com/tiangolo/fastapi
+edit_uri: ''
+google_analytics:
+- UA-133183413-1
+- auto
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - es: /es/
+ - pt: /pt/
+ - zh: /zh/
+- features.md
+- python-types.md
+- Tutorial - User Guide:
+ - tutorial/index.md
+ - tutorial/first-steps.md
+ - tutorial/path-params.md
+ - tutorial/query-params.md
+ - tutorial/body.md
+ - tutorial/query-params-str-validations.md
+ - tutorial/path-params-numeric-validations.md
+ - tutorial/body-multiple-params.md
+ - tutorial/body-fields.md
+ - tutorial/body-nested-models.md
+ - tutorial/schema-extra-example.md
+ - tutorial/extra-data-types.md
+ - tutorial/cookie-params.md
+ - tutorial/header-params.md
+ - tutorial/response-model.md
+ - tutorial/extra-models.md
+ - tutorial/response-status-code.md
+ - tutorial/request-forms.md
+ - tutorial/request-files.md
+ - tutorial/request-forms-and-files.md
+ - tutorial/handling-errors.md
+ - tutorial/path-operation-configuration.md
+ - tutorial/encoder.md
+ - tutorial/body-updates.md
+ - Dependencies:
+ - tutorial/dependencies/index.md
+ - tutorial/dependencies/classes-as-dependencies.md
+ - tutorial/dependencies/sub-dependencies.md
+ - tutorial/dependencies/dependencies-in-path-operation-decorators.md
+ - tutorial/dependencies/dependencies-with-yield.md
+ - Security:
+ - tutorial/security/index.md
+ - tutorial/security/first-steps.md
+ - tutorial/security/get-current-user.md
+ - tutorial/security/simple-oauth2.md
+ - tutorial/security/oauth2-jwt.md
+ - tutorial/middleware.md
+ - tutorial/cors.md
+ - tutorial/sql-databases.md
+ - tutorial/bigger-applications.md
+ - tutorial/background-tasks.md
+ - tutorial/metadata.md
+ - tutorial/static-files.md
+ - tutorial/testing.md
+ - tutorial/debugging.md
+- Advanced User Guide:
+ - advanced/index.md
+ - advanced/path-operation-advanced-configuration.md
+ - advanced/additional-status-codes.md
+ - advanced/response-directly.md
+ - advanced/custom-response.md
+ - advanced/additional-responses.md
+ - advanced/response-cookies.md
+ - advanced/response-headers.md
+ - advanced/response-change-status-code.md
+ - advanced/advanced-dependencies.md
+ - Advanced Security:
+ - advanced/security/index.md
+ - advanced/security/oauth2-scopes.md
+ - advanced/security/http-basic-auth.md
+ - advanced/using-request-directly.md
+ - advanced/middleware.md
+ - advanced/sql-databases-peewee.md
+ - advanced/async-sql-databases.md
+ - advanced/nosql-databases.md
+ - advanced/sub-applications.md
+ - advanced/behind-a-proxy.md
+ - advanced/templates.md
+ - advanced/graphql.md
+ - advanced/websockets.md
+ - advanced/events.md
+ - advanced/custom-request-and-route.md
+ - advanced/testing-websockets.md
+ - advanced/testing-events.md
+ - advanced/testing-dependencies.md
+ - advanced/testing-database.md
+ - advanced/settings.md
+ - advanced/conditional-openapi.md
+ - advanced/extending-openapi.md
+ - advanced/openapi-callbacks.md
+ - advanced/wsgi.md
+- async.md
+- deployment.md
+- project-generation.md
+- alternatives.md
+- history-design-future.md
+- external-links.md
+- benchmarks.md
+- help-fastapi.md
+- contributing.md
+- release-notes.md
+markdown_extensions:
+- toc:
+ permalink: true
+- markdown.extensions.codehilite:
+ guess_lang: false
+- markdown_include.include:
+ base_path: docs
+- admonition
+- codehilite
+- extra
+- pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_div_format ''
+- pymdownx.tabbed
+extra:
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/tiangolo/typer
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/tiangolo
+ - icon: fontawesome/brands/linkedin
+ link: https://www.linkedin.com/in/tiangolo
+ - icon: fontawesome/brands/dev
+ link: https://dev.to/tiangolo
+ - icon: fontawesome/brands/medium
+ link: https://medium.com/@tiangolo
+ - icon: fontawesome/solid/globe
+ link: https://tiangolo.com
+extra_css:
+- css/termynal.css
+- css/custom.css
+extra_javascript:
+- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
+- js/termynal.js
+- js/custom.js
+- js/chat.js
+- https://sidecar.gitter.im/dist/sidecar.v1.js
diff --git a/docs/es/docs/advanced/index.md b/docs/es/docs/advanced/index.md
new file mode 100644
index 0000000000000..1bee540f2bdc7
--- /dev/null
+++ b/docs/es/docs/advanced/index.md
@@ -0,0 +1,18 @@
+# Guía de Usuario Avanzada - Introducción
+
+## Características Adicionales
+
+El [Tutorial - Guía de Usuario](../tutorial/){.internal-link target=_blank} principal debe ser suficiente para darte un paseo por todas las características principales de **FastAPI**
+
+En las secciones siguientes verás otras opciones, configuraciones, y características adicionales.
+
+!!! tip
+ Las próximas secciones **no son necesariamente "avanzadas"**.
+
+ Y es posible que para tu caso, la solución se encuentre en una de estas.
+
+## Lee primero el Tutorial
+
+Puedes continuar usando la mayoría de las características de **FastAPI** con el conocimiento del [Tutorial - Guía de Usuario](../tutorial/){.internal-link target=_blank} principal.
+
+En las siguientes secciones se asume que lo has leído y conoces esas ideas principales.
diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md
new file mode 100644
index 0000000000000..99e2f8b2645e7
--- /dev/null
+++ b/docs/es/docs/async.md
@@ -0,0 +1,394 @@
+# Concurrencia y async / await
+
+Detalles sobre la sintaxis `async def` para *path operation functions* y un poco de información sobre código asíncrono, concurrencia y paralelismo.
+
+## ¿Tienes prisa?
+
+TL;DR:
+
+Si estás utilizando libraries de terceros que te dicen que las llames con `await`, del tipo:
+
+```Python
+results = await some_library()
+```
+
+Entonces declara tus *path operation functions* con `async def` de la siguiente manera:
+
+```Python hl_lines="2"
+@app.get('/')
+async def read_results():
+ results = await some_library()
+ return results
+```
+
+!!! note "Nota"
+ Solo puedes usar `await` dentro de funciones creadas con `async def`.
+
+---
+
+Si estás utilizando libraries de terceros que se comunican con algo (una base de datos, una API, el sistema de archivos, etc.) y no tienes soporte para `await` (este es el caso para la mayoría de las libraries de bases de datos), declara tus *path operation functions* de forma habitual, con solo `def`, de la siguiente manera:
+
+```Python hl_lines="2"
+@app.get('/')
+def results():
+ results = some_library()
+ return results
+```
+
+---
+
+Si tu aplicación (de alguna manera) no tiene que comunicarse con nada más y en consecuencia esperar a que responda, usa `async def`.
+
+---
+
+Si simplemente no lo sabes, usa `def` normal.
+
+---
+
+**Nota**: puedes mezclar `def` y `async def` en tus *path operation functions* tanto como lo necesites y definir cada una utilizando la mejor opción para ti. FastAPI hará lo correcto con ellos.
+
+De todos modos, en cualquiera de los casos anteriores, FastAPI seguirá funcionando de forma asíncrona y será extremadamente rápido.
+
+Pero siguiendo los pasos anteriores, FastAPI podrá hacer algunas optimizaciones de rendimiento.
+
+## Detalles Técnicos
+
+Las versiones modernas de Python tienen soporte para **"código asíncrono"** usando algo llamado **"coroutines"**, usando la sintaxis **`async` y `await`**.
+
+Veamos esa frase por partes en las secciones siguientes:
+
+* **Código Asíncrono**
+* **`async` y `await`**
+* **Coroutines**
+
+## Código Asíncrono
+
+El código asíncrono sólo significa que el lenguaje 💬 tiene una manera de decirle al sistema / programa 🤖 que, en algún momento del código, 🤖 tendrá que esperar a que *algo más* termine en otro sitio. Digamos que ese *algo más* se llama, por ejemplo, "archivo lento" 📝.
+
+Durante ese tiempo, el sistema puede hacer otras cosas, mientras "archivo lento" 📝 termina.
+
+Entonces el sistema / programa 🤖 volverá cada vez que pueda, sea porque está esperando otra vez, porque 🤖 ha terminado todo el trabajo que tenía en ese momento. Y 🤖 verá si alguna de las tareas por las que estaba esperando ha terminado, haciendo lo que tenía que hacer.
+
+Luego, 🤖 cogerá la primera tarea finalizada (digamos, nuestro "archivo lento" 📝) y continuará con lo que tenía que hacer con esa tarea.
+
+Esa "espera de otra cosa" normalmente se refiere a operaciones I/O que son relativamente "lentas" (en relación a la velocidad del procesador y memoria RAM), como por ejemplo esperar por:
+
+* los datos de cliente que se envían a través de la red
+* los datos enviados por tu programa para ser recibidos por el cliente a través de la red
+* el contenido de un archivo en disco para ser leído por el sistema y entregado al programa
+* los contenidos que tu programa da al sistema para ser escritos en disco
+* una operación relacionada con una API remota
+* una operación de base de datos
+* el retorno de resultados de una consulta de base de datos
+* etc.
+
+Como el tiempo de ejecución se consume principalmente al esperar a operaciones de I/O, las llaman operaciones "I/O bound".
+
+Se llama "asíncrono" porque el sistema / programa no tiene que estar "sincronizado" con la tarea lenta, esperando el momento exacto en que finaliza la tarea, sin hacer nada, para poder recoger el resultado de la tarea y continuar el trabajo.
+
+En lugar de eso, al ser un sistema "asíncrono", una vez finalizada, la tarea puede esperar un poco en la cola (algunos microsegundos) para que la computadora / programa termine lo que estaba haciendo, y luego vuelva para recoger los resultados y seguir trabajando con ellos.
+
+Por "síncrono" (contrario a "asíncrono") también se usa habitualmente el término "secuencial", porque el sistema / programa sigue todos los pasos secuencialmente antes de cambiar a una tarea diferente, incluso si esos pasos implican esperas.
+
+### Concurrencia y Hamburguesas
+
+El concepto de código **asíncrono** descrito anteriormente a veces también se llama **"concurrencia"**. Es diferente del **"paralelismo"**.
+
+**Concurrencia** y **paralelismo** ambos se relacionan con "cosas diferentes que suceden más o menos al mismo tiempo".
+
+Pero los detalles entre *concurrencia* y *paralelismo* son bastante diferentes.
+
+Para entender las diferencias, imagina la siguiente historia sobre hamburguesas:
+
+### Hamburguesas Concurrentes
+
+Vas con la persona que te gusta 😍 a pedir comida rápida 🍔, haces cola mientras el cajero 💁 recoge los pedidos de las personas de delante tuyo.
+
+Llega tu turno, haces tu pedido de 2 hamburguesas impresionantes para esa persona 😍 y para ti.
+
+Pagas 💸.
+
+El cajero 💁 le dice algo al chico de la cocina 👨🍳 para que sepa que tiene que preparar tus hamburguesas 🍔 (a pesar de que actualmente está preparando las de los clientes anteriores).
+
+El cajero 💁 te da el número de tu turno.
+
+Mientras esperas, vas con esa persona 😍 y eliges una mesa, se sientan y hablan durante un rato largo (ya que las hamburguesas son muy impresionantes y necesitan un rato para prepararse ✨🍔✨).
+
+Mientras te sientas en la mesa con esa persona 😍, esperando las hamburguesas 🍔, puedes disfrutar ese tiempo admirando lo increíble, inteligente, y bien que se ve ✨😍✨.
+
+Mientras esperas y hablas con esa persona 😍, de vez en cuando, verificas el número del mostrador para ver si ya es tu turno.
+
+Al final, en algún momento, llega tu turno. Vas al mostrador, coges tus hamburguesas 🍔 y vuelves a la mesa.
+
+Tú y esa persona 😍 se comen las hamburguesas 🍔 y la pasan genial ✨.
+
+---
+
+Imagina que eres el sistema / programa 🤖 en esa historia.
+
+Mientras estás en la cola, estás quieto 😴, esperando tu turno, sin hacer nada muy "productivo". Pero la línea va rápida porque el cajero 💁 solo recibe los pedidos (no los prepara), así que está bien.
+
+Luego, cuando llega tu turno, haces un trabajo "productivo" real 🤓, procesas el menú, decides lo que quieres, lo que quiere esa persona 😍, pagas 💸, verificas que das el billete o tarjeta correctos, verificas que te cobren correctamente, que el pedido tiene los artículos correctos, etc.
+
+Pero entonces, aunque aún no tienes tus hamburguesas 🍔, el trabajo hecho con el cajero 💁 está "en pausa" ⏸, porque debes esperar 🕙 a que tus hamburguesas estén listas.
+
+Pero como te alejas del mostrador y te sientas en la mesa con un número para tu turno, puedes cambiar tu atención 🔀 a esa persona 😍 y "trabajar" ⏯ 🤓 en eso. Entonces nuevamente estás haciendo algo muy "productivo" 🤓, como coquetear con esa persona 😍.
+
+Después, el 💁 cajero dice "he terminado de hacer las hamburguesas" 🍔 poniendo tu número en la pantalla del mostrador, pero no saltas al momento que el número que se muestra es el tuyo. Sabes que nadie robará tus hamburguesas 🍔 porque tienes el número de tu turno y ellos tienen el suyo.
+
+Así que esperas a que esa persona 😍 termine la historia (terminas el trabajo actual ⏯ / tarea actual que se está procesando 🤓), sonríes gentilmente y le dices que vas por las hamburguesas ⏸.
+
+Luego vas al mostrador 🔀, a la tarea inicial que ya está terminada ⏯, recoges las hamburguesas 🍔, les dices gracias y las llevas a la mesa. Eso termina esa fase / tarea de interacción con el mostrador ⏹. Eso a su vez, crea una nueva tarea, "comer hamburguesas" 🔀 ⏯, pero la anterior de "conseguir hamburguesas" está terminada ⏹.
+
+### Hamburguesas Paralelas
+
+Ahora imagina que estas no son "Hamburguesas Concurrentes" sino "Hamburguesas Paralelas".
+
+Vas con la persona que te gusta 😍 por comida rápida paralela 🍔.
+
+Haces la cola mientras varios cajeros (digamos 8) que a la vez son cocineros 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳 toman los pedidos de las personas que están delante de ti.
+
+Todos los que están antes de ti están esperando 🕙 que sus hamburguesas 🍔 estén listas antes de dejar el mostrador porque cada uno de los 8 cajeros prepara la hamburguesa de inmediato antes de recibir el siguiente pedido.
+
+Entonces finalmente es tu turno, haces tu pedido de 2 hamburguesas 🍔 impresionantes para esa persona 😍 y para ti.
+
+Pagas 💸.
+
+El cajero va a la cocina 👨🍳.
+
+Esperas, de pie frente al mostrador 🕙, para que nadie más recoja tus hamburguesas 🍔, ya que no hay números para los turnos.
+
+Como tu y esa persona 😍 están ocupados en impedir que alguien se ponga delante y recoja tus hamburguesas apenas llegan 🕙, tampoco puedes prestarle atención a esa persona 😞.
+
+Este es un trabajo "síncrono", estás "sincronizado" con el cajero / cocinero 👨🍳. Tienes que esperar y estar allí en el momento exacto en que el cajero / cocinero 👨🍳 termina las hamburguesas 🍔 y te las da, o de lo contrario, alguien más podría cogerlas.
+
+Luego, el cajero / cocinero 👨🍳 finalmente regresa con tus hamburguesas 🍔, después de mucho tiempo esperando 🕙 frente al mostrador.
+
+Cojes tus hamburguesas 🍔 y vas a la mesa con esa persona 😍.
+
+Sólo las comes y listo 🍔 ⏹.
+
+No has hablado ni coqueteado mucho, ya que has pasado la mayor parte del tiempo esperando 🕙 frente al mostrador 😞.
+
+---
+
+En este escenario de las hamburguesas paralelas, tú eres un sistema / programa 🤖 con dos procesadores (tú y la persona que te gusta 😍), ambos esperando 🕙 y dedicando su atención ⏯ a estar "esperando en el mostrador" 🕙 durante mucho tiempo.
+
+La tienda de comida rápida tiene 8 procesadores (cajeros / cocineros) 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳. Mientras que la tienda de hamburguesas concurrentes podría haber tenido solo 2 (un cajero y un cocinero) 💁 👨🍳.
+
+Pero aún así, la experiencia final no es la mejor 😞.
+
+---
+
+Esta sería la historia paralela equivalente de las hamburguesas 🍔.
+
+Para un ejemplo más "real" de ésto, imagina un banco.
+
+Hasta hace poco, la mayoría de los bancos tenían varios cajeros 👨💼👨💼👨💼👨💼 y una gran línea 🕙🕙🕙🕙🕙🕙🕙🕙.
+
+Todos los cajeros haciendo todo el trabajo con un cliente tras otro 👨💼⏯.
+
+Y tienes que esperar 🕙 en la fila durante mucho tiempo o perderás tu turno.
+
+Probablemente no querrás llevar contigo a la persona que te gusta 😍 a hacer encargos al banco 🏦.
+
+### Conclusión de las Hamburguesa
+
+En este escenario de "hamburguesas de comida rápida con tu pareja", debido a que hay mucha espera 🕙, tiene mucho más sentido tener un sistema con concurrencia ⏸🔀⏯.
+
+Este es el caso de la mayoría de las aplicaciones web.
+
+Muchos, muchos usuarios, pero el servidor está esperando 🕙 el envío de las peticiones ya que su conexión no es buena.
+
+Y luego esperando 🕙 nuevamente a que las respuestas retornen.
+
+Esta "espera" 🕙 se mide en microsegundos, pero aun así, sumando todo, al final es mucha espera.
+
+Es por eso que tiene mucho sentido usar código asíncrono ⏸🔀⏯ para las API web.
+
+La mayoría de los framework populares de Python existentes (incluidos Flask y Django) se crearon antes de que existieran las nuevas funciones asíncronas en Python. Por lo tanto, las formas en que pueden implementarse admiten la ejecución paralela y una forma más antigua de ejecución asíncrona que no es tan potente como la actual.
+
+A pesar de que la especificación principal para Python web asíncrono (ASGI) se desarrolló en Django, para agregar soporte para WebSockets.
+
+Ese tipo de asincronía es lo que hizo popular a NodeJS (aunque NodeJS no es paralelo) y esa es la fortaleza de Go como lenguaje de programación.
+
+Y ese es el mismo nivel de rendimiento que obtienes con **FastAPI**.
+
+Y como puede tener paralelismo y asincronía al mismo tiempo, obtienes un mayor rendimiento que la mayoría de los frameworks de NodeJS probados y a la par con Go, que es un lenguaje compilado más cercano a C (todo gracias Starlette).
+
+### ¿Es la concurrencia mejor que el paralelismo?
+
+¡No! Esa no es la moraleja de la historia.
+
+La concurrencia es diferente al paralelismo. Y es mejor en escenarios **específicos** que implican mucha espera. Debido a eso, generalmente es mucho mejor que el paralelismo para el desarrollo de aplicaciones web. Pero no para todo.
+
+Entonces, para explicar eso, imagina la siguiente historia corta:
+
+> Tienes que limpiar una casa grande y sucia.
+
+*Sí, esa es toda la historia*.
+
+---
+
+No hay esperas 🕙, solo hay mucho trabajo por hacer, en varios lugares de la casa.
+
+Podrías tener turnos como en el ejemplo de las hamburguesas, primero la sala de estar, luego la cocina, pero como no estás esperando nada, solo limpiando y limpiando, los turnos no afectarían nada.
+
+Tomaría la misma cantidad de tiempo terminar con o sin turnos (concurrencia) y habrías hecho la misma cantidad de trabajo.
+
+Pero en este caso, si pudieras traer a los 8 ex cajeros / cocineros / ahora limpiadores 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳, y cada uno de ellos (y tú) podría tomar una zona de la casa para limpiarla, podría hacer todo el trabajo en **paralelo**, con la ayuda adicional y terminar mucho antes.
+
+En este escenario, cada uno de los limpiadores (incluido tú) sería un procesador, haciendo su parte del trabajo.
+
+Y como la mayor parte del tiempo de ejecución lo coge el trabajo real (en lugar de esperar), y el trabajo en un sistema lo realiza una CPU , a estos problemas se les llama "CPU bond".
+
+---
+
+Ejemplos típicos de operaciones dependientes de CPU son cosas que requieren un procesamiento matemático complejo.
+
+Por ejemplo:
+
+* **Audio** o **procesamiento de imágenes**.
+* **Visión por computadora**: una imagen está compuesta de millones de píxeles, cada píxel tiene 3 valores / colores, procesamiento que normalmente requiere calcular algo en esos píxeles, todo al mismo tiempo.
+* **Machine Learning**: normalmente requiere muchas multiplicaciones de "matrices" y "vectores". Imagina en una enorme hoja de cálculo con números y tener que multiplicarlos todos al mismo tiempo.
+* **Deep Learning**: este es un subcampo de Machine Learning, por lo tanto, aplica lo mismo. Es solo que no hay una sola hoja de cálculo de números para multiplicar, sino un gran conjunto de ellas, y en muchos casos, usa un procesador especial para construir y / o usar esos modelos.
+
+### Concurrencia + Paralelismo: Web + Machine Learning
+
+Con **FastAPI** puedes aprovechar la concurrencia que es muy común para el desarrollo web (atractivo principal de NodeJS).
+
+Pero también puedes aprovechar los beneficios del paralelismo y el multiprocesamiento (tener múltiples procesos ejecutándose en paralelo) para cargas de trabajo **CPU bond** como las de los sistemas de Machine Learning.
+
+Eso, más el simple hecho de que Python es el lenguaje principal para **Data Science**, Machine Learning y especialmente Deep Learning, hacen de FastAPI una muy buena combinación para las API y aplicaciones web de Data Science / Machine Learning (entre muchas otras).
+
+Para ver cómo lograr este paralelismo en producción, consulta la sección sobre [Despliegue](deployment.md){.internal-link target=_blank}.
+
+## `async` y `await`
+
+Las versiones modernas de Python tienen una forma muy intuitiva de definir código asíncrono. Esto hace que se vea como un código "secuencial" normal y que haga la "espera" por ti en los momentos correctos.
+
+Cuando hay una operación que requerirá esperar antes de dar los resultados y tiene soporte para estas nuevas características de Python, puedes programarlo como:
+
+```Python
+burgers = await get_burgers(2)
+```
+
+La clave aquí es `await`. Eso le dice a Python que tiene que esperar ⏸ a que `get_burgers (2)` termine de hacer lo suyo 🕙 antes de almacenar los resultados en `hamburguesas`. Con eso, Python sabrá que puede ir y hacer otra cosa 🔀 ⏯ mientras tanto (como recibir otra solicitud).
+
+Para que `await` funcione, tiene que estar dentro de una función que admita esta asincronía. Para hacer eso, simplemente lo declaras con `async def`:
+
+```Python hl_lines="1"
+async def get_burgers(number: int):
+ # Do some asynchronous stuff to create the burgers
+ return burgers
+```
+
+...en vez de `def`:
+
+```Python hl_lines="2"
+# This is not asynchronous
+def get_sequential_burgers(number: int):
+ # Do some sequential stuff to create the burgers
+ return burgers
+```
+
+Con `async def`, Python sabe que, dentro de esa función, debe tener en cuenta las expresiones `wait` y que puede "pausar" ⏸ la ejecución de esa función e ir a hacer otra cosa 🔀 antes de regresar.
+
+Cuando desees llamar a una función `async def`, debes "esperarla". Entonces, esto no funcionará:
+
+```Python
+# Esto no funcionará, porque get_burgers se definió con: async def
+hamburguesas = get_burgers (2)
+```
+
+---
+
+Por lo tanto, si estás utilizando una library que te dice que puedes llamarla con `await`, debes crear las *path operation functions* que la usan con `async def`, como en:
+
+```Python hl_lines="2 3"
+@app.get('/burgers')
+async def read_burgers():
+ burgers = await get_burgers(2)
+ return burgers
+```
+
+### Más detalles técnicos
+
+Es posible que hayas notado que `await` solo se puede usar dentro de las funciones definidas con `async def`.
+
+Pero al mismo tiempo, las funciones definidas con `async def` deben ser "esperadas". Por lo tanto, las funciones con `async def` solo se pueden invocar dentro de las funciones definidas con `async def` también.
+
+Entonces, relacionado con la paradoja del huevo y la gallina, ¿cómo se llama a la primera función `async`?
+
+Si estás trabajando con **FastAPI** no tienes que preocuparte por eso, porque esa "primera" función será tu *path operation function*, y FastAPI sabrá cómo hacer lo pertinente.
+
+En el caso de que desees usar `async` / `await` sin FastAPI, revisa la documentación oficial de Python.
+
+### Otras formas de código asíncrono
+
+Este estilo de usar `async` y `await` es relativamente nuevo en el lenguaje.
+
+Pero hace que trabajar con código asíncrono sea mucho más fácil.
+
+Esta misma sintaxis (o casi idéntica) también se incluyó recientemente en las versiones modernas de JavaScript (en Browser y NodeJS).
+
+Pero antes de eso, manejar código asíncrono era bastante más complejo y difícil.
+
+En versiones anteriores de Python, podrías haber utilizado threads o Gevent. Pero el código es mucho más complejo de entender, depurar y desarrollar.
+
+En versiones anteriores de NodeJS / Browser JavaScript, habrías utilizado "callbacks". Lo que conduce a callback hell.
+
+## Coroutines
+
+**Coroutine** es un término sofisticado para referirse a la cosa devuelta por una función `async def`. Python sabe que es algo así como una función que puede iniciar y que terminará en algún momento, pero que también podría pausarse ⏸ internamente, siempre que haya un `await` dentro de ella.
+
+Pero toda esta funcionalidad de usar código asincrónico con `async` y `await` se resume muchas veces como usar "coroutines". Es comparable a la característica principal de Go, las "Goroutines".
+
+## Conclusión
+
+Veamos la misma frase de arriba:
+
+> Las versiones modernas de Python tienen soporte para **"código asíncrono"** usando algo llamado **"coroutines"**, con la sintaxis **`async` y `await`**.
+
+Eso ya debería tener más sentido ahora. ✨
+
+Todo eso es lo que impulsa FastAPI (a través de Starlette) y lo que hace que tenga un rendimiento tan impresionante.
+
+## Detalles muy técnicos
+
+!!! warning "Advertencia"
+ Probablemente puedas saltarte esto.
+
+ Estos son detalles muy técnicos de cómo **FastAPI** funciona a muy bajo nivel.
+
+ Si tienes bastante conocimiento técnico (coroutines, threads, bloqueos, etc.) y tienes curiosidad acerca de cómo FastAPI gestiona `async def` vs `def` normal, continúa.
+
+### Path operation functions
+
+Cuando declaras una *path operation function* con `def` normal en lugar de `async def`, se ejecuta en un threadpool externo que luego es "awaited", en lugar de ser llamado directamente (ya que bloquearía el servidor).
+
+Si vienes de otro framework asíncrono que no funciona de la manera descrita anteriormente y estás acostumbrado a definir *path operation functions* del tipo sólo cálculo con `def` simple para una pequeña ganancia de rendimiento (aproximadamente 100 nanosegundos), ten en cuenta que en **FastAPI** el efecto sería bastante opuesto. En estos casos, es mejor usar `async def` a menos que tus *path operation functions* usen un código que realice el bloqueo I/O.
+
+Aún así, en ambas situaciones, es probable que **FastAPI** sea [aún más rápido](/#rendimiento){.Internal-link target=_blank} que (o al menos comparable) a tu framework anterior.
+
+### Dependencias
+
+Lo mismo se aplica para las dependencias. Si una dependencia es una función estándar `def` en lugar de `async def`, se ejecuta en el threadpool externo.
+
+### Subdependencias
+
+Puedes tener múltiples dependencias y subdependencias que se requieren unas a otras (como parámetros de las definiciones de cada función), algunas de ellas pueden crearse con `async def` y otras con `def` normal. Igual todo seguiría funcionando correctamente, y las creadas con `def` normal se llamarían en un thread externo (del threadpool) en lugar de ser "awaited".
+
+### Otras funciones de utilidades
+
+Cualquier otra función de utilidad que llames directamente se puede crear con `def` o `async def` normales y FastAPI no afectará la manera en que la llames.
+
+Esto contrasta con las funciones que FastAPI llama por ti: las *path operation functions* y dependencias.
+
+Si tu función de utilidad es creada con `def` normal, se llamará directamente (tal cual la escribes en tu código), no en un threadpool, si la función se crea con `async def`, entonces debes usar `await` con esa función cuando la llamas en tu código.
+
+---
+
+Nuevamente, estos son detalles muy técnicos que probablemente sólo son útiles si los viniste a buscar expresamente.
+
+De lo contrario, la guía de la sección anterior debería ser suficiente: ¿Tienes prisa?.
diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md
new file mode 100644
index 0000000000000..6207c46ca3157
--- /dev/null
+++ b/docs/es/docs/features.md
@@ -0,0 +1,202 @@
+# Características
+
+## Características de FastAPI
+
+**FastAPI** te provee lo siguiente:
+
+### Basado en estándares abiertos
+
+* OpenAPI para la creación de APIs, incluyendo declaraciones de path operations, parámetros, body requests, seguridad, etc.
+* Documentación automática del modelo de datos con JSON Schema (dado que OpenAPI mismo está basado en JSON Schema).
+* Diseñado alrededor de estos estándares después de un estudio meticuloso. En vez de ser una capa añadida a último momento.
+* Esto también permite la **generación automática de código de cliente** para muchos lenguajes.
+
+### Documentación automática
+
+Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluídas por defecto, porque el framework está basado en OpenAPI.
+
+* Swagger UI, con exploración interactiva, llama y prueba tu API directamente desde tu navegador.
+
+
+
+* Documentación alternativa de la API con ReDoc.
+
+
+
+### Simplemente Python moderno
+
+Todo está basado en las declaraciones de tipo de **Python 3.6** estándar (gracias a Pydantic). No necesitas aprender una sintáxis nueva, solo Python moderno.
+
+Si necesitas un repaso de 2 minutos de cómo usar los tipos de Python (así no uses FastAPI) prueba el tutorial corto: [Python Types](python-types.md){.internal-link target=_blank}.
+
+Escribes Python estándar con tipos así:
+
+```Python
+from typing import List, Dict
+from datetime import date
+
+from pydantic import BaseModel
+
+# Declaras la variable como un str
+# y obtienes soporte del editor dentro de la función
+def main(user_id: str):
+ return user_id
+
+
+# Un modelo de Pydantic
+class User(BaseModel):
+ id: int
+ name: str
+ joined: date
+```
+
+Este puede ser usado como:
+
+```Python
+my_user: User = User(id=3, name="John Doe", joined="2018-07-19")
+
+second_user_data = {
+ "id": 4,
+ "name": "Mary",
+ "joined": "2018-11-30",
+}
+
+my_second_user: User = User(**second_user_data)
+```
+
+!!! info
+ `**second_user_data` significa:
+
+ Pasa las keys y los valores del dict `second_user_data` directamente como argumentos de key-value, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")`
+
+### Soporte del editor
+
+El framework fue diseñado en su totalidad para ser fácil e intuitivo de usar. Todas las decisiones fueron probadas en múltiples editores antes de comenzar el desarrollo para asegurar la mejor experiencia de desarrollo.
+
+En la última encuesta a desarrolladores de Python fue claro que la característica más usada es el "autocompletado".
+
+El framework **FastAPI** está creado para satisfacer eso. El autocompletado funciona en todas partes.
+
+No vas a tener que volver a la documentación seguido.
+
+Así es como tu editor te puede ayudar:
+
+* en Visual Studio Code:
+
+
+
+* en PyCharm:
+
+
+
+Obtendrás completado para tu código que podrías haber considerado imposible antes. Por ejemplo, el key `price` dentro del JSON body (que podría haber estado anidado) que viene de un request.
+
+Ya no pasará que escribas los nombres de key equivocados, o que tengas que revisar constantemente la documentación o desplazarte arriba y abajo para saber si usaste `username` o `user_name`.
+
+### Corto
+
+Tiene **configuraciones por defecto** razonables para todo, con configuraciones opcionales en todas partes. Todos los parámetros pueden ser ajustados para tus necesidades y las de tu API.
+
+Pero, todo **simplemente funciona** por defecto.
+
+### Validación
+
+* Validación para la mayoría (¿o todos?) los **tipos de datos** de Python incluyendo:
+ * Objetos JSON (`dict`).
+ * JSON array (`list`) definiendo tipos de ítem.
+ * Campos de texto (`str`) definiendo longitudes mínimas y máximas.
+ * Números (`int`, `float`) con valores mínimos y máximos, etc.
+
+* Validación para tipos más exóticos como:
+ * URL.
+ * Email.
+ * UUID.
+ * ...y otros.
+
+Toda la validación es manejada por **Pydantic**, que es robusto y sólidamente establecido.
+
+### Seguridad y autenticación
+
+La seguridad y la autenticación están integradas. Sin ningún compromiso con bases de datos ni modelos de datos.
+
+Todos los schemes de seguridad están definidos en OpenAPI incluyendo:
+
+* HTTP Basic.
+* **OAuth2** (también con **JWT tokens**). Prueba el tutorial en [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}.
+* API keys en:
+ * Headers.
+ * Parámetros de Query.
+ * Cookies, etc.
+
+Más todas las características de seguridad de Starlette (incluyendo **session cookies**).
+
+Todo ha sido construido como herramientas y componentes reutilizables que son fácilmente integrados con tus sistemas, almacenamiento de datos, bases de datos relacionales y no relacionales, etc.
+
+### Dependency Injection
+
+FastAPI incluye un sistema de Dependency Injection extremadamente poderoso y fácil de usar.
+
+* Inclusive las dependencias pueden tener dependencias creando una jerarquía o un **"grafo" de dependencias**.
+* Todas son **manejadas automáticamente** por el framework.
+* Todas las dependencias pueden requerir datos de los requests y aumentar las restricciones del *path operation* y la documentación automática.
+* **Validación automática** inclusive para parámetros del *path operation* definidos en las dependencias.
+* Soporte para sistemas complejos de autenticación de usuarios, **conexiones con bases de datos**, etc.
+* **Sin comprometerse** con bases de datos, frontends, etc. Pero permitiendo integración fácil con todos ellos.
+
+### "Plug-ins" ilimitados
+
+O dicho de otra manera, no hay necesidad para "plug-ins". Importa y usa el código que necesites.
+
+Cualquier integración está diseñada para que sea tan sencilla de usar (con dependencias) que puedas crear un "plug-in" para tu aplicación en dos líneas de código usando la misma estructura y sintáxis que usaste para tus *path operations*.
+
+### Probado
+
+* Cobertura de pruebas al 100%.
+* Base de código 100% anotada con tipos.
+* Usado en aplicaciones en producción.
+
+## Características de Starlette
+
+**FastAPI** está basado y es completamente compatible con Starlette. Tanto así, que cualquier código de Starlette que tengas también funcionará.
+
+`FastAPI` es realmente una sub-clase de `Starlette`. Así que, si ya conoces o usas Starlette, muchas de las características funcionarán de la misma manera.
+
+Con **FastAPI** obtienes todas las características de **Starlette** (porque FastAPI es simplemente Starlette en esteroides):
+
+* Desempeño realmente impresionante. Es uno de los frameworks de Python más rápidos, a la par con **NodeJS** y **Go**.
+* Soporte para **WebSocket**.
+* Soporte para **GraphQL**.
+* Tareas en background.
+* Eventos de startup y shutdown.
+* Cliente de pruebas construido con `requests`.
+* **CORS**, GZip, Static Files, Streaming responses.
+* Soporte para **Session and Cookie**.
+* Cobertura de pruebas al 100%.
+* Base de código 100% anotada con tipos.
+
+## Características de Pydantic
+
+**FastAPI** está basado y es completamente compatible con Pydantic. Tanto así, que cualquier código de Pydantic que tengas también funcionará.
+
+Esto incluye a librerías externas basadas en Pydantic como ORMs y ODMs para bases de datos.
+
+Esto también significa que en muchos casos puedes pasar el mismo objeto que obtuviste de un request **directamente a la base de datos**, dado que todo es validado automáticamente.
+
+Lo mismo aplica para el sentido contrario. En muchos casos puedes pasarle el objeto que obtienes de la base de datos **directamente al cliente**.
+
+Con **FastAPI** obtienes todas las características de **Pydantic** (dado que FastAPI está basado en Pydantic para todo el manejo de datos):
+
+* **Sin dificultades para entender**:
+ * No necesitas aprender un nuevo micro-lenguaje de definición de schemas.
+ * Si sabes tipos de Python, sabes cómo usar Pydantic.
+* Interactúa bien con tu **IDE/linter/cerebro**:
+ * Porque las estructuras de datos de Pydantic son solo instances de clases que tu defines, el auto-completado, el linting, mypy y tu intuición deberían funcionar bien con tus datos validados.
+* **Rápido**:
+ * En benchmarks Pydantic es más rápido que todas las otras libraries probadas.
+* Valida **estructuras complejas**:
+ * Usa modelos jerárquicos de modelos de Pydantic, `typing` de Python, `List` y `Dict`, etc.
+ * Los validadores también permiten que se definan fácil y claramente schemas complejos de datos. Estos son chequeados y documentados como JSON Schema.
+ * Puedes tener objetos de **JSON profundamente anidados** y que todos sean validados y anotados.
+* **Extensible**:
+ * Pydantic permite que se definan tipos de datos a la medida o puedes extender la validación con métodos en un modelo decorado con el decorador de validación.
+* Cobertura de pruebas al 100%.
diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md
new file mode 100644
index 0000000000000..e795f9578a7ac
--- /dev/null
+++ b/docs/es/docs/index.md
@@ -0,0 +1,442 @@
+
+
+
+
+ FastAPI framework, alto desempeño, fácil de aprender, rápido de programar, listo para producción
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+---
+
+**Documentación**: https://fastapi.tiangolo.com
+
+**Código Fuente**: https://github.com/tiangolo/fastapi
+
+---
+FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 3.6+ basado en las anotaciones de tipos estándar de Python.
+
+Sus características principales son:
+
+* **Rapidez**: Alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks de Python más rápidos](#rendimiento).
+
+* **Rápido de programar**: Incrementa la velocidad de desarrollo entre 200% y 300%. *
+* **Menos errores**: Reduce los errores humanos (de programador) aproximadamente un 40%. *
+* **Intuitivo**: Gran soporte en los editores con auto completado en todas partes. Gasta menos tiempo debugging.
+* **Fácil**: Está diseñado para ser fácil de usar y aprender. Gastando menos tiempo leyendo documentación.
+* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades con cada declaración de parámetros. Menos errores.
+* **Robusto**: Crea código listo para producción con documentación automática interactiva.
+* **Basado en estándares**: Basado y totalmente compatible con los estándares abiertos para APIs: OpenAPI (conocido previamente como Swagger) y JSON Schema.
+
+* Esta estimación está basada en pruebas con un equipo de desarrollo interno contruyendo aplicaciones listas para producción.
+
+## Opiniones
+
+"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
+
+Kabir Khan -
Microsoft (ref)
+
+---
+
+"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
+
+Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala -
Uber (ref)
+
+---
+
+"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
+
+Kevin Glisson, Marc Vilanova, Forest Monsen -
Netflix (ref)
+
+---
+
+"_I’m over the moon excited about **FastAPI**. It’s so fun!_"
+
+
+
+---
+
+"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
+
+
+
+---
+
+"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
+
+"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
+
+
+
+---
+
+## **Typer**, el FastAPI de las CLIs
+
+
+
+Si estás construyendo un app de CLI para ser usada en la terminal en vez de una API web, fíjate en **Typer**.
+
+**Typer** es el hermano menor de FastAPI. La intención es que sea el **FastAPI de las CLIs**. ⌨️ 🚀
+
+## Requisitos
+
+Python 3.6+
+
+FastAPI está sobre los hombros de gigantes:
+
+* Starlette para las partes web.
+* Pydantic para las partes de datos.
+
+## Instalación
+
+
+
+```console
+$ pip install fastapi
+
+---> 100%
+```
+
+
+
+También vas a necesitar un servidor ASGI para producción cómo Uvicorn o Hypercorn.
+
+
+
+```console
+$ pip install uvicorn
+
+---> 100%
+```
+
+
+
+## Ejemplo
+
+### Créalo
+
+* Crea un archivo `main.py` con:
+
+```Python
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: str = None):
+ return {"item_id": item_id, "q": q}
+```
+
+
+O usa async def
...
+
+Si tu código usa `async` / `await`, usa `async def`:
+
+```Python hl_lines="7 12"
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+async def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+async def read_item(item_id: int, q: str = None):
+ return {"item_id": item_id, "q": q}
+```
+
+**Nota**:
+
+Si no lo sabes, revisa la sección _"¿Con prisa?"_ sobre `async` y `await` en la documentación.
+
+
+
+### Córrelo
+
+Corre el servidor con:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+
+
+
+Sobre el comando uvicorn main:app --reload
...
+
+El comando `uvicorn main:app` se refiere a:
+
+* `main`: el archivo `main.py` (el"modulo" de Python).
+* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`.
+* `--reload`: hace que el servidor se reinicie después de cambios en el código. Esta opción solo debe ser usada en desarrollo.
+
+
+
+### Revísalo
+
+Abre tu navegador en http://127.0.0.1:8000/items/5?q=somequery.
+
+Verás la respuesta de JSON cómo:
+
+```JSON
+{"item_id": 5, "q": "somequery"}
+```
+
+Ya creaste una API que:
+
+* Recibe HTTP requests en los _paths_ `/` y `/items/{item_id}`.
+* Ambos _paths_ toman operaciones `GET` (también conocido como HTTP _methods_).
+* El _path_ `/items/{item_id}` tiene un _path parameter_ `item_id` que debería ser un `int`.
+* El _path_ `/items/{item_id}` tiene un `str` _query parameter_ `q` opcional.
+
+### Documentación interactiva de APIs
+
+Ahora ve a http://127.0.0.1:8000/docs.
+
+Verás la documentación automática e interactiva de la API (proveída por Swagger UI):
+
+
+
+### Documentación alternativa de la API
+
+Ahora, ve a http://127.0.0.1:8000/redoc.
+
+Ahora verás la documentación automática alternativa (proveída por ReDoc):
+
+
+
+## Mejora al ejemplo
+
+Ahora modifica el archivo `main.py` para recibir un body del `PUT` request.
+
+Declara el body usando las declaraciones de tipo estándares de Python gracias a Pydantic.
+
+```Python hl_lines="2 7 8 9 10 23 24 25"
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+ is_offer: bool = None
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: str = None):
+ return {"item_id": item_id, "q": q}
+
+
+@app.put("/items/{item_id}")
+def update_item(item_id: int, item: Item):
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+El servidor debería recargar automáticamente (porque añadiste `--reload` al comando `uvicorn` que está más arriba).
+
+### Mejora a la documentación interactiva de APIs
+
+Ahora ve a http://127.0.0.1:8000/docs.
+
+* La documentación interactiva de la API se actualizará automáticamente, incluyendo el nuevo body:
+
+
+
+* Haz clíck en el botón de "Try it out" que te permite llenar los parámetros e interactuar directamente con la API:
+
+
+
+* Luego haz clíck en el botón de "Execute". La interfaz de usuario se comunicará con tu API, enviará los parámetros y recibirá los resultados para mostrarlos en pantalla:
+
+
+
+### Mejora a la documentación alternativa de la API
+
+Ahora, ve a http://127.0.0.1:8000/redoc.
+
+* La documentación alternativa también reflejará el nuevo parámetro de query y el body:
+
+
+
+### Resumen
+
+En resumen, declaras los tipos de parámetros, body, etc. **una vez** como parámetros de la función.
+
+Lo haces con tipos modernos estándar de Python.
+
+No tienes que aprender una sintáxis nueva, los métodos o clases de una library específica, etc.
+
+Solo **Python 3.6+** estándar.
+
+Por ejemplo, para un `int`:
+
+```Python
+item_id: int
+```
+
+o para un modelo más complejo de `Item`:
+
+```Python
+item: Item
+```
+
+...y con esa única declaración obtienes:
+
+* Soporte del editor incluyendo:
+ * Auto completado.
+ * Anotaciones de tipos.
+* Validación de datos:
+ * Errores automáticos y claros cuándo los datos son inválidos.
+ * Validación, incluso para objetos JSON profundamente anidados.
+* Conversión de datos de input: viniendo de la red a datos y tipos de Python. Leyendo desde:
+ * JSON.
+ * Path parameters.
+ * Query parameters.
+ * Cookies.
+ * Headers.
+ * Formularios.
+ * Archivos.
+* Conversión de datos de output: convirtiendo de datos y tipos de Python a datos para la red (como JSON):
+ * Convertir tipos de Python (`str`, `int`, `float`, `bool`, `list`, etc).
+ * Objetos `datetime`.
+ * Objetos `UUID`.
+ * Modelos de bases de datos.
+ * ...y muchos más.
+* Documentación automática e interactiva incluyendo 2 interfaces de usuario alternativas:
+ * Swagger UI.
+ * ReDoc.
+
+---
+
+Volviendo al ejemplo de código anterior, **FastAPI** va a:
+
+* Validar que existe un `item_id` en el path para requests usando `GET` y `PUT`.
+* Validar que el `item_id` es del tipo `int` para requests de tipo `GET` y `PUT`.
+ * Si no lo es, el cliente verá un mensaje de error útil y claro.
+* Revisar si existe un query parameter opcional llamado `q` (cómo en `http://127.0.0.1:8000/items/foo?q=somequery`) para requests de tipo `GET`.
+ * Como el parámetro `q` fue declarado con `= None` es opcional.
+ * Sin el `None` sería obligatorio (cómo lo es el body en el caso con `PUT`).
+* Para requests de tipo `PUT` a `/items/{item_id}` leer el body como JSON:
+ * Revisar si tiene un atributo requerido `name` que debe ser un `str`.
+ * Revisar si tiene un atributo requerido `price` que debe ser un `float`.
+ * Revisar si tiene un atributo opcional `is_offer`, que debe ser un `bool`si está presente.
+ * Todo esto funcionaría para objetos JSON profundamente anidados.
+* Convertir de y a JSON automáticamente.
+* Documentar todo con OpenAPI que puede ser usado por:
+ * Sistemas de documentación interactiva.
+ * Sistemas de generación automática de código de cliente para muchos lenguajes.
+* Proveer directamente 2 interfaces de documentación web interactivas.
+
+---
+
+Hasta ahora, escasamente vimos lo básico pero ya tienes una idea de cómo funciona.
+
+Intenta cambiando la línea a:
+
+```Python
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+...de:
+
+```Python
+ ... "item_name": item.name ...
+```
+
+...a:
+
+```Python
+ ... "item_price": item.price ...
+```
+
+... y mira como el editor va a auto-completar los atributos y sabrá sus tipos:
+
+
+
+Para un ejemplo más completo que incluye más características ve el Tutorial - Guía de Usuario.
+
+**Spoiler alert**: el Tutorial - Guía de Usuario incluye:
+
+* Declaración de **parámetros** en otros lugares diferentes cómo los: **headers**, **cookies**, **formularios** y **archivos**.
+* Cómo agregar **requisitos de validación** cómo `maximum_length` o `regex`.
+* Un sistema de **Dependency Injection** poderoso y fácil de usar.
+* Seguridad y autenticación incluyendo soporte para **OAuth2** con **JWT tokens** y **HTTP Basic** auth.
+* Técnicas más avanzadas, pero igual de fáciles, para declarar **modelos de JSON profundamente anidados** (gracias a Pydantic).
+* Muchas características extra (gracias a Starlette) como:
+ * **WebSockets**
+ * **GraphQL**
+ * pruebas extremadamente fáciles con `requests` y `pytest`
+ * **CORS**
+ * **Cookie Sessions**
+ * ...y mucho más.
+
+## Rendimiento
+
+Benchmarks independientes de TechEmpower muestran que aplicaciones de **FastAPI** corriendo con Uvicorn cómo uno de los frameworks de Python más rápidos, únicamente debajo de Starlette y Uvicorn (usados internamente por FastAPI). (*)
+
+Para entender más al respecto revisa la sección Benchmarks.
+
+## Dependencias Opcionales
+
+Usadas por Pydantic:
+
+* ujson
- para "parsing" de JSON más rápido.
+* email_validator
- para validación de emails.
+
+Usados por Starlette:
+
+* requests
- Requerido si quieres usar el `TestClient`.
+* aiofiles
- Requerido si quieres usar `FileResponse` o `StaticFiles`.
+* jinja2
- Requerido si quieres usar la configuración por defecto de templates.
+* python-multipart
- Requerido si quieres dar soporte a "parsing" de formularios, con `request.form()`.
+* itsdangerous
- Requerido para dar soporte a `SessionMiddleware`.
+* pyyaml
- Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI).
+* graphene
- Requerido para dar soporte a `GraphQLApp`.
+* ujson
- Requerido si quieres usar `UJSONResponse`.
+
+Usado por FastAPI / Starlette:
+
+* uvicorn
- para el servidor que carga y sirve tu aplicación.
+* orjson
- Requerido si quieres usar `ORJSONResponse`.
+
+Puedes instalarlos con `pip install fastapi[all]`.
+
+## Licencia
+
+Este proyecto está licenciado bajo los términos de la licencia del MIT.
diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md
new file mode 100644
index 0000000000000..84a92af959a64
--- /dev/null
+++ b/docs/es/docs/python-types.md
@@ -0,0 +1,286 @@
+# Introducción a los Tipos de Python
+
+**Python 3.6+** tiene soporte para "type hints" opcionales.
+
+Estos **type hints** son una nueva sintáxis, desde Python 3.6+, que permite declarar el tipo de una variable.
+
+Usando las declaraciones de tipos para tus variables, los editores y otras herramientas pueden proveerte un soporte mejor.
+
+Este es solo un **tutorial corto** sobre los Python type hints. Solo cubre lo mínimo necesario para usarlos con **FastAPI**... realmente es muy poco lo que necesitas.
+
+Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas y beneficios.
+
+Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints.
+
+!!! note "Nota"
+ Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo.
+
+## Motivación
+
+Comencemos con un ejemplo simple:
+
+```Python
+{!../../../docs_src/python_types/tutorial001.py!}
+```
+
+Llamar este programa nos muestra el siguiente output:
+
+```
+John Doe
+```
+
+La función hace lo siguiente:
+
+* Toma un `first_name` y un `last_name`.
+* Convierte la primera letra de cada uno en una letra mayúscula con `title()`.
+* Las concatena con un espacio en la mitad.
+
+```Python hl_lines="2"
+{!../../../docs_src/python_types/tutorial001.py!}
+```
+
+### Edítalo
+
+Es un programa muy simple.
+
+Ahora, imagina que lo estás escribiendo desde ceros.
+
+En algún punto habrías comenzado con la definición de la función, tenías los parámetros listos...
+
+Pero, luego tienes que llamar "ese método que convierte la primera letra en una mayúscula".
+
+Era `upper`? O era `uppercase`? `first_uppercase`? `capitalize`?
+
+Luego lo intentas con el viejo amigo de los programadores, el autocompletado del editor.
+
+Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el autocompletado.
+
+Tristemente, no obtienes nada útil:
+
+
+
+### Añade tipos
+
+Vamos a modificar una única línea de la versión previa.
+
+Vamos a cambiar exactamente este fragmento, los parámetros de la función, de:
+
+```Python
+ first_name, last_name
+```
+
+a:
+
+```Python
+ first_name: str, last_name: str
+```
+
+Eso es todo.
+
+Esos son los "type hints":
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial002.py!}
+```
+
+No es lo mismo a declarar valores por defecto, como sería con:
+
+```Python
+ first_name="john", last_name="doe"
+```
+
+Es algo diferente.
+
+Estamos usando los dos puntos (`:`), no un símbolo de igual (`=`).
+
+Añadir los type hints normalmente no cambia lo que sucedería si ellos no estuviesen presentes.
+
+Pero ahora imagina que nuevamente estás creando la función, pero con los type hints.
+
+En el mismo punto intentas iniciar el autocompletado con `Ctrl+Space` y ves:
+
+
+
+Con esto puedes moverte hacia abajo viendo las opciones hasta que encuentras una que te suene:
+
+
+
+## Más motivación
+
+Mira esta función que ya tiene type hints:
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial003.py!}
+```
+
+Como el editor conoce el tipo de las variables no solo obtienes autocompletado, si no que también obtienes chequeo de errores:
+
+
+
+Ahora que sabes que tienes que arreglarlo convierte `age` a un string con `str(age)`:
+
+```Python hl_lines="2"
+{!../../../docs_src/python_types/tutorial004.py!}
+```
+
+## Declarando tipos
+
+Acabas de ver el lugar principal para declarar los type hints. Como parámetros de las funciones.
+
+Este es también el lugar principal en que los usarías con **FastAPI**.
+
+### Tipos simples
+
+Puedes declarar todos los tipos estándar de Python, no solamente `str`.
+
+Por ejemplo, puedes usar:
+
+* `int`
+* `float`
+* `bool`
+* `bytes`
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial005.py!}
+```
+
+### Tipos con sub-tipos
+
+Existen algunas estructuras de datos que pueden contener otros valores, como `dict`, `list`, `set` y `tuple`. Los valores internos pueden tener su propio tipo también.
+
+Para declarar esos tipos y sub-tipos puedes usar el módulo estándar de Python `typing`.
+
+Él existe específicamente para dar soporte a este tipo de type hints.
+
+#### Listas
+
+Por ejemplo, vamos a definir una variable para que sea una `list` compuesta de `str`.
+
+De `typing`, importa `List` (con una `L` mayúscula):
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial006.py!}
+```
+
+Declara la variable con la misma sintáxis de los dos puntos (`:`).
+
+Pon `List` como el tipo.
+
+Como la lista es un tipo que permite tener un "sub-tipo" pones el sub-tipo en corchetes `[]`:
+
+```Python hl_lines="4"
+{!../../../docs_src/python_types/tutorial006.py!}
+```
+
+Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`.
+
+Con esta declaración tu editor puede proveerte soporte inclusive mientras está procesando ítems de la lista.
+
+Sin tipos el autocompletado en este tipo de estructura es casi imposible de lograr:
+
+
+
+Observa que la variable `item` es unos de los elementos en la lista `items`.
+
+El editor aún sabe que es un `str` y provee soporte para ello.
+
+#### Tuples y Sets
+
+Harías lo mismo para declarar `tuple`s y `set`s:
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial007.py!}
+```
+
+Esto significa:
+
+* La variable `items_t` es un `tuple` con 3 ítems, un `int`, otro `int`, y un `str`.
+* La variable `items_s` es un `set` y cada uno de sus ítems es de tipo `bytes`.
+
+#### Diccionarios (Dicts)
+
+Para definir un `dict` le pasas 2 sub-tipos separados por comas.
+
+El primer sub-tipo es para los keys del `dict`.
+
+El segundo sub-tipo es para los valores del `dict`:
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial008.py!}
+```
+
+Esto significa:
+
+* La variable `prices` es un `dict`:
+ * Los keys de este `dict` son de tipo `str` (Digamos que son el nombre de cada ítem).
+ * Los valores de este `dict` son de tipo `float` (Digamos que son el precio de cada ítem).
+
+### Clases como tipos
+
+También puedes declarar una clase como el tipo de una variable.
+
+Digamos que tienes una clase `Person`con un nombre:
+
+```Python hl_lines="1 2 3"
+{!../../../docs_src/python_types/tutorial009.py!}
+```
+
+Entonces puedes declarar una variable que sea de tipo `Person`:
+
+```Python hl_lines="6"
+{!../../../docs_src/python_types/tutorial009.py!}
+```
+
+Una vez más tendrás todo el soporte del editor:
+
+
+
+## Modelos de Pydantic
+
+Pydantic es una library de Python para llevar a cabo validación de datos.
+
+Tú declaras la "forma" de los datos mediante clases con atributos.
+
+Cada atributo tiene un tipo.
+
+Luego creas un instance de esa clase con algunos valores y Pydantic validará los valores, los convertirá al tipo apropiado (si ese es el caso) y te dará un objeto con todos los datos.
+
+Y obtienes todo el soporte del editor con el objeto resultante.
+
+Tomado de la documentación oficial de Pydantic:
+
+```Python
+{!../../../docs_src/python_types/tutorial010.py!}
+```
+
+!!! info "Información"
+ Para aprender más sobre Pydantic mira su documentación.
+
+**FastAPI** está todo basado en Pydantic.
+
+Vas a ver mucho más de esto en práctica en el [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+
+## Type hints en **FastAPI**
+
+**FastAPI** aprovecha estos type hints para hacer varias cosas.
+
+Con **FastAPI** declaras los parámetros con type hints y obtienes:
+
+* **Soporte en el editor**.
+* **Type checks**.
+
+...y **FastAPI** usa las mismas declaraciones para:
+
+* **Definir requerimientos**: desde request path parameters, query parameters, headers, bodies, dependencies, etc.
+* **Convertir datos**: desde el request al tipo requerido.
+* **Validar datos**: viniendo de cada request:
+ * Generando **errores automáticos** devueltos al cliente cuando los datos son inválidos.
+* **Documentar** la API usando OpenAPI:
+ * que en su caso es usada por las interfaces de usuario de la documentación automática e interactiva.
+
+Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en acción en el [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+
+Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti.
+
+!!! info "Información"
+ Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`.
diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md
new file mode 100644
index 0000000000000..a4dc5fe145bcf
--- /dev/null
+++ b/docs/es/docs/tutorial/index.md
@@ -0,0 +1,80 @@
+# Tutorial - Guía de Usuario - Introducción
+
+Este tutorial te muestra cómo usar **FastAPI** con la mayoría de sus características paso a paso.
+
+Cada sección se basa gradualmente en las anteriores, pero está estructurada en temas separados, así puedes ir directamente a cualquier tema en concreto para resolver tus necesidades específicas sobre la API.
+
+También está diseñado para funcionar como una referencia futura.
+
+Para que puedas volver y ver exactamente lo que necesitas.
+
+## Ejecuta el código
+
+Todos los bloques de código se pueden copiar y usar directamente (en realidad son archivos Python probados).
+
+Para ejecutar cualquiera de los ejemplos, copia el código en un archivo llamado `main.py`, y ejecuta `uvicorn` de la siguiente manera en tu terminal:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+
+
+Se **RECOMIENDA** que escribas o copies el código, lo edites y lo ejecutes localmente.
+
+Usarlo en tu editor de código es lo que realmente te muestra los beneficios de FastAPI, al ver la poca cantidad de código que tienes que escribir, todas las verificaciones de tipo, autocompletado, etc.
+
+---
+
+## Instala FastAPI
+
+El primer paso es instalar FastAPI.
+
+Para el tutorial, es posible que quieras instalarlo con todas las dependencias y características opcionales:
+
+
+
+```console
+$ pip install fastapi[all]
+
+---> 100%
+```
+
+
+
+...eso también incluye `uvicorn` que puedes usar como el servidor que ejecuta tu código.
+
+!!! nota
+ También puedes instalarlo parte por parte.
+
+ Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción:
+
+ ```
+ pip install fastapi
+ ```
+
+ También debes instalar `uvicorn` para que funcione como tu servidor:
+
+ ```
+ pip install uvicorn
+ ```
+
+ Y lo mismo para cada una de las dependencias opcionales que quieras utilizar.
+
+## Guía Avanzada de Usuario
+
+También hay una **Guía Avanzada de Usuario** que puedes leer luego de este **Tutorial - Guía de Usuario**.
+
+La **Guía Avanzada de Usuario**, se basa en este tutorial, utiliza los mismos conceptos y enseña algunas características adicionales.
+
+Pero primero deberías leer el **Tutorial - Guía de Gsuario** (lo que estas leyendo ahora mismo).
+
+La guía esa diseñada para que puedas crear una aplicación completa con solo el **Tutorial - Guía de Usuario**, y luego extenderlo de diferentes maneras, según tus necesidades, utilizando algunas de las ideas adicionales de la **Guía Avanzada de Usuario**.
diff --git a/docs/es/mkdocs.yml b/docs/es/mkdocs.yml
new file mode 100644
index 0000000000000..1d42105307fa1
--- /dev/null
+++ b/docs/es/mkdocs.yml
@@ -0,0 +1,72 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/es/
+theme:
+ name: material
+ palette:
+ primary: teal
+ accent: amber
+ icon:
+ repo: fontawesome/brands/github-alt
+ logo: https://fastapi.tiangolo.com/img/icon-white.svg
+ favicon: https://fastapi.tiangolo.com/img/favicon.png
+ language: es
+repo_name: tiangolo/fastapi
+repo_url: https://github.com/tiangolo/fastapi
+edit_uri: ''
+google_analytics:
+- UA-133183413-1
+- auto
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - es: /es/
+ - pt: /pt/
+ - zh: /zh/
+- features.md
+- python-types.md
+- Tutorial - Guía de Usuario:
+ - tutorial/index.md
+- Guía de Usuario Avanzada:
+ - advanced/index.md
+- async.md
+markdown_extensions:
+- toc:
+ permalink: true
+- markdown.extensions.codehilite:
+ guess_lang: false
+- markdown_include.include:
+ base_path: docs
+- admonition
+- codehilite
+- extra
+- pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_div_format ''
+- pymdownx.tabbed
+extra:
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/tiangolo/typer
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/tiangolo
+ - icon: fontawesome/brands/linkedin
+ link: https://www.linkedin.com/in/tiangolo
+ - icon: fontawesome/brands/dev
+ link: https://dev.to/tiangolo
+ - icon: fontawesome/brands/medium
+ link: https://medium.com/@tiangolo
+ - icon: fontawesome/solid/globe
+ link: https://tiangolo.com
+extra_css:
+- https://fastapi.tiangolo.com/css/termynal.css
+- https://fastapi.tiangolo.com/css/custom.css
+extra_javascript:
+- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
+- https://fastapi.tiangolo.com/js/termynal.js
+- https://fastapi.tiangolo.com/js/custom.js
+- https://fastapi.tiangolo.com/js/chat.js
+- https://sidecar.gitter.im/dist/sidecar.v1.js
diff --git a/docs/js/custom.js b/docs/js/custom.js
deleted file mode 100644
index 54bd53d2700b7..0000000000000
--- a/docs/js/custom.js
+++ /dev/null
@@ -1,39 +0,0 @@
-const div = document.querySelector('.github-topic-projects')
-
-async function getDataBatch(page) {
- const response = await fetch(`https://api.github.com/search/repositories?q=topic:fastapi&per_page=100&page=${page}`, { headers: { Accept: 'application/vnd.github.mercy-preview+json' } })
- const data = await response.json()
- return data
-}
-
-async function getData() {
- let page = 1
- let data = []
- let dataBatch = await getDataBatch(page)
- data = data.concat(dataBatch.items)
- const totalCount = dataBatch.total_count
- while (data.length < totalCount) {
- page += 1
- dataBatch = await getDataBatch(page)
- data = data.concat(dataBatch.items)
- }
- return data
-}
-
-async function main() {
- if (div) {
- data = await getData()
- div.innerHTML = ''
- const ul = document.querySelector('.github-topic-projects ul')
- data.forEach(v => {
- if (v.full_name === 'tiangolo/fastapi') {
- return
- }
- const li = document.createElement('li')
- li.innerHTML = `★ ${v.stargazers_count} - ${v.full_name} by @${v.owner.login}`
- ul.append(li)
- })
- }
-}
-
-main()
diff --git a/docs/missing-translation.md b/docs/missing-translation.md
new file mode 100644
index 0000000000000..32b6016f997cd
--- /dev/null
+++ b/docs/missing-translation.md
@@ -0,0 +1,4 @@
+!!! warning
+ The current page still doesn't have a translation for this language.
+
+ But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}.
diff --git a/docs/project-generation.md b/docs/project-generation.md
deleted file mode 100644
index 4562d6204a873..0000000000000
--- a/docs/project-generation.md
+++ /dev/null
@@ -1,100 +0,0 @@
-There is a project generator that you can use to get started, with a lot of the initial set up, security, database and first API endpoints already done for you.
-
-## Full-Stack-FastAPI-PostgreSQL
-
-GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql
-
-### Full-Stack-FastAPI-PostgreSQL Features
-
-* Full **Docker** integration (Docker based).
-* Docker Swarm Mode deployment.
-* **Docker Compose** integration and optimization for local development
-* **Production ready** Python web server using Uvicorn and Gunicorn.
-* Python **FastAPI** backend:
- * **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic).
- * **Intuitive**: Great editor support. Completion everywhere. Less time debugging.
- * **Easy**: Designed to be easy to use and learn. Less time reading docs.
- * **Short**: Minimize code duplication. Multiple features from each parameter declaration.
- * **Robust**: Get production-ready code. With automatic interactive documentation.
- * **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI and JSON Schema.
- * Many other features including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc.
-* **Secure password** hashing by default.
-* **JWT token** authentication.
-* **SQLAlchemy** models (independent of Flask extensions, so they can be used with Celery workers directly).
-* Basic starting models for users (modify and remove as you need).
-* **Alembic** migrations.
-* **CORS** (Cross Origin Resource Sharing).
-* **Celery** worker that can import and use models and code from the rest of the backend selectively (you don't have to install the complete app in each worker).
-* REST backend tests based on **Pytest**, integrated with Docker, so you can test the full API interaction, independent on the database. As it runs in Docker, it can build a new data store from scratch each time (so you can use ElasticSearch, MongoDB, CouchDB, or whatever you want, and just test that the API works).
-* Easy Python integration with **Jupyter Kernels** for remote or in-Docker development with extensions like Atom Hydrogen or Visual Studio Code Jupyter.
-* **Vue** frontend:
- * Generated with Vue CLI.
- * **JWT Authentication** handling.
- * Login view.
- * After login, main dashboard view.
- * Main dashboard with user creation and edition.
- * Self user edition.
- * **Vuex**.
- * **Vue-router**.
- * **Vuetify** for beautiful material design components.
- * **TypeScript**.
- * Docker server based on **Nginx** (configured to play nicely with Vue-router).
- * Docker multi-stage building, so you don't need to save or commit compiled code.
- * Frontend tests ran at build time (can be disabled too).
- * Made as modular as possible, so it works out of the box, but you can re-generate with Vue CLI or create it as you need, and re-use what you want.
-* **PGAdmin** for PostgreSQL database, you can modify it to use PHPMyAdmin and MySQL easily.
-* **Flower** for Celery jobs monitoring.
-* Load balancing between frontend and backend with **Traefik**, so you can have both under the same domain, separated by path, but served by different containers.
-* Traefik integration, including Let's Encrypt **HTTPS** certificates automatic generation.
-* GitLab **CI** (continuous integration), including frontend and backend testing.
-
-## Full-Stack-FastAPI-Couchbase
-
-GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-### Full-Stack-FastAPI-Couchbase Features
-
-* Full **Docker** integration (Docker based).
-* Docker Swarm Mode deployment.
-* **Docker Compose** integration and optimization for local development.
-* **Production ready** Python web server using Uvicorn and Gunicorn.
-* Python **FastAPI** backend:
- * **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic).
- * **Intuitive**: Great editor support. Completion everywhere. Less time debugging.
- * **Easy**: Designed to be easy to use and learn. Less time reading docs.
- * **Short**: Minimize code duplication. Multiple features from each parameter declaration.
- * **Robust**: Get production-ready code. With automatic interactive documentation.
- * **Standards-based**: OpenAPI and JSON Schema.
- * Many other features including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc.
-* **Secure password** hashing by default.
-* **JWT token** authentication.
-* **CORS** (Cross Origin Resource Sharing).
-* **Celery** worker that can import and use code from the rest of the backend selectively (you don't have to install the complete app in each worker).
-* **NoSQL Couchbase** database that supports direct synchronization via Couchbase Sync Gateway for offline-first applications.
-* **Full Text Search** integrated, using Couchbase.
-* REST backend tests based on Pytest, integrated with Docker, so you can test the full API interaction, independent on the database. As it runs in Docker, it can build a new data store from scratch each time (so you can use ElasticSearch, MongoDB, or whatever you want, and just test that the API works).
-* Easy Python integration with **Jupyter** Kernels for remote or in-Docker development with extensions like Atom Hydrogen or Visual Studio Code Jupyter.
-* **Email notifications** for account creation and password recovery, compatible with:
- * Mailgun
- * SparkPost
- * SendGrid
- * ...any other provider that can generate standard SMTP credentials.
-* **Vue** frontend:
- * Generated with Vue CLI.
- * **JWT Authentication** handling.
- * Login view.
- * After login, main dashboard view.
- * Main dashboard with user creation and edition.
- * Self user edition.
- * **Vuex**.
- * **Vue-router**.
- * **Vuetify** for beautiful material design components.
- * **TypeScript**.
- * Docker server based on **Nginx** (configured to play nicely with Vue-router).
- * Docker multi-stage building, so you don't need to save or commit compiled code.
- * Frontend tests ran at build time (can be disabled too).
- * Made as modular as possible, so it works out of the box, but you can re-generate with Vue CLI or create it as you need, and re-use what you want.
-* **Flower** for Celery jobs monitoring.
-* Load balancing between frontend and backend with **Traefik**, so you can have both under the same domain, separated by path, but served by different containers.
-* Traefik integration, including Let's Encrypt **HTTPS** certificates automatic generation.
-* GitLab **CI** (continuous integration), including frontend and backend testing.
diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md
new file mode 100644
index 0000000000000..384eb08020d6c
--- /dev/null
+++ b/docs/pt/docs/alternatives.md
@@ -0,0 +1,413 @@
+# Alternativas, Inspiração e Comparações
+
+O que inspirou **FastAPI**, como ele se compara a outras alternativas e o que FastAPI aprendeu delas.
+
+## Introdução
+
+**FastAPI** não poderia existir se não fosse pelos trabalhos anteriores de outras pessoas.
+
+Houveram tantas ferramentas criadas que ajudaram a inspirar sua criação.
+
+Tenho evitado criar um novo framework por anos. Primeiramente tentei resolver todos os recursos cobertos pelo **FastAPI** utilizando muitos frameworks diferentes, plug-ins e ferramentas.
+
+Mas em algum ponto, não houve outra opção senão criar algo que fornecesse todos esses recursos, pegando as melhores idéias de ferramentas anteriores, e combinando eles da melhor forma possível, utilizando recursos da linguagem que não estavam disponíveis antes (_Type Hints_ no Python 3.6+).
+
+## Ferramentas anteriores
+
+### Django
+
+É o framework mais popular e largamente confiável. É utilizado para construir sistemas como o _Instagram_.
+
+É bem acoplado com banco de dados relacional (como MySQL ou PostgreSQL), então, tendo um banco de dados NoSQL (como Couchbase, MongoDB, Cassandra etc) como a principal ferramenta de armazenamento não é muito fácil.
+
+Foi criado para gerar HTML no _backend_, não para criar APIs utilizando um _frontend_ moderno (como React, Vue.js e Angular) ou por outros sistemas (como dispositivos IoT) comunicando com ele.
+
+### Django REST Framework
+
+Django REST framework foi criado para ser uma caixa de ferramentas flexível para construção de APIs web utilizando Django por baixo, para melhorar suas capacidades de API.
+
+Ele é utilizado por muitas companhias incluindo Mozilla, Red Hat e Eventbrite.
+
+Ele foi um dos primeiros exemplos de **documentação automática de API**, e essa foi especificamente uma das primeiras idéias que inspirou "a busca por" **FastAPI**.
+
+!!! note "Nota"
+ Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado.
+
+!!! check "**FastAPI** inspirado para"
+ Ter uma documentação automática da API em interface web.
+
+### Flask
+
+Flask é um "microframework", não inclui integração com banco de dados nem muitas das coisas que vêm por padrão no Django.
+
+Sua simplicidade e flexibilidade permitem fazer coisas como utilizar bancos de dados NoSQL como principal sistema de armazenamento de dados.
+
+Por ser tão simples, é relativamente intuitivo de aprender, embora a documentação esteja de forma mais técnica em alguns pontos.
+
+Ele é comumente utilizado por outras aplicações que não necessariamente precisam de banco de dados, gerenciamento de usuários, ou algum dos muitos recursos que já vem instalados no Django. Embora muitos desses recursos possam ser adicionados com plug-ins.
+
+Esse desacoplamento de partes, e sendo um "microframework" que pode ser extendido para cobrir exatamente o que é necessário era um recurso chave que eu queria manter.
+
+Dada a simplicidade do Flask, parecia uma ótima opção para construção de APIs. A próxima coisa a procurar era um "Django REST Framework" para Flask.
+
+!!! check "**FastAPI** inspirado para"
+ Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias.
+
+ Ser simples e com sistema de roteamento fácil de usar.
+
+### Requests
+
+**FastAPI** não é uma alternativa para **Requests**. O escopo deles é muito diferente.
+
+Na verdade é comum utilizar Requests *dentro* de uma aplicação FastAPI.
+
+Ainda assim, FastAPI pegou alguma inspiração do Requests.
+
+**Requests** é uma biblioteca para interagir com APIs (como um cliente), enquanto **FastAPI** é uma biblioteca para *construir* APIs (como um servidor).
+
+Eles estão, mais ou menos, em pontas opostas, um complementando o outro.
+
+Requests tem um projeto muito simples e intuitivo, fácil de usar, com padrões sensíveis. Mas ao mesmo tempo, é muito poderoso e customizável.
+
+É por isso que, como dito no site oficial:
+
+> Requests é um dos pacotes Python mais baixados de todos os tempos
+
+O jeito de usar é muito simples. Por exemplo, para fazer uma requisição `GET`, você deveria escrever:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+A contra-parte da aplicação FastAPI, *rota de operação*, poderia parecer como:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+Veja as similaridades em `requests.get(...)` e `@app.get(...)`.
+
+!!! check "**FastAPI** inspirado para"
+ * Ter uma API simples e intuitiva.
+ * Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo.
+ * Ter padrões sensíveis, mas customizações poderosas.
+
+### Swagger / OpenAPI
+
+O principal recurso que eu queria do Django REST Framework era a documentação automática da API.
+
+Então eu descobri que existia um padrão para documentar APIs, utilizando JSON (ou YAML, uma extensão do JSON) chamado Swagger.
+
+E tinha uma interface web para APIs Swagger já criada. Então, sendo capaz de gerar documentação Swagger para uma API poderia permitir utilizar essa interface web automaticamente.
+
+Em algum ponto, Swagger foi dado para a Fundação Linux, e foi renomeado OpenAPI.
+
+Isso acontece porquê quando alguém fala sobre a versão 2.0 é comum dizer "Swagger", e para a versão 3+, "OpenAPI".
+
+!!! check "**FastAPI** inspirado para"
+ Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado.
+
+ E integrar ferramentas de interface para usuários baseado nos padrões:
+
+ * Swagger UI
+ * ReDoc
+
+ Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**).
+
+### Flask REST frameworks
+
+Existem vários Flask REST frameworks, mas depois de investir tempo e trabalho investigando eles, eu descobri que muitos estão descontinuados ou abandonados, com alguns tendo questões que fizeram eles inadequados.
+
+### Marshmallow
+
+Um dos principais recursos necessários em sistemas API é "serialização" de dados, que é pegar dados do código (Python) e converter eles em alguma coisa que possa ser enviado através da rede. Por exemplo, converter um objeto contendo dados de um banco de dados em um objeto JSON. Converter objetos `datetime` em strings etc.
+
+Outro grande recurso necessário nas APIs é validação de dados, certificando que os dados são válidos, dados certos parâmetros. Por exemplo, algum campo é `int`, e não alguma string aleatória. Isso é especialmente útil para dados que estão chegando.
+
+Sem um sistema de validação de dados, você teria que realizar todas as verificações manualmente, no código.
+
+Esses recursos são o que Marshmallow foi construído para fornecer. Ele é uma ótima biblioteca, e eu já utilizei muito antes.
+
+Mas ele foi criado antes da existência do _type hints_ do Python. Então, para definir todo o _schema_ você precisa utilizar específicas ferramentas e classes fornecidas pelo Marshmallow.
+
+!!! check "**FastAPI** inspirado para"
+ Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação.
+
+### Webargs
+
+Outro grande recurso necessário pelas APIs é a análise de dados vindos de requisições.
+
+Webargs é uma ferramente feita para fornecer o que está no topo de vários frameworks, inclusive Flask.
+
+Ele utiliza Marshmallow por baixo para validação de dados. E ele foi criado pelos mesmos desenvolvedores.
+
+Ele é uma grande ferramenta e eu também a utilizei muito, antes de ter o **FastAPI**.
+
+!!! info
+ Webargs foi criado pelos mesmos desenvolvedores do Marshmallow.
+
+!!! check "**FastAPI** inspirado para"
+ Ter validação automática de dados vindos de requisições.
+
+### APISpec
+
+Marshmallow e Webargs fornecem validação, análise e serialização como plug-ins.
+
+Mas a documentação ainda está faltando. Então APISpec foi criado.
+
+APISpec tem plug-ins para muitos frameworks (e tem um plug-in para Starlette também).
+
+O jeito como ele funciona é que você escreve a definição do _schema_ usando formato YAML dentro da _docstring_ de cada função controlando uma rota.
+
+E ele gera _schemas_ OpenAPI.
+
+É assim como funciona no Flask, Starlette, Responder etc.
+
+Mas então, nós temos novamente o problema de ter uma micro-sintaxe, dentro de uma string Python (um grande YAML).
+
+O editor não poderá ajudar muito com isso. E se nós modificarmos os parâmetros dos _schemas_ do Marshmallow e esquecer de modificar também aquela _docstring_ YAML, o _schema_ gerado pode ficar obsoleto.
+
+!!! info
+ APISpec foi criado pelos mesmos desenvolvedores do Marshmallow.
+
+!!! check "**FastAPI** inspirado para"
+ Dar suporte a padrões abertos para APIs, OpenAPI.
+
+### Flask-apispec
+
+É um plug-in Flask, que amarra junto Webargs, Marshmallow e APISpec.
+
+Ele utiliza a informação do Webargs e Marshmallow para gerar automaticamente _schemas_ OpenAPI, usando APISpec.
+
+É uma grande ferramenta, mas muito subestimada. Ela deveria ser um pouco mais popular do que muitos outros plug-ins Flask. É de ser esperado que sua documentação seja bem concisa e abstrata.
+
+Isso resolveu o problema de ter que escrever YAML (outra sintaxe) dentro das _docstrings_ Python.
+
+Essa combinação de Flask, Flask-apispec com Marshmallow e Webargs foi meu _backend stack_ favorito até construir **FastAPI**.
+
+Usando essa combinação levou a criação de vários geradores Flask _full-stack_. Há muitas _stacks_ que eu (e vários times externos) estou utilizando até agora:
+
+* https://github.com/tiangolo/full-stack
+* https://github.com/tiangolo/full-stack-flask-couchbase
+* https://github.com/tiangolo/full-stack-flask-couchdb
+
+E esses mesmos geradores _full-stack_ foram a base dos [Geradores de Projetos **FastAPI**](project-generation.md){.internal-link target=_blank}.
+
+!!! info
+ Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow.
+
+!!! check "**FastAPI** inspirado para"
+ Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação.
+
+### NestJS (and Angular)
+
+NestJS, que não é nem Python, é um framework NodeJS JavaScript (TypeScript) inspirado pelo Angular.
+
+Ele alcança de uma forma similar ao que pode ser feito com o Flask-apispec.
+
+Ele tem um sistema de injeção de dependência integrado, inspirado pelo Angular dois. É necessário fazer o pré-registro dos "injetáveis" (como todos os sistemas de injeção de dependência que conheço), então, adicionando verbosidade e repetição de código.
+
+Como os parâmetros são descritos com tipos TypeScript (similar aos _type hints_ do Python), o suporte ao editor é muito bom.
+
+Mas como os dados TypeScript não são preservados após a compilação para o JavaScript, ele não pode depender dos tipos para definir a validação, serialização e documentação ao mesmo tempo. Devido a isso e a algumas decisões de projeto, para pegar a validação, serialização e geração automática do _schema_, é necessário adicionar decoradores em muitos lugares. Então, ele se torna muito verboso.
+
+Ele também não controla modelos aninhados muito bem. Então, se o corpo JSON na requisição for um objeto JSON que contém campos internos que contém objetos JSON aninhados, ele não consegue ser validado e documentado apropriadamente.
+
+!!! check "**FastAPI** inspirado para"
+ Usar tipos Python para ter um ótimo suporte do editor.
+
+ Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código.
+
+### Sanic
+
+Ele foi um dos primeiros frameworks Python extremamente rápido baseado em `asyncio`. Ele foi feito para ser muito similar ao Flask.
+
+!!! note "Detalhes técnicos"
+ Ele utiliza `uvloop` ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido.
+
+ Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos.
+
+!!! check "**FastAPI** inspirado para"
+ Achar um jeito de ter uma performance insana.
+
+ É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros).
+
+### Falcon
+
+Falcon é outro framework Python de alta performance, e é projetado para ser minimalista, e funciona como fundação de outros frameworks como Hug.
+
+Ele usa o padrão anterior para frameworks web Python (WSGI) que é síncrono, então ele não pode controlar _WebSockets_ e outros casos de uso. No entanto, ele também tem uma boa performance.
+
+Ele é projetado para ter funções que recebem dois parâmetros, uma "requisição" e uma "resposta". Então você "lê" as partes da requisição, e "escreve" partes para a resposta. Devido ao seu design, não é possível declarar parâmetros de requisição e corpos com _type hints_ Python padrão como parâmetros de funções.
+
+Então, validação de dados, serialização e documentação tem que ser feitos no código, não automaticamente. Ou eles terão que ser implementados como um framework acima do Falcon, como o Hug. Essa mesma distinção acontece em outros frameworks que são inspirados pelo design do Falcon, tendo um objeto de requisição e um objeto de resposta como parâmetros.
+
+!!! check "**FastAPI** inspirado para"
+ Achar jeitos de conseguir melhor performance.
+
+ Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta`nas funções.
+
+ Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos.
+
+### Molten
+
+Eu descobri Molten nos primeiros estágios da construção do **FastAPI**. E ele tem umas idéias bem similares:
+
+* Baseado em _type hints_ Python.
+* Validação e documentação desses tipos.
+* Sistema de injeção de dependência.
+
+Ele não utiliza validação de dados, seriallização e documentação de bibliotecas de terceiros como o Pydantic, ele tem seu prórpio. Então, essas definições de tipo de dados não podem ser reutilizados tão facilmente.
+
+Ele exige um pouco mais de verbosidade nas configurações. E como é baseado no WSGI (ao invés de ASGI), ele não é projetado para ter a vantagem da alta performance fornecida por ferramentas como Uvicorn, Starlette e Sanic.
+
+O sistema de injeção de dependência exige pré-registro das dependências e as dependências são resolvidas baseadas nos tipos declarados. Então, não é possível declarar mais do que um "componente" que fornece um certo tipo.
+
+Rotas são declaradas em um único lugar, usando funções declaradas em outros lugares (ao invés de usar decoradores que possam ser colocados diretamente acima da função que controla o _endpoint_). Isso é mais perto de como o Django faz isso do que como Flask (e Starlette) faz. Ele separa no código coisas que são relativamente amarradas.
+
+!!! check "**FastAPI** inspirado para"
+ Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes.
+
+ Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic).
+
+### Hug
+
+Hug foi um dos primeiros frameworks a implementar a declaração de tipos de parâmetros usando Python _type hints_. Isso foi uma ótima idéia que inspirou outras ferramentas a fazer o mesmo.
+
+Ele usou tipos customizados em suas declarações ao invés dos tipos padrão Python, mas mesmo assim foi um grande passo.
+
+Ele também foi um dos primeiros frameworks a gerar um _schema_ customizado declarando a API inteira em JSON.
+
+Ele não era baseado em um padrão como OpenAPI e JSON Schema. Então não poderia ter interação direta com outras ferramentas, como Swagger UI. Mas novamente, era uma idéia muito inovadora.
+
+Hug tinha um incomum, interessante recurso: usando o mesmo framework, é possível criar tanto APIs como CLIs.
+
+Como é baseado nos padrões anteriores de frameworks web síncronos (WSGI), ele não pode controlar _Websockets_ e outras coisas, embora ele ainda tenha uma alta performance também.
+
+!!! info
+ Hug foi criado por Timothy Crosley, o mesmo criador do `isort`, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python.
+
+!!! check "Idéias inspiradas para o **FastAPI**"
+ Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar.
+
+ Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente.
+
+ Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies.
+
+### APIStar (<= 0.5)
+
+Antes de decidir construir **FastAPI** eu encontrei o servidor **APIStar**. Tinha quase tudo que eu estava procurando e tinha um grande projeto.
+
+Ele foi uma das primeiras implementações de um framework usando Python _type hints_ para declarar parâmetros e requisições que eu nunca vi (antes no NestJS e Molten). Eu encontrei ele mais ou menos na mesma época que o Hug. Mas o APIStar utilizava o padrão OpenAPI.
+
+Ele tinha validação de dados automática, serialização de dados e geração de _schema_ OpenAPI baseado nos mesmos _type hints_ em vários locais.
+
+Definições de _schema_ de corpo não utilizavam os mesmos Python _type hints_ como Pydantic, ele era um pouco mais similar ao Marshmallow, então, o suporte ao editor não seria tão bom, ainda assim, APIStar era a melhor opção disponível.
+
+Ele obteve as melhores performances em testes na época (somente batido por Starlette).
+
+A princípio, ele não tinha uma interface web com documentação automática da API, mas eu sabia que poderia adicionar o Swagger UI a ele.
+
+Ele tinha um sistema de injeção de dependência. Ele exigia pré-registro dos componentes, como outras ferramentas já discutidas acima. Mas ainda era um grande recurso.
+
+Eu nunca fui capaz de usar ele num projeto inteiro, por não ter integração de segurança, então, eu não pude substituir todos os recursos que eu tinha com os geradores _full-stack_ baseados no Flask-apispec. Eu tive em minha gaveta de projetos a idéia de criar um _pull request_ adicionando essa funcionalidade.
+
+Mas então, o foco do projeto mudou.
+
+Ele não era mais um framework web API, como o criador precisava focar no Starlette.
+
+Agora APIStar é um conjunto de ferramentas para validar especificações OpenAPI, não um framework web.
+
+!!! info
+ APIStar foi criado por Tom Christie. O mesmo cara que criou:
+
+ * Django REST Framework
+ * Starlette (no qual **FastAPI** é baseado)
+ * Uvicorn (usado por Starlette e **FastAPI**)
+
+!!! check "**FastAPI** inspirado para"
+ Existir.
+
+ A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia.
+
+ E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível.
+
+ Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**.
+
+ Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima.
+
+## Usados por **FastAPI**
+
+### Pydantic
+
+Pydantic é uma biblioteca para definir validação de dados, serialização e documentação (usando JSON Schema) baseado nos Python _type hints_.
+
+Isso faz dele extremamente intuitivo.
+
+Ele é comparável ao Marshmallow. Embora ele seja mais rápido que Marshmallow em testes de performance. E ele é baseado nos mesmos Python _type hints_, o suporte ao editor é ótimo.
+
+!!! check "**FastAPI** usa isso para"
+ Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema).
+
+ **FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz.
+
+### Starlette
+
+Starlette é um framework/caixa de ferramentas ASGI peso leve, o que é ideal para construir serviços assíncronos de alta performance.
+
+Ele é muito simples e intuitivo. É projetado para ser extensível facilmente, e ter componentes modulares.
+
+Ele tem:
+
+* Performance seriamente impressionante.
+* Suporte a WebSocket.
+* Suporte a GraphQL.
+* Tarefas de processamento interno por trás dos panos.
+* Eventos de inicialização e encerramento.
+* Cliente de testes construído com requests.
+* Respostas CORS, GZip, Arquivos Estáticos, Streaming.
+* Suporte para Sessão e Cookie.
+* 100% coberto por testes.
+* Código base 100% anotado com tipagem.
+* Dependências complexas Zero.
+
+Starlette é atualmente o mais rápido framework Python testado. Somente ultrapassado pelo Uvicorn, que não é um framework, mas um servidor.
+
+Starlette fornece toda a funcionalidade básica de um microframework web.
+
+Mas ele não fornece validação de dados automática, serialização e documentação.
+
+Essa é uma das principais coisas que **FastAPI** adiciona no topo, tudo baseado em Python _type hints_ (usando Pydantic). Isso, mais o sistema de injeção de dependência, utilidades de segurança, geração de _schema_ OpenAPI, etc.
+
+!!! note "Detalhes Técnicos"
+ ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso.
+
+ No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`.
+
+!!! check "**FastAPI** usa isso para"
+ Controlar todas as partes web centrais. Adiciona recursos no topo.
+
+ A classe `FastAPI` em si herda `Starlette`.
+
+ Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides.
+
+### Uvicorn
+
+Uvicorn é um servidor ASGI peso leve, construído com uvloop e httptools.
+
+Ele não é um framework web, mas sim um servidor. Por exemplo, ele não fornece ferramentas para roteamento por rotas. Isso é algo que um framework como Starlette (ou **FastAPI**) poderia fornecer por cima.
+
+Ele é o servidor recomendado para Starlette e **FastAPI**.
+
+!!! check "**FastAPI** recomenda isso para"
+ O principal servidor web para rodar aplicações **FastAPI**.
+
+ Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono.
+
+ Verifique mais detalhes na seção [Deployment](deployment.md){.internal-link target=_blank}.
+
+## Performance e velocidade
+
+Para entender, comparar e ver a diferença entre Uvicorn, Starlette e FastAPI, verifique a seção sobre [Benchmarks](benchmarks.md){.internal-link target=_blank}.
diff --git a/docs/pt/docs/benchmarks.md b/docs/pt/docs/benchmarks.md
new file mode 100644
index 0000000000000..7f7c95ba1c65e
--- /dev/null
+++ b/docs/pt/docs/benchmarks.md
@@ -0,0 +1,34 @@
+# Comparações
+
+As comparações independentes da TechEmpower mostram as aplicações **FastAPI** rodando com Uvicorn como um dos _frameworks_ Python mais rápidos disponíveis, somente atrás dos próprios Starlette e Uvicorn (utilizados internamente pelo FastAPI). (*)
+
+Mas quando se checa _benchmarks_ e comparações você deveria ter o seguinte em mente.
+
+## Comparações e velocidade
+
+Ao verificar os _benchmarks_, é comum observar algumas ferramentas de diferentes tipos comparadas como equivalentes.
+
+Especificamente, observa-se Uvicorn, Starlette e FastAPI comparados juntos (entre muitas outras ferramentas).
+
+Quanto mais simples o problema resolvido pela ferramenta, melhor a performance que ela terá. E a maioria dos _benchmarks_ não testam as características adicionais fornecidas pela ferramenta.
+
+A hierarquia segue assim:
+
+* **Uvicorn**: um servidor ASGI
+ * **Starlette**: (utiliza Uvicorn) um _microframework web_
+ * **FastAPI**: (utiliza Starlette) um _microframework_ de API com vários recursos adicionais para construção de APIs, com validação de dados, etc.
+
+* **Uvicorn**:
+ * Terá a melhor performance, já que ele não tem muito código extra além do servidor em si.
+ * Você não conseguiria escrever uma aplicação em Uvicorn diretamente. Isso significa que seu código deveria conter, mais ou menos, todo o código fornecido pelo Starlette (ou **FastAPI**). E se você fizesse isso, sua aplicação final poderia ter a mesma sobrecarga que utilizar um _framework_ que minimiza o código e _bugs_ da sua aplicação.
+ * Se você quer fazer comparações com o Uvicorn, compare com Daphne, Hypercorn, uWSGI, etc. Servidores de Aplicação.
+* **Starlette**:
+ * Terá a melhor performance, depois do Uvicorn. De fato, Starlette utiliza Uvicorn para rodar. Então, ele provavelmente será "mais lento" que Uvicorn por ter que executar mais código.
+ * Mas ele fornece a você as ferramentas para construir aplicações _web_ simples, com roteamento baseado em caminhos, etc.
+ * Se você quer fazer comparações com o Starlette, compare com Sanic, Flask, Django, etc. _Frameworks Web_ (ou _microframeworks_).
+* **FastAPI**:
+ * Do mesmo modo que Starlette utiliza Uvicorn e não pode ser mais rápido que ele, **FastAPI** utiliza o Starlette, então não tem como ser mais rápido do que o Starlette.
+ * FastAPI fornece mais recursos acima do Starlette. Recursos que você quase sempre precisará quando construir APIs, como validação de dados e serialização. E utilizando eles, você terá uma documentação automática de graça (a documentação automática nem sequer adiciona peso para rodar as aplicações, ela é gerada na inicialização).
+ * Se você nunca utilizou FastAPI mas utilizou diretamente o Starlette (ou outra ferramenta, como Sanic, Flask, Responder, etc) você teria que implementar toda validação de dados e serialização por conta. Então, sua aplicação final poderia ainda ter a mesma sobrecarga como se fosse desenvolvida com FastAPI. Em muitos casos, a validação de dados e serialização é o maior pedaço de código escrito em aplicações.
+ * Então, ao utilizar o FastAPI você estará economizando tempo de desenvolvimento, evitará _bugs_, linhas de código, e você provavelmente terá a mesma performance (ou melhor) do que não utilizá-lo (já que você teria que implementar tudo isso em seu código).
+ * Se você quer fazer comparações com o FastAPI, compare com um _framework_ (ou conjunto de ferramentas) para aplicações _web_ que forneça validação de dados, serialização e documentação, como Flask-apispec, NestJS, Molten, etc. _Frameworks_ com validação de dados automática, serialização e documentação integradas.
diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md
new file mode 100644
index 0000000000000..221ebfbf14861
--- /dev/null
+++ b/docs/pt/docs/features.md
@@ -0,0 +1,202 @@
+# Recursos
+
+## Recursos do FastAPI
+
+**FastAPI** te oferece o seguinte:
+
+### Baseado em padrões abertos
+
+* OpenAPI para criação de APIs, incluindo declarações de operações de caminho, parâmetros, requisições de corpo, segurança etc.
+* Modelo de documentação automática com JSON Schema (já que o OpenAPI em si é baseado no JSON Schema).
+* Projetado em cima desses padrões após um estudo meticuloso, em vez de uma reflexão breve.
+* Isso também permite o uso de **geração de código do cliente** automaticamente em muitas linguagens.
+
+### Documentação automática
+
+Documentação interativa da API e navegação _web_ da interface de usuário. Como o _framework_ é baseado no OpenAPI, há várias opções, 2 incluídas por padrão.
+
+* Swagger UI, com navegação interativa, chame e teste sua API diretamente do navegador.
+
+
+
+* Documentação alternativa da API com ReDoc.
+
+
+
+### Apenas Python moderno
+
+Tudo é baseado no padrão das declarações de **tipos do Python 3.6** (graças ao Pydantic). Nenhuma sintaxe nova para aprender. Apenas o padrão moderno do Python.
+
+Se você precisa refrescar a memória rapidamente sobre como usar tipos do Python (mesmo que você não use o FastAPI), confira esse rápido tutorial: [Tipos do Python](python-types.md){.internal-link target=_blank}.
+
+Você escreve Python padrão com tipos:
+
+```Python
+from typing import List, Dict
+from datetime import date
+
+from pydantic import BaseModel
+
+# Declare uma variável como str
+# e obtenha suporte do editor dentro da função
+def main(user_id: str):
+ return user_id
+
+
+# Um modelo do Pydantic
+class User(BaseModel):
+ id: int
+ name: str
+ joined: date
+```
+
+Que então pode ser usado como:
+
+```Python
+my_user: User = User(id=3, name="John Doe", joined="2018-07-19")
+
+second_user_data = {
+ "id": 4,
+ "name": "Mary",
+ "joined": "2018-11-30",
+}
+
+my_second_user: User = User(**second_user_data)
+```
+
+!!! info
+ `**second_user_data` quer dizer:
+
+ Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")`
+
+### Suporte de editores
+
+Todo o _framework_ foi projetado para ser fácil e intuitivo de usar, todas as decisões foram testadas em vários editores antes do início do desenvolvimento, para garantir a melhor experiência de desenvolvimento.
+
+Na última pesquisa do desenvolvedor Python ficou claro que o recurso mais utilizado é o "auto completar".
+
+Todo o _framework_ **FastAPI** é feito para satisfazer isso. Auto completação funciona em todos os lugares.
+
+Você raramente precisará voltar à documentação.
+
+Aqui está como o editor poderá te ajudar:
+
+* no Visual Studio Code:
+
+
+
+* no PyCharm:
+
+
+
+Você terá completação do seu código que você poderia considerar impossível antes. Como por exemplo, a chave `price` dentro do corpo JSON (que poderia ter sido aninhado) que vem de uma requisição.
+
+Sem a necessidade de digitar nomes de chaves erroneamente, ir e voltar entre documentações, ou rolar pela página para descobrir se você utilizou `username` or `user_name`.
+
+### Breve
+
+Há **padrões** sensíveis para tudo, com configurações adicionais em todos os lugares. Todos os parâmetros podem ser regulados para fazer o que você precisa e para definir a API que você necessita.
+
+Por padrão, tudo **"simplesmente funciona"**.
+
+### Validação
+
+* Validação para a maioria dos (ou todos?) **tipos de dados** do Python, incluindo:
+ * objetos JSON (`dict`).
+ * arrays JSON (`list`), definindo tipos dos itens.
+ * campos String (`str`), definindo tamanho mínimo e máximo.
+ * Numbers (`int`, `float`) com valores mínimos e máximos, etc.
+
+* Validação de tipos mais exóticos, como:
+ * URL.
+ * Email.
+ * UUID.
+ * ...e outros.
+
+Toda a validação é controlada pelo robusto e bem estabelecido **Pydantic**.
+
+### Segurança e autenticação
+
+Segurança e autenticação integradas. Sem nenhum compromisso com bancos de dados ou modelos de dados.
+
+Todos os esquemas de seguranças definidos no OpenAPI, incluindo:
+
+* HTTP Basic.
+* **OAuth2** (também com **tokens JWT**). Confira o tutorial em [OAuth2 com JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}.
+* Chaves de API em:
+ * Headers.
+ * parâmetros da Query.
+ * Cookies etc.
+
+Além disso, todos os recursos de seguranças do Starlette (incluindo **cookies de sessão**).
+
+Tudo construído como ferramentas e componentes reutilizáveis que são fáceis de integrar com seus sistemas, armazenamento de dados, banco de dados relacionais e não-relacionais etc.
+
+### Injeção de dependência
+
+FastAPI inclui um sistema de injeção de dependência extremamente fácil de usar, mas extremamente poderoso.
+
+* Mesmo dependências podem ter dependências, criando uma hierarquia ou **"grafo" de dependências**.
+* Tudo **automaticamente controlado** pelo _framework_.
+* Todas as dependências podem pedir dados das requisições e **ampliar** as restrições e documentação automática da **operação de caminho**.
+* **Validação automática** mesmo para parâmetros da *operação de caminho* definidos em dependências.
+* Suporte para sistemas de autenticação complexos, **conexões com banco de dados** etc.
+* **Sem comprometer** os bancos de dados, _frontends_ etc. Mas fácil integração com todos eles.
+
+### "Plug-ins" ilimitados
+
+Ou, de outra forma, sem a necessidade deles, importe e use o código que precisar.
+
+Qualquer integração é projetada para ser tão simples de usar (com dependências) que você pode criar um "plug-in" para suas aplicações com 2 linhas de código usando a mesma estrutura e sintaxe para as suas *operações de caminho*.
+
+### Testado
+
+* 100% de cobertura de testes.
+* 100% do código utiliza type annotations.
+* Usado para aplicações em produção.
+
+## Recursos do Starlette
+
+**FastAPI** é totalmente compatível com (e baseado no) Starlette. Então, qualquer código adicional Starlette que você tiver, também funcionará.
+
+`FastAPI` é na verdade uma sub-classe do `Starlette`. Então, se você já conhece ou usa Starlette, a maioria das funcionalidades se comportará da mesma forma.
+
+Com **FastAPI**, você terá todos os recursos do **Starlette** (já que FastAPI é apenas um Starlette com esteróides):
+
+* Desempenho realmente impressionante. É um dos _frameworks_ Python disponíveis mais rápidos, a par com o **NodeJS** e **Go**.
+* Suporte a **WebSocket**.
+* Suporte a **GraphQL**.
+* Tarefas em processo _background_.
+* Eventos na inicialização e encerramento.
+* Cliente de testes construído sobre `requests`.
+* Respostas em **CORS**, GZip, Static Files, Streaming.
+* Suporte a **Session e Cookie**.
+* 100% de cobertura de testes.
+* 100% do código utilizando _type annotations_.
+
+## Recursos do Pydantic
+
+**FastAPI** é totalmente compatível com (e baseado no) Pydantic. Então, qualquer código Pydantic adicional que você tiver, também funcionará.
+
+Incluindo bibliotecas externas também baseadas no Pydantic, como ORMs e ODMs para bancos de dados.
+
+Isso também significa que em muitos casos você poderá passar o mesmo objeto que você receber de uma requisição **diretamente para o banco de dados**, já que tudo é validado automaticamente.
+
+O mesmo se aplica no sentido inverso, em muitos casos você poderá simplesmente passar o objeto que você recebeu do banco de dados **diretamente para o cliente**.
+
+Com **FastAPI** você terá todos os recursos do **Pydantic** (já que FastAPI utiliza o Pydantic para todo o controle dos dados):
+
+* **Sem pegadinhas**:
+ * Sem novas definições de esquema de micro-linguagem para aprender.
+ * Se você conhece os tipos do Python, você sabe como usar o Pydantic.
+* Vai bem com o/a seu/sua **IDE/linter/cérebro**:
+ * Como as estruturas de dados do Pydantic são apenas instâncias de classes que você define, a auto completação, _linting_, _mypy_ e a sua intuição devem funcionar corretamente com seus dados validados.
+* **Rápido**:
+ * em _benchmarks_, o Pydantic é mais rápido que todas as outras bibliotecas testadas.
+* Valida **estruturas complexas**:
+ * Use modelos hierárquicos do Pydantic, `List` e `Dict` do `typing` do Python, etc.
+ * Validadores permitem que esquemas de dados complexos sejam limpos e facilmente definidos, conferidos e documentados como JSON Schema.
+ * Você pode ter **JSONs aninhados** profundamente e tê-los todos validados e anotados.
+* **Extensível**:
+ * Pydantic permite que tipos de dados personalizados sejam definidos ou você pode estender a validação com métodos em um modelo decorado com seu decorador de validador.
+* 100% de cobertura de testes.
diff --git a/docs/pt/docs/history-design-future.md b/docs/pt/docs/history-design-future.md
new file mode 100644
index 0000000000000..45427ec630735
--- /dev/null
+++ b/docs/pt/docs/history-design-future.md
@@ -0,0 +1,79 @@
+# História, Design e Futuro
+
+Há algum tempo, um usuário **FastAPI** perguntou:
+
+> Qual é a história desse projeto? Parece que surgiu do nada e se tornou incrível em poucas semanas [...]
+
+Aqui está um pouco dessa história.
+
+## Alternativas
+
+Eu tenho criado APIs com requisitos complexos por vários anos (Aprendizado de Máquina, sistemas distribuídos, tarefas assíncronas, banco de dados NoSQL etc.), liderando vários times de desenvolvedores.
+
+Como parte disso, eu precisava investigar, testar e usar muitas alternativas.
+
+A história do **FastAPI** é, em grande parte, a história de seus predecessores.
+
+Como dito na seção [Alternativas](alternatives.md){.internal-link target=_blank}:
+
+
+
+**FastAPI** não existiria se não pelo trabalho anterior de outros.
+
+Há muitas ferramentas criadas antes que ajudaram a inspirar sua criação.
+
+Eu estive evitando a criação de um novo _framework_ por vários anos. Primeiro tentei resolver todas as funcionalidades cobertas por **FastAPI** usando muitos _frameworks_, _plug-ins_ e ferramentas diferentes.
+
+Mas em algum ponto, não havia outra opção senão criar algo que oferecia todas as funcionalidades, aproveitando as melhores ideias de ferramentas anteriores, e combinando-as da melhor maneira possível, usando funcionalidades da linguagem que nem estavam disponíveis antes (_type hints_ do Python 3.6+).
+
+
+
+## Investigação
+
+Ao usar todas as alternativas anteriores, eu tive a chance de aprender com todas elas, aproveitar ideias e combiná-las da melhor maneira que encontrei para mim e para os times de desenvolvedores com os quais trabalhava.
+
+Por exemplo, estava claro que idealmente ele deveria ser baseado nos _type hints_ padrões do Python.
+
+Também, a melhor abordagem era usar padrões já existentes.
+
+Então, antes mesmo de começar a codificar o **FastAPI**, eu investi vários meses estudando as especificações do OpenAPI, JSON Schema, OAuth2 etc. Entendendo suas relações, sobreposições e diferenças.
+
+## Design
+
+Eu então dediquei algum tempo projetando a "API" de desenvolvimento que eu queria como usuário (como um desenvolvedor usando o FastAPI).
+
+Eu testei várias ideias nos editores Python mais populares: PyCharm, VS Code, e editores baseados no Jedi.
+
+Pela última Pesquisa do Desenvolvedor Python, isso cobre cerca de 80% dos usuários.
+
+Isso significa que o **FastAPI** foi testado especificamente com os editores usados por 80% dos desenvolvedores Python. Como a maioria dos outros editores tendem a funcionar de forma similar, todos os seus benefícios devem funcionar para virtualmente todos os editores.
+
+Dessa forma eu pude encontrar a melhor maneira de reduzir duplicação de código o máximo possível, ter completação de texto em todos os lugares, conferência de tipos e erros etc.
+
+Tudo de uma forma que oferecesse a melhor experiência de desenvolvimento para todos os desenvolvedores.
+
+## Requisitos
+
+Após testar várias alternativas, eu decidi que usaria o **Pydantic** por suas vantagens.
+
+Então eu contribuí com ele, para deixá-lo completamente de acordo com o JSON Schema, para dar suporte a diferentes maneiras de definir declarações de restrições, e melhorar o suporte a editores (conferências de tipos, auto completações) baseado nos testes em vários editores.
+
+Durante o desenvolvimento, eu também contribuí com o **Starlette**, outro requisito chave.
+
+## Desenvolvimento
+
+Quando comecei a criar o **FastAPI** de fato, a maior parte das peças já estavam encaixadas, o design estava definido, os requisitos e ferramentas já estavam prontos, e o conhecimento sobre os padrões e especificações estavam claros e frescos.
+
+## Futuro
+
+Nesse ponto, já está claro que o **FastAPI** com suas ideias está sendo útil para muitas pessoas.
+
+Ele foi escolhido sobre outras alternativas anteriores por se adequar melhor em muitos casos.
+
+Muitos desenvolvedores e times já dependem do **FastAPI** para seus projetos (incluindo eu e meu time).
+
+Mas ainda há muitas melhorias e funcionalidades a vir.
+
+**FastAPI** tem um grande futuro à frente.
+
+E [sua ajuda](help-fastapi.md){.internal-link target=_blank} é muito bem-vinda.
diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md
new file mode 100644
index 0000000000000..10b2d6855f72f
--- /dev/null
+++ b/docs/pt/docs/index.md
@@ -0,0 +1,436 @@
+
+
+
+
+ Framework FastAPI, alta performance, fácil de aprender, fácil de codar, pronto para produção
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+---
+
+**Documentação**: https://fastapi.tiangolo.com
+
+**Código fonte**: https://github.com/tiangolo/fastapi
+
+---
+
+FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python 3.6 ou superior, baseado nos _type hints_ padrões do Python.
+
+Os recursos chave são:
+
+* **Rápido**: alta performance, equivalente a **NodeJS** e **Go** (graças ao Starlette e Pydantic). [Um dos frameworks mais rápidos disponíveis](#performance).
+* **Rápido para codar**: Aumenta a velocidade para desenvolver recursos entre 200% a 300%. *
+* **Poucos bugs**: Reduz cerca de 40% de erros iduzidos por humanos (desenvolvedores). *
+* **Intuitivo**: Grande suporte a _IDEs_. _Auto-Complete_ em todos os lugares. Menos tempo debugando.
+* **Fácil**: Projetado para ser fácil de aprender e usar. Menos tempo lendo documentação.
+* **Enxuto**: Minimize duplicação de código. Múltiplos recursos para cada declaração de parâmetro. Menos bugs.
+* **Robusto**: Tenha código pronto para produção. E com documentação interativa automática.
+* **Baseado em padrões**: Baseado em (e totalmente compatível com) os padrões abertos para APIs: OpenAPI (anteriormente conhecido como Swagger) e _JSON Schema_.
+
+* estimativas baseadas em testes realizados com equipe interna de desenvolvimento, construindo aplicações em produção.
+
+## Opiniões
+
+"*[...] Estou usando **FastAPI** muito esses dias. [...] Estou na verdade planejando utilizar ele em todos os times de **serviços _Machine Learning_ na Microsoft**. Alguns deles estão sendo integrados no _core_ do produto **Windows** e alguns produtos **Office**.*"
+
+Kabir Khan -
Microsoft (ref)
+
+---
+
+"*Estou extremamente entusiasmado com o **FastAPI**. É tão divertido!*"
+
+
+
+---
+
+"*Honestamente, o que você construiu parece super sólido e rebuscado. De muitas formas, eu queria que o **Hug** fosse assim - é realmente inspirador ver alguém que construiu ele.*"
+
+
+
+---
+
+"*Se você está procurando aprender um **_framework_ moderno** para construir aplicações _REST_, dê uma olhada no **FastAPI** [...] É rápido, fácil de usar e fácil de aprender [...]*"
+
+"*Nós trocamos nossas **APIs** por **FastAPI** [...] Acredito que vocês gostarão dele [...]*"
+
+
+
+---
+
+"*Nós adotamos a biblioteca **FastAPI** para criar um servidor **REST** que possa ser chamado para obter **predições**. [para o Ludwig]*"
+
+Piero Molino, Yaroslav Dudin e Sai Sumanth Miryala -
Uber (ref)
+
+---
+
+## **Typer**, o FastAPI das interfaces de linhas de comando
+
+
+
+Se você estiver construindo uma aplicação _CLI_ para ser utilizada em um terminal ao invés de uma aplicação web, dê uma olhada no **Typer**.
+
+**Typer** é o irmão menor do FastAPI. E seu propósito é ser o **FastAPI das _CLIs_**. ⌨️ 🚀
+
+## Requisitos
+
+Python 3.6+
+
+FastAPI está nos ombros de gigantes:
+
+* Starlette para as partes web.
+* Pydantic para a parte de dados.
+
+## Instalação
+
+
+
+```console
+$ pip install fastapi
+
+---> 100%
+```
+
+
+
+Você também precisará de um servidor ASGI para produção, tal como Uvicorn ou Hypercorn.
+
+
+
+```console
+$ pip install uvicorn
+
+---> 100%
+```
+
+
+
+## Exemplo
+
+### Crie
+
+* Crie um arquivo `main.py` com:
+
+```Python
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: str = None):
+ return {"item_id": item_id, "q": q}
+```
+
+
+Ou use async def
...
+
+Se seu código utiliza `async` / `await`, use `async def`:
+
+```Python hl_lines="7 12"
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+async def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+async def read_item(item_id: int, q: str = None):
+ return {"item_id": item_id, "q": q}
+```
+
+**Nota**:
+
+Se você não sabe, verifique a seção _"In a hurry?"_ sobre `async` e `await` nas docs.
+
+
+
+### Rode
+
+Rode o servidor com:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+
+
+
+Sobre o comando uvicorn main:app --reload
...
+
+O comando `uvicorn main:app` se refere a:
+
+* `main`: o arquivo `main.py` (o "módulo" Python).
+* `app`: o objeto criado dentro de `main.py` com a linha `app = FastAPI()`.
+* `--reload`: faz o servidor recarregar após mudanças de código. Somente faça isso para desenvolvimento.
+
+
+
+### Verifique
+
+Abra seu navegador em http://127.0.0.1:8000/items/5?q=somequery.
+
+Você verá a resposta JSON como:
+
+```JSON
+{"item_id": 5, "q": "somequery"}
+```
+
+Você acabou de criar uma API que:
+
+* Recebe requisições HTTP nas _rotas_ `/` e `/items/{item_id}`.
+* Ambas _rotas_ fazem operações `GET` (também conhecido como _métodos_ HTTP).
+* A _rota_ `/items/{item_id}` tem um _parâmetro de rota_ `item_id` que deve ser um `int`.
+* A _rota_ `/items/{item_id}` tem um _parâmetro query_ `q` `str` opcional.
+
+### Documentação Interativa da API
+
+Agora vá para http://127.0.0.1:8000/docs.
+
+Você verá a documentação automática interativa da API (fornecida por Swagger UI):
+
+
+
+### Documentação Alternativa da API
+
+E agora, vá para http://127.0.0.1:8000/redoc.
+
+Você verá a documentação automática alternativa (fornecida por ReDoc):
+
+
+
+## Evoluindo o Exemplo
+
+Agora modifique o arquivo `main.py` para receber um corpo para uma requisição `PUT`.
+
+Declare o corpo utilizando tipos padrão Python, graças ao Pydantic.
+
+```Python hl_lines="2 7 8 9 10 23 24 25"
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+ is_offer: bool = None
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: str = None):
+ return {"item_id": item_id, "q": q}
+
+
+@app.put("/items/{item_id}")
+def update_item(item_id: int, item: Item):
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+O servidor deverá recarregar automaticamente (porquê você adicionou `--reload` ao comando `uvicorn` acima).
+
+### Evoluindo a Documentação Interativa da API
+
+Agora vá para http://127.0.0.1:8000/docs.
+
+* A documentação interativa da API será automaticamente atualizada, incluindo o novo corpo:
+
+
+
+* Clique no botão "Try it out", ele permiirá que você preencha os parâmetros e interaja diretamente com a API:
+
+
+
+* Então clique no botão "Execute", a interface do usuário irá se comunicar com a API, enviar os parâmetros, pegar os resultados e mostrá-los na tela:
+
+
+
+### Evoluindo a Documentação Alternativa da API
+
+E agora, vá para http://127.0.0.1:8000/redoc.
+
+* A documentação alternativa também irá refletir o novo parâmetro da _query_ e o corpo:
+
+
+
+### Recapitulando
+
+Resumindo, você declara **uma vez** os tipos dos parâmetros, corpo etc. como parâmetros de função.
+
+Você faz com tipos padrão do Python moderno.
+
+Você não terá que aprender uma nova sintaxe, métodos ou classes de uma biblioteca específica etc.
+
+Apenas **Python 3.6+** padrão.
+
+Por exemplo, para um `int`:
+
+```Python
+item_id: int
+```
+
+ou para um modelo mais complexo, `Item`:
+
+```Python
+item: Item
+```
+
+...e com essa única declaração você tem:
+
+* Suporte ao Editor, incluindo:
+ * Completação.
+ * Verificação de tipos.
+* Validação de dados:
+ * Erros automáticos e claros quando o dado é inválido.
+ * Validação até para objetos JSON profundamente aninhados.
+* Conversão de dados de entrada: vindo da rede para dados e tipos Python. Consegue ler:
+ * JSON.
+ * Parâmetros de rota.
+ * Parâmetros de _query_ .
+ * _Cookies_.
+ * Cabeçalhos.
+ * Formulários.
+ * Arquivos.
+* Conversão de dados de saída de tipos e dados Python para dados de rede (como JSON):
+ * Converte tipos Python (`str`, `int`, `float`, `bool`, `list` etc).
+ * Objetos `datetime`.
+ * Objetos `UUID`.
+ * Modelos de Banco de Dados.
+ * ...e muito mais.
+* Documentação interativa automática da API, incluindo 2 alternativas de interface de usuário:
+ * Swagger UI.
+ * ReDoc.
+
+---
+
+Voltando ao código do exemplo anterior, **FastAPI** irá:
+
+* Validar que existe um `item_id` na rota para requisições `GET` e `PUT`.
+* Validar que `item_id` é do tipo `int` para requisições `GET` e `PUT`.
+ * Se não é validado, o cliente verá um útil, claro erro.
+* Verificar se existe um parâmetro de _query_ opcional nomeado como `q` (como em `http://127.0.0.1:8000/items/foo?q=somequery`) para requisições `GET`.
+ * Como o parâmetro `q` é declarado com `= None`, ele é opcional.
+ * Sem o `None` ele poderia ser obrigatório (como o corpo no caso de `PUT`).
+* Para requisições `PUT` para `/items/{item_id}`, lerá o corpo como JSON e:
+ * Verifica que tem um atributo obrigatório `name` que deve ser `str`.
+ * Verifica que tem um atributo obrigatório `price` que deve ser `float`.
+ * Verifica que tem an atributo opcional `is_offer`, que deve ser `bool`, se presente.
+ * Tudo isso também funciona para objetos JSON profundamente aninhados.
+* Converter de e para JSON automaticamente.
+* Documentar tudo com OpenAPI, que poderá ser usado por:
+ * Sistemas de documentação interativos.
+ * Sistemas de clientes de geração de código automáticos, para muitas linguagens.
+* Fornecer diretamente 2 interfaces _web_ de documentação interativa.
+
+---
+
+Nós arranhamos apenas a superfície, mas você já tem idéia de como tudo funciona.
+
+Experimente mudar a seguinte linha:
+
+```Python
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+...de:
+
+```Python
+ ... "item_name": item.name ...
+```
+
+...para:
+
+```Python
+ ... "item_price": item.price ...
+```
+
+...e veja como seu editor irá auto-completar os atributos e saberá os tipos:
+
+
+
+Para um exemplo mais completo incluindo mais recursos, veja Tutorial - Guia do Usuário.
+
+**Alerta de Spoiler**: o tutorial - guia do usuário inclui:
+
+* Declaração de **parâmetetros** de diferentes lugares como: **cabeçalhos**, **cookies**, **campos de formulários** e **arquivos**.
+* Como configurar **Limitações de Validação** como `maximum_length` ou `regex`.
+* Um poderoso e fácil de usar sistema de **Injeção de Dependência**.
+* Segurança e autenticação, incluindo suporte para **OAuth2** com autenticação **JWT tokens** e **HTTP Basic**.
+* Técnicas mais avançadas (mas igualmente fáceis) para declaração de **modelos JSON profundamente aninhados** (graças ao Pydantic).
+* Muitos recursos extras (graças ao Starlette) como:
+ * **WebSockets**
+ * **GraphQL**
+ * testes extrememamente fáceis baseados em `requests` e `pytest`
+ * **CORS**
+ * **Cookie Sessions**
+ * ...e mais.
+
+## Performance
+
+Testes de performance da _Independent TechEmpower_ mostram aplicações **FastAPI** rodando sob Uvicorn como um dos _frameworks_ Python mais rápidos disponíveis, somente atrás de Starlette e Uvicorn (utilizados internamente pelo FastAPI). (*)
+
+Para entender mais sobre performance, veja a seção Benchmarks.
+
+## Dependências opcionais
+
+Usados por Pydantic:
+
+* ujson
- para JSON mais rápido "parsing".
+* email_validator
- para validação de email.
+
+Usados por Starlette:
+
+* requests
- Necessário se você quiser utilizar o `TestClient`.
+* aiofiles
- Necessário se você quiser utilizar o `FileResponse` ou `StaticFiles`.
+* jinja2
- Necessário se você quiser utilizar a configuração padrão de templates.
+* python-multipart
- Necessário se você quiser suporte com "parsing" de formulário, com `request.form()`.
+* itsdangerous
- Necessário para suporte a `SessionMiddleware`.
+* pyyaml
- Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI).
+* graphene
- Necessário para suporte a `GraphQLApp`.
+* ujson
- Necessário se você quer utilizar `UJSONResponse`.
+
+Usados por FastAPI / Starlette:
+
+* uvicorn
- para o servidor que carrega e serve sua aplicação.
+* orjson
- Necessário se você quer utilizar `ORJSONResponse`.
+
+Você pode instalar todas essas dependências com `pip install fastapi[all]`.
+
+## Licença
+
+Esse projeto é licenciado sob os termos da licença MIT.
diff --git a/docs/pt/docs/tutorial/index.md b/docs/pt/docs/tutorial/index.md
new file mode 100644
index 0000000000000..8470927a7ffd2
--- /dev/null
+++ b/docs/pt/docs/tutorial/index.md
@@ -0,0 +1,80 @@
+# Tutorial - Guia de Usuário - Introdução
+
+Esse tutorial mostra como usar o **FastAPI** com a maior parte de seus recursos, passo a passo.
+
+Cada seção constrói, gradualmente, sobre as anteriores, mas sua estrutura são tópicos separados, para que você possa ir a qualquer um específico e resolver suas necessidades específicas de API.
+
+Ele também foi feito como referência futura.
+
+Então você poderá voltar e ver exatamente o que precisar.
+
+## Rode o código
+
+Todos os blocos de código podem ser copiados e utilizados diretamente (eles são, na verdade, arquivos Python testados).
+
+Para rodar qualquer um dos exemplos, copie o codigo para um arquivo `main.py`, e inicie o `uvivorn` com:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+
+
+É **ALTAMENTE recomendado** que você escreva ou copie o código, edite-o e rode-o localmente.
+
+Usá-lo em seu editor é o que realmente te mostra os benefícios do FastAPI, ver quão pouco código você tem que escrever, todas as conferências de tipo, auto completações etc.
+
+---
+
+## Instale o FastAPI
+
+O primeiro passo é instalar o FastAPI.
+
+Para o tutorial, você deve querer instalá-lo com todas as dependências e recursos opicionais.
+
+
+
+```console
+$ pip install fastapi[all]
+
+---> 100%
+```
+
+
+
+...isso também inclui o `uvicorn`, que você pode usar como o servidor que rodará seu código.
+
+!!! nota
+ Você também pode instalar parte por parte.
+
+ Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção:
+
+ ```
+ pip install fastapi
+ ```
+
+ Também instale o `uvicorn` para funcionar como servidor:
+
+ ```
+ pip install uvicorn
+ ```
+
+ E o mesmo para cada dependência opcional que você quiser usar.
+
+## Guia Avançado de Usuário
+
+Há também um **Guia Avançado de Usuário** que você pode ler após esse **Tutorial - Guia de Usuário**.
+
+O **Guia Avançado de Usuário** constrói sobre esse, usa os mesmos conceitos e te ensina alguns recursos extras.
+
+Mas você deveria ler primeiro o **Tutorial - Guia de Usuário** (que você está lendo agora).
+
+Ele foi projetado para que você possa construir uma aplicação completa com apenas o **Tutorial - Guia de Usuário**, e então estendê-la de diferentes formas, dependendo das suas necessidades, usando algumas ideias adicionais do **Guia Avançado de Usuário**.
diff --git a/docs/pt/mkdocs.yml b/docs/pt/mkdocs.yml
new file mode 100644
index 0000000000000..105f7e6f32fbb
--- /dev/null
+++ b/docs/pt/mkdocs.yml
@@ -0,0 +1,71 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/pt/
+theme:
+ name: material
+ palette:
+ primary: teal
+ accent: amber
+ icon:
+ repo: fontawesome/brands/github-alt
+ logo: https://fastapi.tiangolo.com/img/icon-white.svg
+ favicon: https://fastapi.tiangolo.com/img/favicon.png
+ language: pt
+repo_name: tiangolo/fastapi
+repo_url: https://github.com/tiangolo/fastapi
+edit_uri: ''
+google_analytics:
+- UA-133183413-1
+- auto
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - es: /es/
+ - pt: /pt/
+ - zh: /zh/
+- features.md
+- Tutorial - Guia de Usuário:
+ - tutorial/index.md
+- alternatives.md
+- history-design-future.md
+- benchmarks.md
+markdown_extensions:
+- toc:
+ permalink: true
+- markdown.extensions.codehilite:
+ guess_lang: false
+- markdown_include.include:
+ base_path: docs
+- admonition
+- codehilite
+- extra
+- pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_div_format ''
+- pymdownx.tabbed
+extra:
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/tiangolo/typer
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/tiangolo
+ - icon: fontawesome/brands/linkedin
+ link: https://www.linkedin.com/in/tiangolo
+ - icon: fontawesome/brands/dev
+ link: https://dev.to/tiangolo
+ - icon: fontawesome/brands/medium
+ link: https://medium.com/@tiangolo
+ - icon: fontawesome/solid/globe
+ link: https://tiangolo.com
+extra_css:
+- https://fastapi.tiangolo.com/css/termynal.css
+- https://fastapi.tiangolo.com/css/custom.css
+extra_javascript:
+- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
+- https://fastapi.tiangolo.com/js/termynal.js
+- https://fastapi.tiangolo.com/js/custom.js
+- https://fastapi.tiangolo.com/js/chat.js
+- https://sidecar.gitter.im/dist/sidecar.v1.js
diff --git a/docs/src/python_types/tutorial007.py b/docs/src/python_types/tutorial007.py
deleted file mode 100644
index d2c6cb6e7f29a..0000000000000
--- a/docs/src/python_types/tutorial007.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from typing import Set, Tuple
-
-
-def process_items(items_t: Tuple[int], items_s: Set[bytes]):
- return items_t, items_s
diff --git a/docs/zh/docs/deployment.md b/docs/zh/docs/deployment.md
new file mode 100644
index 0000000000000..6eb25824a7c42
--- /dev/null
+++ b/docs/zh/docs/deployment.md
@@ -0,0 +1,390 @@
+# 部署
+
+部署 **FastAPI** 应用相对比较简单。
+
+根据特定使用情况和使用工具有几种不同的部署方式。
+
+接下来的章节,你将了解到一些关于部署方式的内容。
+
+## FastAPI 版本
+
+许多应用和系统已经在生产环境使用 **FastAPI**。其测试覆盖率保持在 100%。但该项目仍在快速开发。
+
+我们会经常加入新的功能,定期错误修复,同时也在不断的优化项目代码。
+
+这也是为什么当前版本仍然是 `0.x.x`,我们以此表明每个版本都可能有重大改变。
+
+现在就可以使用 **FastAPI** 创建生产应用(你可能已经使用一段时间了)。你只需要确保使用的版本和代码其他部分能够正常兼容。
+
+### 指定你的 `FastAPI` 版本
+
+你应该做的第一件事情,是为你正在使用的 **FastAPI** 指定一个能够正确运行你的应用的最新版本。
+
+例如,假设你的应用中正在使用版本 `0.45.0`。
+
+如果你使用 `requirements.txt` 文件,你可以这样指定版本:
+
+```txt
+fastapi==0.45.0
+```
+
+这表明你将使用 `0.45.0` 版本的 `FastAPI`。
+
+或者你也可以这样指定:
+
+```txt
+fastapi>=0.45.0,<0.46.0
+```
+
+这表明你将使用 `0.45.0` 及以上,但低于 `0.46.0` 的版本,例如,`0.45.2` 依然可以接受。
+
+如果使用其他工具管理你的安装,比如 Poetry,Pipenv,或者其他工具,它们都有各自指定包的版本的方式。
+
+### 可用版本
+
+你可以在 [发行说明](release-notes.md){.internal-link target=_blank} 中查看可用的版本(比如:检查最新版本是什么)。
+
+
+### 关于版本
+
+FastAPI 遵循语义版本控制约定,`1.0.0` 以下的任何版本都可能加入重大变更。
+
+FastAPI 也遵循这样的约定:任何 ”PATCH“ 版本变更都是用来修复 bug 和向下兼容的变更。
+
+!!! tip
+ "PATCH" 是指版本号的最后一个数字,例如,在 `0.2.3` 中,PATCH 版本是 `3`。
+
+所以,你应该像这样指定版本:
+
+```txt
+fastapi>=0.45.0,<0.46.0
+```
+
+不兼容变更和新特性在 "MINOR" 版本中添加。
+
+!!! tip
+ "MINOR" 是版本号中间的数字,例如,在 `0.2.3` 中,MINOR 版本是 `2`。
+
+### 更新 FaseAPI 版本
+
+你应该为你的应用添加测试。
+
+使用 **FastAPI** 测试应用非常容易(归功于 Starlette),查看文档:[测试](tutorial/testing.md){.internal-link target=_blank}
+
+有了测试之后,就可以将 **FastAPI** 更新到最近的一个的版本,然后通过运行测试来确定你所有代码都可以正确工作。
+
+如果一切正常,或者做了必要的修改之后,所有的测试都通过了,就可以把 `FastAPI` 版本指定为那个比较新的版本了。
+
+### 关于 Starlette
+
+不要指定 `starlette` 的版本。
+
+不同版本的 **FastAPI** 会使用特定版本的 Starlette。
+
+所以你只要让 **FastAPI** 自行选择正确的 Starlette 版本。
+
+### 关于 Pydantic
+
+Pydantic 自身的测试中已经包含了 **FastAPI** 的测试,所以最新版本的 Pydantic (`1.0.0` 以上版本)总是兼容 **FastAPI**。
+
+你可以指定 Pydantic 为任意一个高于 `1.0.0` 且低于的 `2.0.0` 的版本。
+
+例如:
+
+```txt
+pydantic>=1.2.0,<2.0.0
+```
+
+## Docker
+
+这部分,你将通过指引和链接了解到:
+
+* 如何将你的 **FastAPI** 应用制作成最高性能的 **Docker** 映像/容器。约需五分钟。
+* (可选)理解作为一个开发者需要知道的 HTTPS 相关知识。
+* 使用自动化 HTTPS 设置一个 Docker Swarm 模式的集群,即使是在一个简单的 $5 USD/month 的服务器上。约需要 20 分钟。
+* 使用 Docker Swarm 集群以及 HTTP 等等,生成和部署一个完整的 **FastAPI** 应用。约需 10 分钟。
+
+可以使用 **Docker** 进行部署。它具有安全性、可复制性、开发简单性等优点。
+
+如果你正在使用 Docker,你可以使用官方 Docker 镜像:
+
+### tiangolo/uvicorn-gunicorn-fastapi
+
+该映像包含一个「自动调优」的机制,这样就可以仅仅添加代码就能自动获得超高性能,而不用做出牺牲。
+
+不过你仍然可以使用环境变量或配置文件更改和更新所有配置。
+
+!!! tip
+ 查看全部配置和选项,请移步 Docker 镜像页面:tiangolo/uvicorn-gunicorn-fastapi。
+
+### 创建 `Dockerfile`
+
+* 进入你的项目目录。
+* 使用如下命令创建一个 `Dockerfile`:
+
+```Dockerfile
+FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
+
+COPY ./app /app
+```
+
+#### 大型应用
+
+如果遵循创建 [多文件大型应用](tutorial/bigger-applications.md){.internal-link target=_blank} 的章节,你的 Dockerfile 可能看起来是这样:
+
+```Dockerfile
+FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
+
+COPY ./app /app/app
+```
+
+#### 树莓派以及其他架构
+
+如果你在树莓派或者任何其他架构中运行 Docker,可以基于 Python 基础镜像(它是多架构的)从头创建一个 `Dockerfile` 并单独使用 Uvicorn。
+
+这种情况下,你的 `Dockerfile` 可能是这样的:
+
+```Dockerfile
+FROM python:3.7
+
+RUN pip install fastapi uvicorn
+
+EXPOSE 80
+
+COPY ./app /app
+
+CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
+```
+
+### 创建 **FastAPI** 代码
+
+* 创建一个 `app` 目录并进入该目录。
+* 创建一个 `main.py` 文件,内容如下:
+
+```Python
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: str = None):
+ return {"item_id": item_id, "q": q}
+```
+
+* 现在目录结构如下:
+
+```
+.
+├── app
+│ └── main.py
+└── Dockerfile
+```
+
+### 构建 Docker 镜像
+
+* 进入项目目录(在 `Dockerfile` 所在的位置,包含 `app` 目录)
+* 构建 **FastAPI** 镜像
+
+
+
+```console
+$ docker build -t myimage .
+
+---> 100%
+```
+
+
+
+### 启动 Docker 容器
+
+* 运行基于你的镜像容器:
+
+
+
+```console
+$ docker run -d --name mycontainer -p 80:80 myimage
+```
+
+
+
+现在你在 Docker 容器中有了一个根据当前服务器(和CPU核心的数量)自动优化好的 FastAPI 服务器。
+
+### 检查一下
+
+你应该能够在 Docker 容器的 URL 中检查它。例如:http://192.168.99.100/items/5?q=somequery 或者 http://127.0.0.1/items/5?q=somequery (或者类似的,使用Docker主机)。
+
+得到类似的输出:
+
+```JSON
+{"item_id": 5, "q": "somequery"}
+```
+
+### 交互式 API 文档
+
+现在可以访问 http://192.168.99.100/docs 或者 http://127.0.0.1/docs (或者类似的,使用Docker主机)。
+
+你会看到一个交互式的 API 文档 (由 Swagger UI 提供):
+
+
+
+### 可选的 API 文档
+
+你也可以访问 http://192.168.99.100/redoc 或者 http://127.0.0.1/redoc (或者类似的,使用Docker主机)。
+
+你将看到一个可选的自动化文档(由 ReDoc 提供)
+
+
+
+## HTTPS
+
+### 关于 HTTPS
+
+我们当然可以假设 HTTPS 只是某种「启用」或「不启用」的东西。
+
+但是事实比这要复杂的多。
+
+!!! tip
+ 如果你着急或者不关心这部分内容,请继续按照下一章节的步骤进行配置。
+
+要从用户的角度学习 HTTPS 的基础,请移步 https://howhttps.works/。
+
+从开发人员的角度来看,在考虑 HTTPS 时有以下几点需要注意:
+
+* 对 HTTPS 来说,服务端需要有第三方生成的「证书」。
+ * 实际上这些证书是从第三方获取的,而非「生成」的。
+* 证书有生命周期。
+ * 证书会过期。
+ * 证书过期之后需要更新,重新从第三方获取。
+* 连接的加密发生在 TCP 层。
+ * TCP 层在 HTTP 之下一层。
+ * 因此,证书和加密处理在 HTTP 之前完成。
+* TCP 不知道「域名」,只知道 IP 地址。
+ * 指定域名的请求信息在 HTTP 的数据中。
+* HTTPS 证书「认证」某个特定域名,但是协议和加密在知道要处理哪个域名之前就已经在 TCP 层发生了。
+* 默认情况下,一个 IP 地址仅有一个 HTTPS 证书。
+ * 无论你的服务器大小,都是如此。
+ * 但是对此有解决办法。
+* TSL 协议(在 TCP 层处理加密的协议,发生在 HTTP 之前)有一个扩展,叫 SNI。
+ * SNI 扩展允许一个服务器(一个 IP 地址)有多个 HTTPS 证书,为多个 HTTPS 域名/应用 提供服务。
+ * 要使其工作,服务器运行的单一组件(程序)监听公网 IP 地址,所有 HTTPS 证书必须都在该服务器上。
+* 在获得一个安全连接之后,通讯协议仍然是 HTTP。
+ * HTTP 内容是加密的,即使这些内容使用 HTTP 协议传输。
+
+常见的做法是在服务器(机器,主机等等)上运行一个程序或 HTTP 服务来管理所有的 HTTPS 部分:将解密后的 HTTP 请求发送给在同一服务器运行的真实 HTTP 应用(在这里是 **FastAPI** 应用),从应用获得 HTTP 响应,使用适当的证书加密响应然后使用 HTTPS 将其发回客户端。这个服务器常被称作 TLS 终止代理。
+
+
+### Let's Encrypt
+
+在 Let's Encrypt 出现之前,这些 HTTPS 证书由受信任的第三方出售。
+
+获取这些证书的过程曾经非常繁琐,需要大量的文书工作,而且证书的价格也相当昂贵。
+
+但是紧接着 Let's Encrypt 被创造了。
+
+这是一个来自 Linux 基金会的项目。它以自动化的方式免费提供 HTTPS 证书。这些证书使用所有的标准加密措施,且证书生命周期很短(大约 3 个月),正是由于它们生命周期的减短,所以实际上安全性更高。
+
+对域名进行安全验证并自动生成证书。同时也允许自动更新这些证书。
+
+其想法是自动获取和更新这些证书,这样就可以一直免费获得安全的 HTTPS。
+
+### Traefik
+
+Traefik 是一个高性能的反向代理/负载均衡器。它能够完成「TLS 终止代理」的工作(其他特性除外)。
+
+Traefik 集成了 Let's Encrypt,所以能够处理全部 HTTPS 的部分,包括证书获取与更新。
+
+Traefik 也集成了 Docker,所以你也可以在每个应用的配置中声明你的域名并可以让它读取这些配置,生成 HTTPS 证书并自动将 HTTPS 提供给你的应用程序,而你不需要对其配置进行任何更改。
+
+---
+
+有了这些信息和工具,就可以进入下一节把所有内容结合到一起。
+
+## 通过 Traefik 和 HTTPS 搭建 Docker Swarm mode 集群
+
+通过一个主要的 Traefik 来处理 HTTPS (包括证书获取和更新),大约 20 分钟就可以搭建好一个 Docker Swarm mode 集群。
+
+借助 Docker Swarm mode,你可以从单个机器的集群开始(甚至可以是 $5 /月的服务器),然后你可以根据需要添加更多的服务器来进行扩展。
+
+要使用 Traefik 和 HTTPS 处理来构建 Docker Swarm Mode 集群,请遵循以下指南:
+
+### Docker Swarm Mode 和 Traefik 用于 HTTPS 集群
+
+### 部署一个 FastAPI 应用
+
+部署的最简单方式就是使用 [**FastAPI** 项目生成器](project-generation.md){.internal-link target=_blank}。
+
+它被设计成与上述带有 Traefik 和 HTTPS 的 Docker Swarm 集群整合到一起。
+
+你可以在大概两分钟内生成一个项目。
+
+生成的项目有部署说明,需要再花两分钟部署项目。
+
+## 或者,不用 Docker 部署 **FastAPI**
+
+你也可以不用 Docker 直接部署 **FastAPI**。
+
+只需要安装一个兼容 ASGI 的服务器:
+
+* Uvicorn,一个轻量快速的 ASGI 服务器,基于 uvloop 和 httptools 构建。
+
+
+
+```console
+$ pip install uvicorn
+
+---> 100%
+```
+
+
+
+* Hypercorn,一个也兼容 HTTP/2 的 ASGI 服务器。
+
+
+
+```console
+$ pip install hypercorn
+
+---> 100%
+```
+
+
+
+...或者任何其他的 ASGI 服务器。
+
+然后使用教程中同样的方式来运行你的应用,但是不要加 `--reload` 选项,比如:
+
+
+
+```console
+$ uvicorn main:app --host 0.0.0.0 --port 80
+
+INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)
+```
+
+
+
+或者使用 Hypercorn:
+
+
+
+```console
+$ hypercorn main:app --bind 0.0.0.0:80
+
+Running on 0.0.0.0:8080 over http (CTRL + C to quit)
+```
+
+
+
+也许你想编写一些工具来确保它停止时会自动重启。
+
+或者安装 Gunicorn 并 将其作为 Uvicorn 的管理器,或者使用多职程(worker)的 Hypercorn。
+
+或者保证精确调整职程的数量等等。
+
+但是如果你正做这些,你可能只需要使用 Docker 镜像就能够自动做到这些了。
diff --git a/docs/zh/docs/features.md b/docs/zh/docs/features.md
new file mode 100644
index 0000000000000..964a2fd7ece60
--- /dev/null
+++ b/docs/zh/docs/features.md
@@ -0,0 +1,206 @@
+# 特性
+
+## FastAPI 特性
+
+**FastAPI** 提供了以下内容:
+
+### 基于开放标准
+
+
+* 用于创建 API 的 OpenAPI 包含了路径操作,请求参数,请求体,安全性等的声明。
+* 使用 JSON Schema (因为 OpenAPI 本身就是基于 JSON Schema 的)自动生成数据模型文档。
+* 经过了缜密的研究后围绕这些标准而设计。并非狗尾续貂。
+* 这也允许了在很多语言中自动**生成客户端代码**。
+
+### 自动生成文档
+
+交互式 API 文档以及具探索性 web 界面。因为该框架是基于 OpenAPI,所以有很多可选项,FastAPI 默认自带两个交互式 API 文档。
+
+* Swagger UI,可交互式操作,能在浏览器中直接调用和测试你的 API 。
+
+
+
+* 另外的 API 文档:ReDoc
+
+
+
+### 更主流的 Python
+
+全部都基于标准的 **Python 3.6 类型**声明(感谢 Pydantic )。没有新的语法需要学习。只需要标准的 Python 。
+
+如果你需要2分钟来学习如何使用 Python 类型(即使你不使用 FastAPI ),看看这个简短的教程:[Python Types](python-types.md){.internal-link target=_blank}。
+
+编写带有类型标注的标准 Python:
+
+```Python
+from typing import List, Dict
+from datetime import date
+
+from pydantic import BaseModel
+
+# Declare a variable as a str
+# and get editor support inside the function
+def main(user_id: str):
+ return user_id
+
+
+# A Pydantic model
+class User(BaseModel):
+ id: int
+ name: str
+ joined: date
+```
+
+可以像这样来使用:
+
+```Python
+my_user: User = User(id=3, name="John Doe", joined="2018-07-19")
+
+second_user_data = {
+ "id": 4,
+ "name": "Mary",
+ "joined": "2018-11-30",
+}
+
+my_second_user: User = User(**second_user_data)
+```
+
+
+!!! info
+ `**second_user_data` 意思是:
+
+ 直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")`
+
+### 编辑器支持
+
+整个框架都被设计得易于使用且直观,所有的决定都在开发之前就在多个编辑器上进行了测试,来确保最佳的开发体验。
+
+在最近的 Python 开发者调查中,我们能看到 被使用最多的功能是"自动补全"。
+
+整个 **FastAPI** 框架就是基于这一点的。任何地方都可以进行自动补全。
+
+你几乎不需要经常回来看文档。
+
+在这里,你的编辑器可能会这样帮助你:
+
+* Visual Studio Code 中:
+
+
+
+* PyCharm 中:
+
+
+
+你将能进行代码补全,这是在之前你可能曾认为不可能的事。例如,在来自请求 JSON 体(可能是嵌套的)中的键 `price`。
+
+不会再输错键名,来回翻看文档,或者来回滚动寻找你最后使用的 `username` 或者 `user_name` 。
+
+
+
+### 简洁
+
+任何类型都有合理的**默认值**,任何和地方都有可选配置。所有的参数被微调,来满足你的需求,定义成你需要的 API。
+
+但是默认情况下,一切都能**“顺利工作”**。
+
+### 验证
+
+* 校验大部分(甚至所有?)的 Python **数据类型**,包括:
+ * JSON 对象 (`dict`).
+ * JSON 数组 (`list`) 定义成员类型。
+ * 字符串 (`str`) 字段, 定义最小或最大长度。
+ * 数字 (`int`, `float`) 有最大值和最小值, 等等。
+
+* 校验外来类型, 比如:
+ * URL.
+ * Email.
+ * UUID.
+ * ...及其他.
+
+所有的校验都由完善且强大的 **Pydantic** 处理。
+
+### 安全性及身份验证
+
+集成了安全性和身份认证。杜绝数据库或者数据模型的渗透风险。
+
+OpenAPI 中定义的安全模式,包括:
+
+* HTTP 基本认证。
+* **OAuth2** (也使用 **JWT tokens**)。在 [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}查看教程。
+* API 密钥,在:
+ * 请求头。
+ * 查询参数。
+ * Cookies, 等等。
+
+加上来自 Starlette(包括 **session cookie**)的所有安全特性。
+
+所有的这些都是可复用的工具和组件,可以轻松与你的系统,数据仓库,关系型以及 NoSQL 数据库等等集成。
+
+
+
+### 依赖注入
+
+FastAPI 有一个使用非常简单,但是非常强大的依赖注入系统。
+
+* 甚至依赖也可以有依赖,创建一个层级或者**“图”依赖**。
+* 所有**自动化处理**都由框架完成。
+* 所有的依赖关系都可以从请求中获取数据,并且**增加了路径操作**约束和自动文档生成。
+* 即使在依赖项中被定义的*路径操作* 也会**自动验证**。
+* 支持复杂的用户身份认证系统,**数据库连接**等等。
+* **不依赖**数据库,前端等。 但是和它们集成很简单。
+
+### 无限制"插件"
+
+或者说,导入并使用你需要的代码,而不需要它们。
+
+任何集成都被设计得被易于使用(用依赖关系),你可以用和*路径操作*相同的结构和语法,在两行代码中为你的应用创建一个“插件”。
+
+### 测试
+
+* 100% 测试覆盖。
+* 代码库100% 类型注释。
+* 用于生产应用。
+
+## Starlette 特性
+
+**FastAPI** 和 Starlette 完全兼容(并基于)。所以,你有的其他的 Starlette 代码也能正常工作。`FastAPI` 实际上是 `Starlette`的一个子类。所以,如果你已经知道或者使用 Starlette,大部分的功能会以相同的方式工作。
+
+通过 **FastAPI** 你可以获得所有 **Starlette** 的特性 ( FastAPI 就像加强版的 Starlette ):
+
+* 令人惊叹的性能。它是 Python 可用的最快的框架之一,和 **NodeJS** 及 **Go** 相当。
+* **支持 WebSocket** 。
+* **支持 GraphQL** 。
+* 后台任务处理。
+* Startup 和 shutdown 事件。
+* 测试客户端基于 `requests`。
+* **CORS**, GZip, 静态文件, 流响应。
+* 支持 **Session 和 Cookie** 。
+* 100% 测试覆盖率。
+* 代码库 100% 类型注释。
+
+## Pydantic 特性
+
+**FastAPI** 和 Pydantic 完全兼容(并基于)。所以,你有的其他的 Pydantic 代码也能正常工作。
+
+兼容包括基于 Pydantic 的外部库, 例如用与数据库的 ORMs, ODMs。
+
+这也意味着在很多情况下,你可以将从请求中获得的相同对象**直接传到数据库**,因为所有的验证都是自动的。
+
+反之亦然,在很多情况下,你也可以将从数据库中获取的对象**直接传到客户端**。
+
+通过 **FastAPI** 你可以获得所有 **Pydantic** (FastAPI 基于 Pydantic 做了所有的数据处理):
+
+* **更简单**:
+ * 没有新的模式定义 micro-language 需要学习。
+ * 如果你知道 Python types,你就知道如何使用 Pydantic。
+* 和你 **IDE/linter/brain** 适配:
+ * 因为 pydantic 数据结构仅仅是你定义的类的实例;自动补全,linting,mypy 以及你的直觉应该可以和你验证的数据一起正常工作。
+* **更快**:
+ * 在 基准测试 中,Pydantic 比其他被测试的库都要快。
+* 验证**复杂结构**:
+ * 使用分层的 Pydantic 模型, Python `typing`的 `List` 和 `Dict` 等等。
+ * 验证器使我们能够简单清楚的将复杂的数据模式定义、检查并记录为 JSON Schema。
+ * 你可以拥有深度**嵌套的 JSON** 对象并对它们进行验证和注释。
+* **可扩展**:
+ * Pydantic 允许定义自定义数据类型或者你可以用验证器装饰器对被装饰的模型上的方法扩展验证。
+* 100% 测试覆盖率。
diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md
new file mode 100644
index 0000000000000..897fd45fbac2c
--- /dev/null
+++ b/docs/zh/docs/index.md
@@ -0,0 +1,438 @@
+
+
+
+
+ FastAPI framework, high performance, easy to learn, fast to code, ready for production
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+---
+
+**文档**: https://fastapi.tiangolo.com
+
+**源码**: https://github.com/tiangolo/fastapi
+
+---
+
+FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用基于类型提示的 Python 3.6 及更高版本。
+
+关键特性:
+
+* **快速**:可与 **NodeJS** 和 **Go** 比肩的极高性能(归功于 Starlette 和 Pydantic)。[最快的 Python web 框架之一](#_11)。
+
+* **高效编码**:提高功能开发速度约 200% 至 300%。*
+* **更少 bug**:减少约 40% 的人为(开发者)导致错误。*
+* **智能**:极佳的编辑器支持。处处皆可自动补全,减少调试时间。
+* **简单**:设计的易于使用和学习,减少阅读文档时间。
+* **简短**:减少代码重复。通过不同的参数声明实现丰富功能。bug 更少。
+* **健壮**:生产可用级别的代码。以及自动生成的交互式文档。
+* **标准化**:基于 API 的相关开放标准并完全兼容:OpenAPI (以前被称为 Swagger) 和 JSON Schema。
+
+* 根据对某个构建线上应用的内部开发团队所进行的测试估算得出。
+
+## 评价
+
+"*[...] 最近我一直在使用 **FastAPI**。[...] 实际上我正在计划将其用于我所在的微软团队的所有**机器学习服务**。其中一些服务正被集成进 **Windows** 核心产品和一些 **Office** 产品。*"
+
+
+
+---
+
+"***FastAPI** 让我兴奋的欣喜若狂。它太棒了!*"
+
+
+
+---
+
+"*老实说,你的作品看起来非常可靠和优美。在很多方面,这就是我想让 **Hug** 成为的样子 - 看到有人实现了它真的很鼓舞人心。*"
+
+
+
+---
+
+"*如果你正打算学习一个**现代框架**用来构建 REST API,来看下 **FastAPI** [...] 它快速、易用且易于学习 [...]*"
+
+"*我们已经将 **API** 服务切换到了 **FastAPI** [...] 我认为你会喜欢它的 [...]*"
+
+
+
+---
+
+"*我们采用了 **FastAPI** 来创建用于获取**预测结果**的 **REST** 服务。[用于 Ludwig]*"
+
+Piero Molino, Yaroslav Dudin 和 Sai Sumanth Miryala -
Uber (ref)
+
+---
+
+## **Typer**,命令行中的 Fast API
+
+
+
+如果你正在开发一个在终端中运行的命令行应用而不是 web API,不妨试下 **Typer**。
+
+**Typer** 是 FastAPI 的小伙伴。它打算成为**命令行中的 FastAPI**。 ⌨️ 🚀
+
+## 依赖
+
+Python 3.6 及更高版本
+
+FastAPI 站在以下巨人的肩膀之上:
+
+* Starlette负责 web 部分。
+* Pydantic负责数据部分。
+
+## 安装
+
+
+
+```console
+$ pip install fastapi
+
+---> 100%
+```
+
+
+
+你还需要一个 ASGI 服务器,生产环境可以使用 Uvicorn 或者 Hypercorn。
+
+
+
+```console
+$ pip install uvicorn
+
+---> 100%
+```
+
+
+
+## 示例
+
+### 创建
+
+* 创建一个 `main.py` 文件并写入以下内容:
+
+```Python
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: str = None):
+ return {"item_id": item_id, "q": q}
+```
+
+
+或者使用 async def
...
+
+如果你的代码里会出现 `async` / `await`,应使用 `async def`:
+
+```Python hl_lines="7 12"
+from fastapi import FastAPI
+
+app = FastAPI()
+
+
+@app.get("/")
+async def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+async def read_item(item_id: int, q: str = None):
+ return {"item_id": item_id, "q": q}
+```
+
+**Note**:
+
+如果你不知道是否会用到,可以查看文档的 _"In a hurry?"_ 章节中 关于 `async` 和 `await` 的部分。
+
+
+
+### 运行
+
+通过以下命令运行服务器:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+
+
+
+关于 uvicorn main:app --reload
命令......
+
+ `uvicorn main:app` 命令含义如下:
+
+* `main`:`main.py` 文件(一个 Python "模块")。
+* `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。
+* `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。
+
+
+
+### 检查
+
+使用浏览器访问 http://127.0.0.1:8000/items/5?q=somequery。
+
+你将会看到如下 JSON 响应:
+
+```JSON
+{"item_id": 5, "q": "somequery"}
+```
+
+你已经创建了一个具有以下功能的 API:
+
+* 通过 _路径_ `/` 和 `/items/{item_id}` 接受 HTTP 请求。
+* 以上 _路径_ 都接受 `GET` 操作(也被称为 HTTP _方法_)。
+* `/items/{item_id}` _路径_ 有一个 _路径参数_ `item_id` 并且应该为 `int` 类型。
+* `/items/{item_id}` _路径_ 有一个可选的 `str` 类型的 _查询参数_ `q`。
+
+### 交互式 API 文档
+
+现在访问 http://127.0.0.1:8000/docs。
+
+你会看到自动生成的交互式 API 文档(由 Swagger UI生成):
+
+
+
+### 备选 API 文档
+
+访问 http://127.0.0.1:8000/redoc。
+
+你会看到另一个自动生成的文档(由 ReDoc)生成:
+
+
+
+## 升级示例
+
+修改 `main.py` 文件来从 `PUT` 请求中接收请求体。
+
+我们借助 Pydantic 来使用标准的 Python 类型声明请求体。
+
+```Python hl_lines="2 7 8 9 10 23 24 25"
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+ is_offer: bool = None
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: str = None):
+ return {"item_id": item_id, "q": q}
+
+
+@app.put("/items/{item_id}")
+def update_item(item_id: int, item: Item):
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+服务器将会自动重载(因为在上面的步骤中你向 `uvicorn` 命令添加了 `--reload` 选项)。
+
+### 升级交互式 API 文档
+
+访问 http://127.0.0.1:8000/docs。
+
+* 交互式 API 文档将会自动更新,并加入新的请求体:
+
+
+
+* 点击 "Try it out" 按钮,之后你可以填写参数并直接调用 API:
+
+
+
+* 然后点击 "Execute" 按钮,用户界面将会和 API 进行通信,发送参数,获取结果并在屏幕上展示:
+
+
+
+### 升级备选文档
+
+访问 http://127.0.0.1:8000/redoc。
+
+* 备选文档同样会体现新加入的请求参数和请求体:
+
+
+
+### 回顾
+
+总的来说,你就像声明函数的参数类型一样只声明了**一次**请求参数、请求体等的类型。
+
+你使用了标准的现代 Python 类型来完成声明。
+
+你不需要去学习新的语法、了解特定库的方法或类,等等。
+
+只需要使用标准的 **Python 3.6 及更高版本**。
+
+举个例子,比如声明 `int` 类型:
+
+```Python
+item_id: int
+```
+
+或者一个更复杂的 `Item` 模型:
+
+```Python
+item: Item
+```
+
+......在进行一次声明之后,你将获得:
+
+* 编辑器支持,包括:
+ * 自动补全
+ * 类型检查
+* 数据校验:
+ * 在校验失败时自动生成清晰的错误信息
+ * 对多层嵌套的 JSON 对象依然执行校验
+* 转换 来自网络请求的输入数据为 Python 数据类型。包括以下数据:
+ * JSON
+ * 路径参数
+ * 查询参数
+ * Cookies
+ * 请求头
+ * 表单
+ * 文件
+* 转换 输出的数据:转换 Python 数据类型为供网络传输的 JSON 数据:
+ * 转换 Python 基础类型 (`str`、 `int`、 `float`、 `bool`、 `list` 等)
+ * `datetime` 对象
+ * `UUID` 对象
+ * 数据库模型
+ * ......以及更多其他类型
+* 自动生成的交互式 API 文档,包括两种可选的用户界面:
+ * Swagger UI
+ * ReDoc
+
+---
+
+回到前面的代码示例,**FastAPI** 将会:
+
+* 校验 `GET` 和 `PUT` 请求的路径中是否含有 `item_id`。
+* 校验 `GET` 和 `PUT` 请求中的 `item_id` 是否为 `int` 类型。
+ * 如果不是,客户端将会收到清晰有用的错误信息。
+* 检查 `GET` 请求中是否有命名为 `q` 的可选查询参数(比如 `http://127.0.0.1:8000/items/foo?q=somequery`)。
+ * 因为 `q` 被声明为 `= None`,所以它是可选的。
+ * 如果没有 `None` 它将会是必需的 (如 `PUT` 例子中的请求体)。
+* 对于访问 `/items/{item_id}` 的 `PUT` 请求,将请求体读取为 JSON 并:
+ * 检查是否有必需属性 `name` 并且值为 `str` 类型 。
+ * 检查是否有必需属性 `price` 并且值为 `float` 类型。
+ * 检查是否有可选属性 `is_offer`, 如果有的话值应该为 `bool` 类型。
+ * 以上过程对于多层嵌套的 JSON 对象同样也会执行
+* 自动对 JSON 进行转换或转换成 JSON。
+* 通过 OpenAPI 文档来记录所有内容,可被用于:
+ * 交互式文档系统
+ * 许多编程语言的客户端代码自动生成系统
+* 直接提供 2 种交互式文档 web 界面。
+
+---
+
+虽然我们才刚刚开始,但其实你已经了解了这一切是如何工作的。
+
+尝试更改下面这行代码:
+
+```Python
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+......从:
+
+```Python
+ ... "item_name": item.name ...
+```
+
+......改为:
+
+```Python
+ ... "item_price": item.price ...
+```
+
+......注意观察编辑器是如何自动补全属性并且还知道它们的类型:
+
+
+
+教程 - 用户指南 中有包含更多特性的更完整示例。
+
+**剧透警告**: 教程 - 用户指南中的内容有:
+
+* 对来自不同地方的参数进行声明,如:**请求头**、**cookies**、**form 表单**以及**上传的文件**。
+* 如何设置**校验约束**如 `maximum_length` 或者 `regex`。
+* 一个强大并易于使用的 **依赖注入** 系统。
+* 安全性和身份验证,包括通过 **JWT 令牌**和 **HTTP 基本身份认证**来支持 **OAuth2**。
+* 更进阶(但同样简单)的技巧来声明 **多层嵌套 JSON 模型** (借助 Pydantic)。
+* 许多额外功能(归功于 Starlette)比如:
+ * **WebSockets**
+ * **GraphQL**
+ * 基于 `requests` 和 `pytest` 的极其简单的测试
+ * **CORS**
+ * **Cookie Sessions**
+ * ......以及更多
+
+## 性能
+
+
+独立机构 TechEmpower 所作的基准测试结果显示,基于 Uvicorn 运行的 **FastAPI** 程序是 最快的 Python web 框架之一,仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部使用了它们)。(*)
+
+想了解更多,请查阅 基准测试 章节。
+
+## 可选依赖
+
+用于 Pydantic:
+
+* ujson
- 更快的 JSON "解析"。
+* email_validator
- 用于 email 校验。
+
+用于 Starlette:
+
+* requests
- 使用 `TestClient` 时安装。
+* aiofiles
- 使用 `FileResponse` 或 `StaticFiles` 时安装。
+* jinja2
- 使用默认模板配置时安装。
+* python-multipart
- 需要通过 `request.form()` 对表单进行"解析"时安装。
+* itsdangerous
- 提供 `SessionMiddleware` 支持。
+* pyyaml
- 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。
+* graphene
- 需要 `GraphQLApp` 支持时安装。
+* ujson
- 使用 `UJSONResponse` 时安装。
+
+用于 FastAPI / Starlette:
+
+* uvicorn
- 用于加载和服务你的应用程序的服务器。
+* orjson
- 使用 `ORJSONResponse` 时安装。
+
+你可以通过 `pip install fastapi[all]` 命令来安装以上所有依赖。
+
+## 许可协议
+
+该项目遵循 MIT 许可协议。
diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md
new file mode 100644
index 0000000000000..0c9e9db470ed1
--- /dev/null
+++ b/docs/zh/docs/python-types.md
@@ -0,0 +1,286 @@
+# Python 类型提示简介
+
+**Python 3.6+ 版本**加入了对"类型提示"的支持。
+
+这些**"类型提示"**是一种新的语法(在 Python 3.6 版本加入)用来声明一个变量的类型。
+
+通过声明变量的类型,编辑器和一些工具能给你提供更好的支持。
+
+这只是一个关于 Python 类型提示的**快速入门 / 复习**。它仅涵盖与 **FastAPI** 一起使用所需的最少部分...实际上只有很少一点。
+
+整个 **FastAPI** 都基于这些类型提示构建,它们带来了许多优点和好处。
+
+但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。
+
+!!! note
+ 如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+
+## 动机
+
+让我们从一个简单的例子开始:
+
+```Python
+{!../../../docs_src/python_types/tutorial001.py!}
+```
+
+运行这段程序将输出:
+
+```
+John Doe
+```
+
+这个函数做了下面这些事情:
+
+* 接收 `first_name` 和 `last_name` 参数。
+* 通过 `title()` 将每个参数的第一个字母转换为大写形式。
+* 中间用一个空格来拼接它们。
+
+```Python hl_lines="2"
+{!../../../docs_src/python_types/tutorial001.py!}
+```
+
+### 修改示例
+
+这是一个非常简单的程序。
+
+现在假设你将从头开始编写这段程序。
+
+在某一时刻,你开始定义函数,并且准备好了参数...。
+
+现在你需要调用一个"将第一个字母转换为大写形式的方法"。
+
+等等,那个方法是什么来着?`upper`?还是 `uppercase`?`first_uppercase`?`capitalize`?
+
+然后你尝试向程序员老手的朋友——编辑器自动补全寻求帮助。
+
+输入函数的第一个参数 `first_name`,输入点号(`.`)然后敲下 `Ctrl+Space` 来触发代码补全。
+
+但遗憾的是并没有起什么作用:
+
+
+
+### 添加类型
+
+让我们来修改上面例子的一行代码。
+
+我们将把下面这段代码中的函数参数从:
+
+```Python
+ first_name, last_name
+```
+
+改成:
+
+```Python
+ first_name: str, last_name: str
+```
+
+就是这样。
+
+这些就是"类型提示":
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial002.py!}
+```
+
+这和声明默认值是不同的,例如:
+
+```Python
+ first_name="john", last_name="doe"
+```
+
+这两者不一样。
+
+我们用的是冒号(`:`),不是等号(`=`)。
+
+而且添加类型提示一般不会改变原来的运行结果。
+
+现在假设我们又一次正在创建这个函数,这次添加了类型提示。
+
+在同样的地方,通过 `Ctrl+Space` 触发自动补全,你会发现:
+
+
+
+这样,你可以滚动查看选项,直到你找到看起来眼熟的那个:
+
+
+
+## 更多动机
+
+下面是一个已经有类型提示的函数:
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial003.py!}
+```
+
+因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误:
+
+
+
+现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串:
+
+```Python hl_lines="2"
+{!../../../docs_src/python_types/tutorial004.py!}
+```
+
+## 声明类型
+
+你刚刚看到的就是声明类型提示的主要场景。用于函数的参数。
+
+这也是你将在 **FastAPI** 中使用它们的主要场景。
+
+### 简单类型
+
+不只是 `str`,你能够声明所有的标准 Python 类型。
+
+比如以下类型:
+
+* `int`
+* `float`
+* `bool`
+* `bytes`
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial005.py!}
+```
+
+### 嵌套类型
+
+有些容器数据结构可以包含其他的值,比如 `dict`、`list`、`set` 和 `tuple`。它们内部的值也会拥有自己的类型。
+
+你可以使用 Python 的 `typing` 标准库来声明这些类型以及子类型。
+
+它专门用来支持这些类型提示。
+
+#### 列表
+
+例如,让我们来定义一个由 `str` 组成的 `list` 变量。
+
+从 `typing` 模块导入 `List`(注意是大写的 `L`):
+
+```Python hl_lines="1"
+{!../../../docs_src/python_types/tutorial006.py!}
+```
+
+同样以冒号(`:`)来声明这个变量。
+
+输入 `List` 作为类型。
+
+由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中:
+
+```Python hl_lines="4"
+{!../../../docs_src/python_types/tutorial006.py!}
+```
+
+这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。
+
+这样,即使在处理列表中的元素时,你的编辑器也可以提供支持。
+
+没有类型,几乎是不可能实现下面这样:
+
+
+
+注意,变量 `item` 是列表 `items` 中的元素之一。
+
+而且,编辑器仍然知道它是一个 `str`,并为此提供了支持。
+
+#### 元组和集合
+
+声明 `tuple` 和 `set` 的方法也是一样的:
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial007.py!}
+```
+
+这表示:
+
+* 变量 `items_t` 是一个 `tuple`,其中的每个元素都是 `int` 类型。
+* 变量 `items_s` 是一个 `set`,其中的每个元素都是 `bytes` 类型。
+
+#### 字典
+
+定义 `dict` 时,需要传入两个子类型,用逗号进行分隔。
+
+第一个子类型声明 `dict` 的所有键。
+
+第二个子类型声明 `dict` 的所有值:
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial008.py!}
+```
+
+这表示:
+
+* 变量 `prices` 是一个 `dict`:
+ * 这个 `dict` 的所有键为 `str` 类型(可以看作是字典内每个元素的名称)。
+ * 这个 `dict` 的所有值为 `float` 类型(可以看作是字典内每个元素的价格)。
+
+### 类作为类型
+
+你也可以将类声明为变量的类型。
+
+假设你有一个名为 `Person` 的类,拥有 name 属性:
+
+```Python hl_lines="1 2 3"
+{!../../../docs_src/python_types/tutorial009.py!}
+```
+
+接下来,你可以将一个变量声明为 `Person` 类型:
+
+```Python hl_lines="6"
+{!../../../docs_src/python_types/tutorial009.py!}
+```
+
+然后,你将再次获得所有的编辑器支持:
+
+
+
+## Pydantic 模型
+
+Pydantic 是一个用来用来执行数据校验的 Python 库。
+
+你可以将数据的"结构"声明为具有属性的类。
+
+每个属性都拥有类型。
+
+接着你用一些值来创建这个类的实例,这些值会被校验,并被转换为适当的类型(在需要的情况下),返回一个包含所有数据的对象。
+
+然后,你将获得这个对象的所有编辑器支持。
+
+下面的例子来自 Pydantic 官方文档:
+
+```Python
+{!../../../docs_src/python_types/tutorial010.py!}
+```
+
+!!! info
+ 想进一步了解 Pydantic,请阅读其文档.
+
+整个 **FastAPI** 建立在 Pydantic 的基础之上。
+
+实际上你将在 [教程 - 用户指南](tutorial/index.md){.internal-link target=_blank} 看到很多这种情况。
+
+## **FastAPI** 中的类型提示
+
+**FastAPI** 利用这些类型提示来做下面几件事。
+
+使用 **FastAPI** 时用类型提示声明参数可以获得:
+
+* **编辑器支持**。
+* **类型检查**。
+
+...并且 **FastAPI** 还会用这些类型声明来:
+
+* **定义参数要求**:声明对请求路径参数、查询参数、请求头、请求体、依赖等的要求。
+* **转换数据**:将来自请求的数据转换为需要的类型。
+* **校验数据**: 对于每一个请求:
+ * 当数据校验失败时自动生成**错误信息**返回给客户端。
+* 使用 OpenAPI **记录** API:
+ * 然后用于自动生成交互式文档的用户界面。
+
+听上去有点抽象。不过不用担心。你将在 [教程 - 用户指南](tutorial/index.md){.internal-link target=_blank} 中看到所有的实战。
+
+最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。
+
+!!! info
+ 如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。
diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md
new file mode 100644
index 0000000000000..fbc488202f25f
--- /dev/null
+++ b/docs/zh/docs/tutorial/index.md
@@ -0,0 +1,80 @@
+# 教程 - 用户指南 - 简介
+
+本教程将一步步向你展示如何使用 **FastAPI** 的绝大部分特性。
+
+各个章节的内容循序渐进,但是又围绕着单独的主题,所以你可以直接跳转到某个章节以解决你的特定需求。
+
+本教程同样可以作为将来的参考手册。
+
+你可以随时回到本教程并查阅你需要的内容。
+
+## 运行代码
+
+所有代码片段都可以复制后直接使用(它们实际上是经过测试的 Python 文件)。
+
+要运行任何示例,请将代码复制到 `main.py` 文件中,然后使用以下命令启动 `uvicorn`:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [28720]
+INFO: Started server process [28722]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+
+
+强烈建议你在本地编写或复制代码,对其进行编辑并运行。
+
+在编辑器中使用 FastAPI 会真正地展现出它的优势:只需要编写很少的代码,所有的类型检查,代码补全等等。
+
+---
+
+## 安装 FastAPI
+
+第一个步骤是安装 FastAPI。
+
+为了使用本教程,你可能需要安装所有的可选依赖及对应功能:
+
+
+
+```console
+$ pip install fastapi[all]
+
+---> 100%
+```
+
+
+
+......以上安装还包括了 `uvicorn`,你可以将其用作运行代码的服务器。
+
+!!! note
+ 你也可以分开来安装。
+
+ 假如你想将应用程序部署到生产环境,你可能要执行以下操作:
+
+ ```
+ pip install fastapi
+ ```
+
+ 并且安装`uvicorn`来作为服务器:
+
+ ```
+ pip install uvicorn
+ ```
+
+ 然后对你想使用的每个可选依赖项也执行相同的操作。
+
+## 进阶用户指南
+
+在本**教程-用户指南**之后,你可以阅读**进阶用户指南**。
+
+**进阶用户指南**以本教程为基础,使用相同的概念,并教授一些额外的特性。
+
+但是你应该先阅读**教程-用户指南**(即你现在正在阅读的内容)。
+
+教程经过精心设计,使你可以仅通过**教程-用户指南**来开发一个完整的应用程序,然后根据你的需要,使用**进阶用户指南**中的一些其他概念,以不同的方式来扩展它。
diff --git a/docs/zh/mkdocs.yml b/docs/zh/mkdocs.yml
new file mode 100644
index 0000000000000..75a7e9707670b
--- /dev/null
+++ b/docs/zh/mkdocs.yml
@@ -0,0 +1,70 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/zh/
+theme:
+ name: material
+ palette:
+ primary: teal
+ accent: amber
+ icon:
+ repo: fontawesome/brands/github-alt
+ logo: https://fastapi.tiangolo.com/img/icon-white.svg
+ favicon: https://fastapi.tiangolo.com/img/favicon.png
+ language: zh
+repo_name: tiangolo/fastapi
+repo_url: https://github.com/tiangolo/fastapi
+edit_uri: ''
+google_analytics:
+- UA-133183413-1
+- auto
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - es: /es/
+ - pt: /pt/
+ - zh: /zh/
+- features.md
+- python-types.md
+- 教程 - 用户指南:
+ - tutorial/index.md
+- deployment.md
+markdown_extensions:
+- toc:
+ permalink: true
+- markdown.extensions.codehilite:
+ guess_lang: false
+- markdown_include.include:
+ base_path: docs
+- admonition
+- codehilite
+- extra
+- pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_div_format ''
+- pymdownx.tabbed
+extra:
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/tiangolo/typer
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/tiangolo
+ - icon: fontawesome/brands/linkedin
+ link: https://www.linkedin.com/in/tiangolo
+ - icon: fontawesome/brands/dev
+ link: https://dev.to/tiangolo
+ - icon: fontawesome/brands/medium
+ link: https://medium.com/@tiangolo
+ - icon: fontawesome/solid/globe
+ link: https://tiangolo.com
+extra_css:
+- https://fastapi.tiangolo.com/css/termynal.css
+- https://fastapi.tiangolo.com/css/custom.css
+extra_javascript:
+- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
+- https://fastapi.tiangolo.com/js/termynal.js
+- https://fastapi.tiangolo.com/js/custom.js
+- https://fastapi.tiangolo.com/js/chat.js
+- https://sidecar.gitter.im/dist/sidecar.v1.js
diff --git a/docs/src/additional_responses/tutorial001.py b/docs_src/additional_responses/tutorial001.py
similarity index 100%
rename from docs/src/additional_responses/tutorial001.py
rename to docs_src/additional_responses/tutorial001.py
diff --git a/docs/src/additional_responses/tutorial002.py b/docs_src/additional_responses/tutorial002.py
similarity index 100%
rename from docs/src/additional_responses/tutorial002.py
rename to docs_src/additional_responses/tutorial002.py
diff --git a/docs/src/additional_responses/tutorial003.py b/docs_src/additional_responses/tutorial003.py
similarity index 100%
rename from docs/src/additional_responses/tutorial003.py
rename to docs_src/additional_responses/tutorial003.py
diff --git a/docs/src/additional_responses/tutorial004.py b/docs_src/additional_responses/tutorial004.py
similarity index 100%
rename from docs/src/additional_responses/tutorial004.py
rename to docs_src/additional_responses/tutorial004.py
diff --git a/docs/src/additional_status_codes/tutorial001.py b/docs_src/additional_status_codes/tutorial001.py
similarity index 100%
rename from docs/src/additional_status_codes/tutorial001.py
rename to docs_src/additional_status_codes/tutorial001.py
diff --git a/docs/src/advanced_middleware/tutorial001.py b/docs_src/advanced_middleware/tutorial001.py
similarity index 100%
rename from docs/src/advanced_middleware/tutorial001.py
rename to docs_src/advanced_middleware/tutorial001.py
diff --git a/docs/src/advanced_middleware/tutorial002.py b/docs_src/advanced_middleware/tutorial002.py
similarity index 100%
rename from docs/src/advanced_middleware/tutorial002.py
rename to docs_src/advanced_middleware/tutorial002.py
diff --git a/docs/src/advanced_middleware/tutorial003.py b/docs_src/advanced_middleware/tutorial003.py
similarity index 100%
rename from docs/src/advanced_middleware/tutorial003.py
rename to docs_src/advanced_middleware/tutorial003.py
diff --git a/docs/src/app_testing/__init__.py b/docs_src/app_testing/__init__.py
similarity index 100%
rename from docs/src/app_testing/__init__.py
rename to docs_src/app_testing/__init__.py
diff --git a/docs/src/app_testing/main.py b/docs_src/app_testing/main.py
similarity index 100%
rename from docs/src/app_testing/main.py
rename to docs_src/app_testing/main.py
diff --git a/docs/src/app_testing/main_b.py b/docs_src/app_testing/main_b.py
similarity index 100%
rename from docs/src/app_testing/main_b.py
rename to docs_src/app_testing/main_b.py
diff --git a/docs/src/app_testing/test_main.py b/docs_src/app_testing/test_main.py
similarity index 100%
rename from docs/src/app_testing/test_main.py
rename to docs_src/app_testing/test_main.py
diff --git a/docs/src/app_testing/test_main_b.py b/docs_src/app_testing/test_main_b.py
similarity index 100%
rename from docs/src/app_testing/test_main_b.py
rename to docs_src/app_testing/test_main_b.py
diff --git a/docs/src/app_testing/tutorial001.py b/docs_src/app_testing/tutorial001.py
similarity index 100%
rename from docs/src/app_testing/tutorial001.py
rename to docs_src/app_testing/tutorial001.py
diff --git a/docs/src/app_testing/tutorial002.py b/docs_src/app_testing/tutorial002.py
similarity index 100%
rename from docs/src/app_testing/tutorial002.py
rename to docs_src/app_testing/tutorial002.py
diff --git a/docs/src/app_testing/tutorial003.py b/docs_src/app_testing/tutorial003.py
similarity index 100%
rename from docs/src/app_testing/tutorial003.py
rename to docs_src/app_testing/tutorial003.py
diff --git a/docs/src/async_sql_databases/tutorial001.py b/docs_src/async_sql_databases/tutorial001.py
similarity index 100%
rename from docs/src/async_sql_databases/tutorial001.py
rename to docs_src/async_sql_databases/tutorial001.py
diff --git a/docs/src/background_tasks/tutorial001.py b/docs_src/background_tasks/tutorial001.py
similarity index 100%
rename from docs/src/background_tasks/tutorial001.py
rename to docs_src/background_tasks/tutorial001.py
diff --git a/docs/src/background_tasks/tutorial002.py b/docs_src/background_tasks/tutorial002.py
similarity index 100%
rename from docs/src/background_tasks/tutorial002.py
rename to docs_src/background_tasks/tutorial002.py
diff --git a/docs_src/behind_a_proxy/tutorial001.py b/docs_src/behind_a_proxy/tutorial001.py
new file mode 100644
index 0000000000000..ede59ada1132a
--- /dev/null
+++ b/docs_src/behind_a_proxy/tutorial001.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI, Request
+
+app = FastAPI()
+
+
+@app.get("/app")
+def read_main(request: Request):
+ return {"message": "Hello World", "root_path": request.scope.get("root_path")}
diff --git a/docs_src/behind_a_proxy/tutorial002.py b/docs_src/behind_a_proxy/tutorial002.py
new file mode 100644
index 0000000000000..c1600cde9e94a
--- /dev/null
+++ b/docs_src/behind_a_proxy/tutorial002.py
@@ -0,0 +1,8 @@
+from fastapi import FastAPI, Request
+
+app = FastAPI(root_path="/api/v1")
+
+
+@app.get("/app")
+def read_main(request: Request):
+ return {"message": "Hello World", "root_path": request.scope.get("root_path")}
diff --git a/docs/src/bigger_applications/__init__.py b/docs_src/bigger_applications/__init__.py
similarity index 100%
rename from docs/src/bigger_applications/__init__.py
rename to docs_src/bigger_applications/__init__.py
diff --git a/docs/src/bigger_applications/app/__init__.py b/docs_src/bigger_applications/app/__init__.py
similarity index 100%
rename from docs/src/bigger_applications/app/__init__.py
rename to docs_src/bigger_applications/app/__init__.py
diff --git a/docs/src/bigger_applications/app/main.py b/docs_src/bigger_applications/app/main.py
similarity index 100%
rename from docs/src/bigger_applications/app/main.py
rename to docs_src/bigger_applications/app/main.py
diff --git a/docs/src/bigger_applications/app/routers/__init__.py b/docs_src/bigger_applications/app/routers/__init__.py
similarity index 100%
rename from docs/src/bigger_applications/app/routers/__init__.py
rename to docs_src/bigger_applications/app/routers/__init__.py
diff --git a/docs/src/bigger_applications/app/routers/items.py b/docs_src/bigger_applications/app/routers/items.py
similarity index 100%
rename from docs/src/bigger_applications/app/routers/items.py
rename to docs_src/bigger_applications/app/routers/items.py
diff --git a/docs/src/bigger_applications/app/routers/users.py b/docs_src/bigger_applications/app/routers/users.py
similarity index 100%
rename from docs/src/bigger_applications/app/routers/users.py
rename to docs_src/bigger_applications/app/routers/users.py
diff --git a/docs/src/body/tutorial001.py b/docs_src/body/tutorial001.py
similarity index 100%
rename from docs/src/body/tutorial001.py
rename to docs_src/body/tutorial001.py
diff --git a/docs/src/body/tutorial002.py b/docs_src/body/tutorial002.py
similarity index 100%
rename from docs/src/body/tutorial002.py
rename to docs_src/body/tutorial002.py
diff --git a/docs/src/body/tutorial003.py b/docs_src/body/tutorial003.py
similarity index 100%
rename from docs/src/body/tutorial003.py
rename to docs_src/body/tutorial003.py
diff --git a/docs/src/body/tutorial004.py b/docs_src/body/tutorial004.py
similarity index 100%
rename from docs/src/body/tutorial004.py
rename to docs_src/body/tutorial004.py
diff --git a/docs/src/body_fields/tutorial001.py b/docs_src/body_fields/tutorial001.py
similarity index 100%
rename from docs/src/body_fields/tutorial001.py
rename to docs_src/body_fields/tutorial001.py
diff --git a/docs/src/body_multiple_params/tutorial001.py b/docs_src/body_multiple_params/tutorial001.py
similarity index 100%
rename from docs/src/body_multiple_params/tutorial001.py
rename to docs_src/body_multiple_params/tutorial001.py
diff --git a/docs/src/body_multiple_params/tutorial002.py b/docs_src/body_multiple_params/tutorial002.py
similarity index 100%
rename from docs/src/body_multiple_params/tutorial002.py
rename to docs_src/body_multiple_params/tutorial002.py
diff --git a/docs/src/body_multiple_params/tutorial003.py b/docs_src/body_multiple_params/tutorial003.py
similarity index 100%
rename from docs/src/body_multiple_params/tutorial003.py
rename to docs_src/body_multiple_params/tutorial003.py
diff --git a/docs/src/body_multiple_params/tutorial004.py b/docs_src/body_multiple_params/tutorial004.py
similarity index 100%
rename from docs/src/body_multiple_params/tutorial004.py
rename to docs_src/body_multiple_params/tutorial004.py
diff --git a/docs/src/body_multiple_params/tutorial005.py b/docs_src/body_multiple_params/tutorial005.py
similarity index 100%
rename from docs/src/body_multiple_params/tutorial005.py
rename to docs_src/body_multiple_params/tutorial005.py
diff --git a/docs/src/body_nested_models/tutorial001.py b/docs_src/body_nested_models/tutorial001.py
similarity index 100%
rename from docs/src/body_nested_models/tutorial001.py
rename to docs_src/body_nested_models/tutorial001.py
diff --git a/docs/src/body_nested_models/tutorial002.py b/docs_src/body_nested_models/tutorial002.py
similarity index 100%
rename from docs/src/body_nested_models/tutorial002.py
rename to docs_src/body_nested_models/tutorial002.py
diff --git a/docs/src/body_nested_models/tutorial003.py b/docs_src/body_nested_models/tutorial003.py
similarity index 100%
rename from docs/src/body_nested_models/tutorial003.py
rename to docs_src/body_nested_models/tutorial003.py
diff --git a/docs/src/body_nested_models/tutorial004.py b/docs_src/body_nested_models/tutorial004.py
similarity index 100%
rename from docs/src/body_nested_models/tutorial004.py
rename to docs_src/body_nested_models/tutorial004.py
diff --git a/docs/src/body_nested_models/tutorial005.py b/docs_src/body_nested_models/tutorial005.py
similarity index 100%
rename from docs/src/body_nested_models/tutorial005.py
rename to docs_src/body_nested_models/tutorial005.py
diff --git a/docs/src/body_nested_models/tutorial006.py b/docs_src/body_nested_models/tutorial006.py
similarity index 100%
rename from docs/src/body_nested_models/tutorial006.py
rename to docs_src/body_nested_models/tutorial006.py
diff --git a/docs/src/body_nested_models/tutorial007.py b/docs_src/body_nested_models/tutorial007.py
similarity index 100%
rename from docs/src/body_nested_models/tutorial007.py
rename to docs_src/body_nested_models/tutorial007.py
diff --git a/docs/src/body_nested_models/tutorial008.py b/docs_src/body_nested_models/tutorial008.py
similarity index 100%
rename from docs/src/body_nested_models/tutorial008.py
rename to docs_src/body_nested_models/tutorial008.py
diff --git a/docs/src/body_nested_models/tutorial009.py b/docs_src/body_nested_models/tutorial009.py
similarity index 100%
rename from docs/src/body_nested_models/tutorial009.py
rename to docs_src/body_nested_models/tutorial009.py
diff --git a/docs/src/body_updates/tutorial001.py b/docs_src/body_updates/tutorial001.py
similarity index 100%
rename from docs/src/body_updates/tutorial001.py
rename to docs_src/body_updates/tutorial001.py
diff --git a/docs/src/body_updates/tutorial002.py b/docs_src/body_updates/tutorial002.py
similarity index 100%
rename from docs/src/body_updates/tutorial002.py
rename to docs_src/body_updates/tutorial002.py
diff --git a/docs_src/conditional_openapi/tutorial001.py b/docs_src/conditional_openapi/tutorial001.py
new file mode 100644
index 0000000000000..717e723e83a89
--- /dev/null
+++ b/docs_src/conditional_openapi/tutorial001.py
@@ -0,0 +1,16 @@
+from fastapi import FastAPI
+from pydantic import BaseSettings
+
+
+class Settings(BaseSettings):
+ openapi_url: str = "/openapi.json"
+
+
+settings = Settings()
+
+app = FastAPI(openapi_url=settings.openapi_url)
+
+
+@app.get("/")
+def root():
+ return {"message": "Hello World"}
diff --git a/docs/src/cookie_params/tutorial001.py b/docs_src/cookie_params/tutorial001.py
similarity index 100%
rename from docs/src/cookie_params/tutorial001.py
rename to docs_src/cookie_params/tutorial001.py
diff --git a/docs/src/cors/tutorial001.py b/docs_src/cors/tutorial001.py
similarity index 100%
rename from docs/src/cors/tutorial001.py
rename to docs_src/cors/tutorial001.py
diff --git a/docs/src/custom_request_and_route/tutorial001.py b/docs_src/custom_request_and_route/tutorial001.py
similarity index 100%
rename from docs/src/custom_request_and_route/tutorial001.py
rename to docs_src/custom_request_and_route/tutorial001.py
diff --git a/docs/src/custom_request_and_route/tutorial002.py b/docs_src/custom_request_and_route/tutorial002.py
similarity index 100%
rename from docs/src/custom_request_and_route/tutorial002.py
rename to docs_src/custom_request_and_route/tutorial002.py
diff --git a/docs/src/custom_request_and_route/tutorial003.py b/docs_src/custom_request_and_route/tutorial003.py
similarity index 100%
rename from docs/src/custom_request_and_route/tutorial003.py
rename to docs_src/custom_request_and_route/tutorial003.py
diff --git a/docs/src/custom_response/tutorial001.py b/docs_src/custom_response/tutorial001.py
similarity index 100%
rename from docs/src/custom_response/tutorial001.py
rename to docs_src/custom_response/tutorial001.py
diff --git a/docs/src/custom_response/tutorial001b.py b/docs_src/custom_response/tutorial001b.py
similarity index 100%
rename from docs/src/custom_response/tutorial001b.py
rename to docs_src/custom_response/tutorial001b.py
diff --git a/docs/src/custom_response/tutorial002.py b/docs_src/custom_response/tutorial002.py
similarity index 100%
rename from docs/src/custom_response/tutorial002.py
rename to docs_src/custom_response/tutorial002.py
diff --git a/docs/src/custom_response/tutorial003.py b/docs_src/custom_response/tutorial003.py
similarity index 100%
rename from docs/src/custom_response/tutorial003.py
rename to docs_src/custom_response/tutorial003.py
diff --git a/docs/src/custom_response/tutorial004.py b/docs_src/custom_response/tutorial004.py
similarity index 100%
rename from docs/src/custom_response/tutorial004.py
rename to docs_src/custom_response/tutorial004.py
diff --git a/docs/src/custom_response/tutorial005.py b/docs_src/custom_response/tutorial005.py
similarity index 100%
rename from docs/src/custom_response/tutorial005.py
rename to docs_src/custom_response/tutorial005.py
diff --git a/docs/src/custom_response/tutorial006.py b/docs_src/custom_response/tutorial006.py
similarity index 100%
rename from docs/src/custom_response/tutorial006.py
rename to docs_src/custom_response/tutorial006.py
diff --git a/docs/src/custom_response/tutorial007.py b/docs_src/custom_response/tutorial007.py
similarity index 100%
rename from docs/src/custom_response/tutorial007.py
rename to docs_src/custom_response/tutorial007.py
diff --git a/docs/src/custom_response/tutorial008.py b/docs_src/custom_response/tutorial008.py
similarity index 100%
rename from docs/src/custom_response/tutorial008.py
rename to docs_src/custom_response/tutorial008.py
diff --git a/docs/src/custom_response/tutorial009.py b/docs_src/custom_response/tutorial009.py
similarity index 100%
rename from docs/src/custom_response/tutorial009.py
rename to docs_src/custom_response/tutorial009.py
diff --git a/docs/src/debugging/tutorial001.py b/docs_src/debugging/tutorial001.py
similarity index 100%
rename from docs/src/debugging/tutorial001.py
rename to docs_src/debugging/tutorial001.py
diff --git a/docs/src/dependencies/tutorial001.py b/docs_src/dependencies/tutorial001.py
similarity index 100%
rename from docs/src/dependencies/tutorial001.py
rename to docs_src/dependencies/tutorial001.py
diff --git a/docs/src/dependencies/tutorial002.py b/docs_src/dependencies/tutorial002.py
similarity index 100%
rename from docs/src/dependencies/tutorial002.py
rename to docs_src/dependencies/tutorial002.py
diff --git a/docs/src/dependencies/tutorial003.py b/docs_src/dependencies/tutorial003.py
similarity index 100%
rename from docs/src/dependencies/tutorial003.py
rename to docs_src/dependencies/tutorial003.py
diff --git a/docs/src/dependencies/tutorial004.py b/docs_src/dependencies/tutorial004.py
similarity index 100%
rename from docs/src/dependencies/tutorial004.py
rename to docs_src/dependencies/tutorial004.py
diff --git a/docs/src/dependencies/tutorial005.py b/docs_src/dependencies/tutorial005.py
similarity index 100%
rename from docs/src/dependencies/tutorial005.py
rename to docs_src/dependencies/tutorial005.py
diff --git a/docs/src/dependencies/tutorial006.py b/docs_src/dependencies/tutorial006.py
similarity index 100%
rename from docs/src/dependencies/tutorial006.py
rename to docs_src/dependencies/tutorial006.py
diff --git a/docs/src/dependencies/tutorial007.py b/docs_src/dependencies/tutorial007.py
similarity index 100%
rename from docs/src/dependencies/tutorial007.py
rename to docs_src/dependencies/tutorial007.py
diff --git a/docs/src/dependencies/tutorial008.py b/docs_src/dependencies/tutorial008.py
similarity index 100%
rename from docs/src/dependencies/tutorial008.py
rename to docs_src/dependencies/tutorial008.py
diff --git a/docs/src/dependencies/tutorial009.py b/docs_src/dependencies/tutorial009.py
similarity index 100%
rename from docs/src/dependencies/tutorial009.py
rename to docs_src/dependencies/tutorial009.py
diff --git a/docs/src/dependencies/tutorial010.py b/docs_src/dependencies/tutorial010.py
similarity index 100%
rename from docs/src/dependencies/tutorial010.py
rename to docs_src/dependencies/tutorial010.py
diff --git a/docs/src/dependencies/tutorial011.py b/docs_src/dependencies/tutorial011.py
similarity index 100%
rename from docs/src/dependencies/tutorial011.py
rename to docs_src/dependencies/tutorial011.py
diff --git a/docs/src/dependency_testing/tutorial001.py b/docs_src/dependency_testing/tutorial001.py
similarity index 100%
rename from docs/src/dependency_testing/tutorial001.py
rename to docs_src/dependency_testing/tutorial001.py
diff --git a/docs/src/encoder/tutorial001.py b/docs_src/encoder/tutorial001.py
similarity index 100%
rename from docs/src/encoder/tutorial001.py
rename to docs_src/encoder/tutorial001.py
diff --git a/docs/src/events/tutorial001.py b/docs_src/events/tutorial001.py
similarity index 100%
rename from docs/src/events/tutorial001.py
rename to docs_src/events/tutorial001.py
diff --git a/docs/src/events/tutorial002.py b/docs_src/events/tutorial002.py
similarity index 100%
rename from docs/src/events/tutorial002.py
rename to docs_src/events/tutorial002.py
diff --git a/docs/src/extending_openapi/tutorial001.py b/docs_src/extending_openapi/tutorial001.py
similarity index 88%
rename from docs/src/extending_openapi/tutorial001.py
rename to docs_src/extending_openapi/tutorial001.py
index 561e95898f5f4..d9d7e9844bec9 100644
--- a/docs/src/extending_openapi/tutorial001.py
+++ b/docs_src/extending_openapi/tutorial001.py
@@ -9,7 +9,7 @@ async def read_items():
return [{"name": "Foo"}]
-def custom_openapi():
+def custom_openapi(openapi_prefix: str):
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
@@ -17,6 +17,7 @@ def custom_openapi():
version="2.5.0",
description="This is a very custom OpenAPI schema",
routes=app.routes,
+ openapi_prefix=openapi_prefix,
)
openapi_schema["info"]["x-logo"] = {
"url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png"
diff --git a/docs/src/extending_openapi/tutorial002.py b/docs_src/extending_openapi/tutorial002.py
similarity index 100%
rename from docs/src/extending_openapi/tutorial002.py
rename to docs_src/extending_openapi/tutorial002.py
diff --git a/docs/src/extra_data_types/tutorial001.py b/docs_src/extra_data_types/tutorial001.py
similarity index 100%
rename from docs/src/extra_data_types/tutorial001.py
rename to docs_src/extra_data_types/tutorial001.py
diff --git a/docs/src/extra_models/tutorial001.py b/docs_src/extra_models/tutorial001.py
similarity index 100%
rename from docs/src/extra_models/tutorial001.py
rename to docs_src/extra_models/tutorial001.py
diff --git a/docs/src/extra_models/tutorial002.py b/docs_src/extra_models/tutorial002.py
similarity index 100%
rename from docs/src/extra_models/tutorial002.py
rename to docs_src/extra_models/tutorial002.py
diff --git a/docs/src/extra_models/tutorial003.py b/docs_src/extra_models/tutorial003.py
similarity index 100%
rename from docs/src/extra_models/tutorial003.py
rename to docs_src/extra_models/tutorial003.py
diff --git a/docs/src/extra_models/tutorial004.py b/docs_src/extra_models/tutorial004.py
similarity index 100%
rename from docs/src/extra_models/tutorial004.py
rename to docs_src/extra_models/tutorial004.py
diff --git a/docs/src/extra_models/tutorial005.py b/docs_src/extra_models/tutorial005.py
similarity index 100%
rename from docs/src/extra_models/tutorial005.py
rename to docs_src/extra_models/tutorial005.py
diff --git a/docs/src/first_steps/tutorial001.py b/docs_src/first_steps/tutorial001.py
similarity index 100%
rename from docs/src/first_steps/tutorial001.py
rename to docs_src/first_steps/tutorial001.py
diff --git a/docs/src/first_steps/tutorial002.py b/docs_src/first_steps/tutorial002.py
similarity index 100%
rename from docs/src/first_steps/tutorial002.py
rename to docs_src/first_steps/tutorial002.py
diff --git a/docs/src/first_steps/tutorial003.py b/docs_src/first_steps/tutorial003.py
similarity index 100%
rename from docs/src/first_steps/tutorial003.py
rename to docs_src/first_steps/tutorial003.py
diff --git a/docs/src/graphql/tutorial001.py b/docs_src/graphql/tutorial001.py
similarity index 100%
rename from docs/src/graphql/tutorial001.py
rename to docs_src/graphql/tutorial001.py
diff --git a/docs/src/handling_errors/tutorial001.py b/docs_src/handling_errors/tutorial001.py
similarity index 100%
rename from docs/src/handling_errors/tutorial001.py
rename to docs_src/handling_errors/tutorial001.py
diff --git a/docs/src/handling_errors/tutorial002.py b/docs_src/handling_errors/tutorial002.py
similarity index 100%
rename from docs/src/handling_errors/tutorial002.py
rename to docs_src/handling_errors/tutorial002.py
diff --git a/docs/src/handling_errors/tutorial003.py b/docs_src/handling_errors/tutorial003.py
similarity index 100%
rename from docs/src/handling_errors/tutorial003.py
rename to docs_src/handling_errors/tutorial003.py
diff --git a/docs/src/handling_errors/tutorial004.py b/docs_src/handling_errors/tutorial004.py
similarity index 100%
rename from docs/src/handling_errors/tutorial004.py
rename to docs_src/handling_errors/tutorial004.py
diff --git a/docs/src/handling_errors/tutorial005.py b/docs_src/handling_errors/tutorial005.py
similarity index 100%
rename from docs/src/handling_errors/tutorial005.py
rename to docs_src/handling_errors/tutorial005.py
diff --git a/docs/src/handling_errors/tutorial006.py b/docs_src/handling_errors/tutorial006.py
similarity index 100%
rename from docs/src/handling_errors/tutorial006.py
rename to docs_src/handling_errors/tutorial006.py
diff --git a/docs/src/header_params/tutorial001.py b/docs_src/header_params/tutorial001.py
similarity index 100%
rename from docs/src/header_params/tutorial001.py
rename to docs_src/header_params/tutorial001.py
diff --git a/docs/src/header_params/tutorial002.py b/docs_src/header_params/tutorial002.py
similarity index 100%
rename from docs/src/header_params/tutorial002.py
rename to docs_src/header_params/tutorial002.py
diff --git a/docs/src/header_params/tutorial003.py b/docs_src/header_params/tutorial003.py
similarity index 100%
rename from docs/src/header_params/tutorial003.py
rename to docs_src/header_params/tutorial003.py
diff --git a/docs/src/application_configuration/tutorial001.py b/docs_src/metadata/tutorial001.py
similarity index 100%
rename from docs/src/application_configuration/tutorial001.py
rename to docs_src/metadata/tutorial001.py
diff --git a/docs/src/application_configuration/tutorial002.py b/docs_src/metadata/tutorial002.py
similarity index 100%
rename from docs/src/application_configuration/tutorial002.py
rename to docs_src/metadata/tutorial002.py
diff --git a/docs/src/application_configuration/tutorial003.py b/docs_src/metadata/tutorial003.py
similarity index 100%
rename from docs/src/application_configuration/tutorial003.py
rename to docs_src/metadata/tutorial003.py
diff --git a/docs/src/middleware/tutorial001.py b/docs_src/middleware/tutorial001.py
similarity index 100%
rename from docs/src/middleware/tutorial001.py
rename to docs_src/middleware/tutorial001.py
diff --git a/docs/src/nosql_databases/tutorial001.py b/docs_src/nosql_databases/tutorial001.py
similarity index 100%
rename from docs/src/nosql_databases/tutorial001.py
rename to docs_src/nosql_databases/tutorial001.py
diff --git a/docs/src/openapi_callbacks/tutorial001.py b/docs_src/openapi_callbacks/tutorial001.py
similarity index 100%
rename from docs/src/openapi_callbacks/tutorial001.py
rename to docs_src/openapi_callbacks/tutorial001.py
diff --git a/docs/src/path_operation_advanced_configuration/tutorial001.py b/docs_src/path_operation_advanced_configuration/tutorial001.py
similarity index 100%
rename from docs/src/path_operation_advanced_configuration/tutorial001.py
rename to docs_src/path_operation_advanced_configuration/tutorial001.py
diff --git a/docs/src/path_operation_advanced_configuration/tutorial002.py b/docs_src/path_operation_advanced_configuration/tutorial002.py
similarity index 100%
rename from docs/src/path_operation_advanced_configuration/tutorial002.py
rename to docs_src/path_operation_advanced_configuration/tutorial002.py
diff --git a/docs/src/path_operation_advanced_configuration/tutorial003.py b/docs_src/path_operation_advanced_configuration/tutorial003.py
similarity index 100%
rename from docs/src/path_operation_advanced_configuration/tutorial003.py
rename to docs_src/path_operation_advanced_configuration/tutorial003.py
diff --git a/docs/src/path_operation_advanced_configuration/tutorial004.py b/docs_src/path_operation_advanced_configuration/tutorial004.py
similarity index 100%
rename from docs/src/path_operation_advanced_configuration/tutorial004.py
rename to docs_src/path_operation_advanced_configuration/tutorial004.py
diff --git a/docs/src/path_operation_configuration/tutorial001.py b/docs_src/path_operation_configuration/tutorial001.py
similarity index 100%
rename from docs/src/path_operation_configuration/tutorial001.py
rename to docs_src/path_operation_configuration/tutorial001.py
diff --git a/docs/src/path_operation_configuration/tutorial002.py b/docs_src/path_operation_configuration/tutorial002.py
similarity index 100%
rename from docs/src/path_operation_configuration/tutorial002.py
rename to docs_src/path_operation_configuration/tutorial002.py
diff --git a/docs/src/path_operation_configuration/tutorial003.py b/docs_src/path_operation_configuration/tutorial003.py
similarity index 100%
rename from docs/src/path_operation_configuration/tutorial003.py
rename to docs_src/path_operation_configuration/tutorial003.py
diff --git a/docs/src/path_operation_configuration/tutorial004.py b/docs_src/path_operation_configuration/tutorial004.py
similarity index 100%
rename from docs/src/path_operation_configuration/tutorial004.py
rename to docs_src/path_operation_configuration/tutorial004.py
diff --git a/docs/src/path_operation_configuration/tutorial005.py b/docs_src/path_operation_configuration/tutorial005.py
similarity index 100%
rename from docs/src/path_operation_configuration/tutorial005.py
rename to docs_src/path_operation_configuration/tutorial005.py
diff --git a/docs/src/path_operation_configuration/tutorial006.py b/docs_src/path_operation_configuration/tutorial006.py
similarity index 100%
rename from docs/src/path_operation_configuration/tutorial006.py
rename to docs_src/path_operation_configuration/tutorial006.py
diff --git a/docs/src/path_params/tutorial001.py b/docs_src/path_params/tutorial001.py
similarity index 100%
rename from docs/src/path_params/tutorial001.py
rename to docs_src/path_params/tutorial001.py
diff --git a/docs/src/path_params/tutorial002.py b/docs_src/path_params/tutorial002.py
similarity index 100%
rename from docs/src/path_params/tutorial002.py
rename to docs_src/path_params/tutorial002.py
diff --git a/docs/src/path_params/tutorial003.py b/docs_src/path_params/tutorial003.py
similarity index 100%
rename from docs/src/path_params/tutorial003.py
rename to docs_src/path_params/tutorial003.py
diff --git a/docs/src/path_params/tutorial004.py b/docs_src/path_params/tutorial004.py
similarity index 74%
rename from docs/src/path_params/tutorial004.py
rename to docs_src/path_params/tutorial004.py
index 76adf38217a10..2961e6178e7a6 100644
--- a/docs/src/path_params/tutorial004.py
+++ b/docs_src/path_params/tutorial004.py
@@ -4,5 +4,5 @@
@app.get("/files/{file_path:path}")
-async def read_user_me(file_path: str):
+async def read_file(file_path: str):
return {"file_path": file_path}
diff --git a/docs/src/path_params/tutorial005.py b/docs_src/path_params/tutorial005.py
similarity index 100%
rename from docs/src/path_params/tutorial005.py
rename to docs_src/path_params/tutorial005.py
diff --git a/docs/src/path_params_numeric_validations/tutorial001.py b/docs_src/path_params_numeric_validations/tutorial001.py
similarity index 100%
rename from docs/src/path_params_numeric_validations/tutorial001.py
rename to docs_src/path_params_numeric_validations/tutorial001.py
diff --git a/docs/src/path_params_numeric_validations/tutorial002.py b/docs_src/path_params_numeric_validations/tutorial002.py
similarity index 100%
rename from docs/src/path_params_numeric_validations/tutorial002.py
rename to docs_src/path_params_numeric_validations/tutorial002.py
diff --git a/docs/src/path_params_numeric_validations/tutorial003.py b/docs_src/path_params_numeric_validations/tutorial003.py
similarity index 100%
rename from docs/src/path_params_numeric_validations/tutorial003.py
rename to docs_src/path_params_numeric_validations/tutorial003.py
diff --git a/docs/src/path_params_numeric_validations/tutorial004.py b/docs_src/path_params_numeric_validations/tutorial004.py
similarity index 100%
rename from docs/src/path_params_numeric_validations/tutorial004.py
rename to docs_src/path_params_numeric_validations/tutorial004.py
diff --git a/docs/src/path_params_numeric_validations/tutorial005.py b/docs_src/path_params_numeric_validations/tutorial005.py
similarity index 100%
rename from docs/src/path_params_numeric_validations/tutorial005.py
rename to docs_src/path_params_numeric_validations/tutorial005.py
diff --git a/docs/src/path_params_numeric_validations/tutorial006.py b/docs_src/path_params_numeric_validations/tutorial006.py
similarity index 100%
rename from docs/src/path_params_numeric_validations/tutorial006.py
rename to docs_src/path_params_numeric_validations/tutorial006.py
diff --git a/docs/src/python_types/tutorial001.py b/docs_src/python_types/tutorial001.py
similarity index 100%
rename from docs/src/python_types/tutorial001.py
rename to docs_src/python_types/tutorial001.py
diff --git a/docs/src/python_types/tutorial002.py b/docs_src/python_types/tutorial002.py
similarity index 100%
rename from docs/src/python_types/tutorial002.py
rename to docs_src/python_types/tutorial002.py
diff --git a/docs/src/python_types/tutorial003.py b/docs_src/python_types/tutorial003.py
similarity index 100%
rename from docs/src/python_types/tutorial003.py
rename to docs_src/python_types/tutorial003.py
diff --git a/docs/src/python_types/tutorial004.py b/docs_src/python_types/tutorial004.py
similarity index 100%
rename from docs/src/python_types/tutorial004.py
rename to docs_src/python_types/tutorial004.py
diff --git a/docs/src/python_types/tutorial005.py b/docs_src/python_types/tutorial005.py
similarity index 100%
rename from docs/src/python_types/tutorial005.py
rename to docs_src/python_types/tutorial005.py
diff --git a/docs/src/python_types/tutorial006.py b/docs_src/python_types/tutorial006.py
similarity index 100%
rename from docs/src/python_types/tutorial006.py
rename to docs_src/python_types/tutorial006.py
diff --git a/docs_src/python_types/tutorial007.py b/docs_src/python_types/tutorial007.py
new file mode 100644
index 0000000000000..5b13f15494a8d
--- /dev/null
+++ b/docs_src/python_types/tutorial007.py
@@ -0,0 +1,5 @@
+from typing import Set, Tuple
+
+
+def process_items(items_t: Tuple[int, int, str], items_s: Set[bytes]):
+ return items_t, items_s
diff --git a/docs/src/python_types/tutorial008.py b/docs_src/python_types/tutorial008.py
similarity index 100%
rename from docs/src/python_types/tutorial008.py
rename to docs_src/python_types/tutorial008.py
diff --git a/docs/src/python_types/tutorial009.py b/docs_src/python_types/tutorial009.py
similarity index 100%
rename from docs/src/python_types/tutorial009.py
rename to docs_src/python_types/tutorial009.py
diff --git a/docs/src/python_types/tutorial010.py b/docs_src/python_types/tutorial010.py
similarity index 100%
rename from docs/src/python_types/tutorial010.py
rename to docs_src/python_types/tutorial010.py
diff --git a/docs/src/query_params/tutorial001.py b/docs_src/query_params/tutorial001.py
similarity index 100%
rename from docs/src/query_params/tutorial001.py
rename to docs_src/query_params/tutorial001.py
diff --git a/docs/src/query_params/tutorial002.py b/docs_src/query_params/tutorial002.py
similarity index 100%
rename from docs/src/query_params/tutorial002.py
rename to docs_src/query_params/tutorial002.py
diff --git a/docs/src/query_params/tutorial003.py b/docs_src/query_params/tutorial003.py
similarity index 100%
rename from docs/src/query_params/tutorial003.py
rename to docs_src/query_params/tutorial003.py
diff --git a/docs/src/query_params/tutorial004.py b/docs_src/query_params/tutorial004.py
similarity index 100%
rename from docs/src/query_params/tutorial004.py
rename to docs_src/query_params/tutorial004.py
diff --git a/docs/src/query_params/tutorial005.py b/docs_src/query_params/tutorial005.py
similarity index 100%
rename from docs/src/query_params/tutorial005.py
rename to docs_src/query_params/tutorial005.py
diff --git a/docs/src/query_params/tutorial006.py b/docs_src/query_params/tutorial006.py
similarity index 100%
rename from docs/src/query_params/tutorial006.py
rename to docs_src/query_params/tutorial006.py
diff --git a/docs/src/query_params/tutorial007.py b/docs_src/query_params/tutorial007.py
similarity index 100%
rename from docs/src/query_params/tutorial007.py
rename to docs_src/query_params/tutorial007.py
diff --git a/docs/src/query_params_str_validations/tutorial001.py b/docs_src/query_params_str_validations/tutorial001.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial001.py
rename to docs_src/query_params_str_validations/tutorial001.py
diff --git a/docs/src/query_params_str_validations/tutorial002.py b/docs_src/query_params_str_validations/tutorial002.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial002.py
rename to docs_src/query_params_str_validations/tutorial002.py
diff --git a/docs/src/query_params_str_validations/tutorial003.py b/docs_src/query_params_str_validations/tutorial003.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial003.py
rename to docs_src/query_params_str_validations/tutorial003.py
diff --git a/docs/src/query_params_str_validations/tutorial004.py b/docs_src/query_params_str_validations/tutorial004.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial004.py
rename to docs_src/query_params_str_validations/tutorial004.py
diff --git a/docs/src/query_params_str_validations/tutorial005.py b/docs_src/query_params_str_validations/tutorial005.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial005.py
rename to docs_src/query_params_str_validations/tutorial005.py
diff --git a/docs/src/query_params_str_validations/tutorial006.py b/docs_src/query_params_str_validations/tutorial006.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial006.py
rename to docs_src/query_params_str_validations/tutorial006.py
diff --git a/docs/src/query_params_str_validations/tutorial007.py b/docs_src/query_params_str_validations/tutorial007.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial007.py
rename to docs_src/query_params_str_validations/tutorial007.py
diff --git a/docs/src/query_params_str_validations/tutorial008.py b/docs_src/query_params_str_validations/tutorial008.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial008.py
rename to docs_src/query_params_str_validations/tutorial008.py
diff --git a/docs/src/query_params_str_validations/tutorial009.py b/docs_src/query_params_str_validations/tutorial009.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial009.py
rename to docs_src/query_params_str_validations/tutorial009.py
diff --git a/docs/src/query_params_str_validations/tutorial010.py b/docs_src/query_params_str_validations/tutorial010.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial010.py
rename to docs_src/query_params_str_validations/tutorial010.py
diff --git a/docs/src/query_params_str_validations/tutorial011.py b/docs_src/query_params_str_validations/tutorial011.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial011.py
rename to docs_src/query_params_str_validations/tutorial011.py
diff --git a/docs/src/query_params_str_validations/tutorial012.py b/docs_src/query_params_str_validations/tutorial012.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial012.py
rename to docs_src/query_params_str_validations/tutorial012.py
diff --git a/docs/src/query_params_str_validations/tutorial013.py b/docs_src/query_params_str_validations/tutorial013.py
similarity index 100%
rename from docs/src/query_params_str_validations/tutorial013.py
rename to docs_src/query_params_str_validations/tutorial013.py
diff --git a/docs/src/request_files/tutorial001.py b/docs_src/request_files/tutorial001.py
similarity index 100%
rename from docs/src/request_files/tutorial001.py
rename to docs_src/request_files/tutorial001.py
diff --git a/docs/src/request_files/tutorial002.py b/docs_src/request_files/tutorial002.py
similarity index 100%
rename from docs/src/request_files/tutorial002.py
rename to docs_src/request_files/tutorial002.py
diff --git a/docs/src/request_forms/tutorial001.py b/docs_src/request_forms/tutorial001.py
similarity index 100%
rename from docs/src/request_forms/tutorial001.py
rename to docs_src/request_forms/tutorial001.py
diff --git a/docs/src/request_forms_and_files/tutorial001.py b/docs_src/request_forms_and_files/tutorial001.py
similarity index 100%
rename from docs/src/request_forms_and_files/tutorial001.py
rename to docs_src/request_forms_and_files/tutorial001.py
diff --git a/docs/src/response_change_status_code/tutorial001.py b/docs_src/response_change_status_code/tutorial001.py
similarity index 100%
rename from docs/src/response_change_status_code/tutorial001.py
rename to docs_src/response_change_status_code/tutorial001.py
diff --git a/docs/src/response_cookies/tutorial001.py b/docs_src/response_cookies/tutorial001.py
similarity index 100%
rename from docs/src/response_cookies/tutorial001.py
rename to docs_src/response_cookies/tutorial001.py
diff --git a/docs/src/response_cookies/tutorial002.py b/docs_src/response_cookies/tutorial002.py
similarity index 100%
rename from docs/src/response_cookies/tutorial002.py
rename to docs_src/response_cookies/tutorial002.py
diff --git a/docs/src/response_directly/tutorial001.py b/docs_src/response_directly/tutorial001.py
similarity index 100%
rename from docs/src/response_directly/tutorial001.py
rename to docs_src/response_directly/tutorial001.py
diff --git a/docs/src/response_directly/tutorial002.py b/docs_src/response_directly/tutorial002.py
similarity index 100%
rename from docs/src/response_directly/tutorial002.py
rename to docs_src/response_directly/tutorial002.py
diff --git a/docs/src/response_headers/tutorial001.py b/docs_src/response_headers/tutorial001.py
similarity index 100%
rename from docs/src/response_headers/tutorial001.py
rename to docs_src/response_headers/tutorial001.py
diff --git a/docs/src/response_headers/tutorial002.py b/docs_src/response_headers/tutorial002.py
similarity index 100%
rename from docs/src/response_headers/tutorial002.py
rename to docs_src/response_headers/tutorial002.py
diff --git a/docs/src/response_model/tutorial001.py b/docs_src/response_model/tutorial001.py
similarity index 100%
rename from docs/src/response_model/tutorial001.py
rename to docs_src/response_model/tutorial001.py
diff --git a/docs/src/response_model/tutorial002.py b/docs_src/response_model/tutorial002.py
similarity index 100%
rename from docs/src/response_model/tutorial002.py
rename to docs_src/response_model/tutorial002.py
diff --git a/docs/src/response_model/tutorial003.py b/docs_src/response_model/tutorial003.py
similarity index 100%
rename from docs/src/response_model/tutorial003.py
rename to docs_src/response_model/tutorial003.py
diff --git a/docs/src/response_model/tutorial004.py b/docs_src/response_model/tutorial004.py
similarity index 100%
rename from docs/src/response_model/tutorial004.py
rename to docs_src/response_model/tutorial004.py
diff --git a/docs/src/response_model/tutorial005.py b/docs_src/response_model/tutorial005.py
similarity index 100%
rename from docs/src/response_model/tutorial005.py
rename to docs_src/response_model/tutorial005.py
diff --git a/docs/src/response_model/tutorial006.py b/docs_src/response_model/tutorial006.py
similarity index 100%
rename from docs/src/response_model/tutorial006.py
rename to docs_src/response_model/tutorial006.py
diff --git a/docs/src/response_status_code/tutorial001.py b/docs_src/response_status_code/tutorial001.py
similarity index 100%
rename from docs/src/response_status_code/tutorial001.py
rename to docs_src/response_status_code/tutorial001.py
diff --git a/docs/src/response_status_code/tutorial002.py b/docs_src/response_status_code/tutorial002.py
similarity index 100%
rename from docs/src/response_status_code/tutorial002.py
rename to docs_src/response_status_code/tutorial002.py
diff --git a/docs_src/schema_extra_example/tutorial001.py b/docs_src/schema_extra_example/tutorial001.py
new file mode 100644
index 0000000000000..cd4d45f51d4d2
--- /dev/null
+++ b/docs_src/schema_extra_example/tutorial001.py
@@ -0,0 +1,27 @@
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ description: str = None
+ price: float
+ tax: float = None
+
+ class Config:
+ schema_extra = {
+ "example": {
+ "name": "Foo",
+ "description": "A very nice Item",
+ "price": 35.4,
+ "tax": 3.2,
+ }
+ }
+
+
+@app.put("/items/{item_id}")
+async def update_item(*, item_id: int, item: Item):
+ results = {"item_id": item_id, "item": item}
+ return results
diff --git a/docs_src/schema_extra_example/tutorial002.py b/docs_src/schema_extra_example/tutorial002.py
new file mode 100644
index 0000000000000..edf9897d08b98
--- /dev/null
+++ b/docs_src/schema_extra_example/tutorial002.py
@@ -0,0 +1,17 @@
+from fastapi import FastAPI
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str = Field(..., example="Foo")
+ description: str = Field(None, example="A very nice Item")
+ price: float = Field(..., example=35.4)
+ tax: float = Field(None, example=3.2)
+
+
+@app.put("/items/{item_id}")
+async def update_item(*, item_id: int, item: Item):
+ results = {"item_id": item_id, "item": item}
+ return results
diff --git a/docs/src/body_fields/tutorial002.py b/docs_src/schema_extra_example/tutorial003.py
similarity index 100%
rename from docs/src/body_fields/tutorial002.py
rename to docs_src/schema_extra_example/tutorial003.py
diff --git a/docs/src/security/tutorial001.py b/docs_src/security/tutorial001.py
similarity index 100%
rename from docs/src/security/tutorial001.py
rename to docs_src/security/tutorial001.py
diff --git a/docs/src/security/tutorial002.py b/docs_src/security/tutorial002.py
similarity index 100%
rename from docs/src/security/tutorial002.py
rename to docs_src/security/tutorial002.py
diff --git a/docs/src/security/tutorial003.py b/docs_src/security/tutorial003.py
similarity index 100%
rename from docs/src/security/tutorial003.py
rename to docs_src/security/tutorial003.py
diff --git a/docs/src/security/tutorial004.py b/docs_src/security/tutorial004.py
similarity index 100%
rename from docs/src/security/tutorial004.py
rename to docs_src/security/tutorial004.py
diff --git a/docs/src/security/tutorial005.py b/docs_src/security/tutorial005.py
similarity index 100%
rename from docs/src/security/tutorial005.py
rename to docs_src/security/tutorial005.py
diff --git a/docs/src/security/tutorial006.py b/docs_src/security/tutorial006.py
similarity index 100%
rename from docs/src/security/tutorial006.py
rename to docs_src/security/tutorial006.py
diff --git a/docs/src/security/tutorial007.py b/docs_src/security/tutorial007.py
similarity index 100%
rename from docs/src/security/tutorial007.py
rename to docs_src/security/tutorial007.py
diff --git a/docs/src/sql_databases/__init__.py b/docs_src/settings/app01/__init__.py
similarity index 100%
rename from docs/src/sql_databases/__init__.py
rename to docs_src/settings/app01/__init__.py
diff --git a/docs_src/settings/app01/config.py b/docs_src/settings/app01/config.py
new file mode 100644
index 0000000000000..defede9db401e
--- /dev/null
+++ b/docs_src/settings/app01/config.py
@@ -0,0 +1,10 @@
+from pydantic import BaseSettings
+
+
+class Settings(BaseSettings):
+ app_name: str = "Awesome API"
+ admin_email: str
+ items_per_user: int = 50
+
+
+settings = Settings()
diff --git a/docs_src/settings/app01/main.py b/docs_src/settings/app01/main.py
new file mode 100644
index 0000000000000..53503797ecb31
--- /dev/null
+++ b/docs_src/settings/app01/main.py
@@ -0,0 +1,14 @@
+from fastapi import FastAPI
+
+from . import config
+
+app = FastAPI()
+
+
+@app.get("/info")
+async def info():
+ return {
+ "app_name": config.settings.app_name,
+ "admin_email": config.settings.admin_email,
+ "items_per_user": config.settings.items_per_user,
+ }
diff --git a/docs/src/sql_databases/sql_app/__init__.py b/docs_src/settings/app02/__init__.py
similarity index 100%
rename from docs/src/sql_databases/sql_app/__init__.py
rename to docs_src/settings/app02/__init__.py
diff --git a/docs_src/settings/app02/config.py b/docs_src/settings/app02/config.py
new file mode 100644
index 0000000000000..9a7829135690d
--- /dev/null
+++ b/docs_src/settings/app02/config.py
@@ -0,0 +1,7 @@
+from pydantic import BaseSettings
+
+
+class Settings(BaseSettings):
+ app_name: str = "Awesome API"
+ admin_email: str
+ items_per_user: int = 50
diff --git a/docs_src/settings/app02/main.py b/docs_src/settings/app02/main.py
new file mode 100644
index 0000000000000..69bc8c6e0eb6b
--- /dev/null
+++ b/docs_src/settings/app02/main.py
@@ -0,0 +1,21 @@
+from functools import lru_cache
+
+from fastapi import Depends, FastAPI
+
+from . import config
+
+app = FastAPI()
+
+
+@lru_cache()
+def get_settings():
+ return config.Settings()
+
+
+@app.get("/info")
+async def info(settings: config.Settings = Depends(get_settings)):
+ return {
+ "app_name": settings.app_name,
+ "admin_email": settings.admin_email,
+ "items_per_user": settings.items_per_user,
+ }
diff --git a/docs_src/settings/app02/test_main.py b/docs_src/settings/app02/test_main.py
new file mode 100644
index 0000000000000..44d9f837963d8
--- /dev/null
+++ b/docs_src/settings/app02/test_main.py
@@ -0,0 +1,23 @@
+from fastapi.testclient import TestClient
+
+from . import config, main
+
+client = TestClient(main.app)
+
+
+def get_settings_override():
+ return config.Settings(admin_email="testing_admin@example.com")
+
+
+main.app.dependency_overrides[main.get_settings] = get_settings_override
+
+
+def test_app():
+
+ response = client.get("/info")
+ data = response.json()
+ assert data == {
+ "app_name": "Awesome API",
+ "admin_email": "testing_admin@example.com",
+ "items_per_user": 50,
+ }
diff --git a/docs/src/sql_databases_peewee/__init__.py b/docs_src/settings/app03/__init__.py
similarity index 100%
rename from docs/src/sql_databases_peewee/__init__.py
rename to docs_src/settings/app03/__init__.py
diff --git a/docs_src/settings/app03/config.py b/docs_src/settings/app03/config.py
new file mode 100644
index 0000000000000..e1c3ee30063b7
--- /dev/null
+++ b/docs_src/settings/app03/config.py
@@ -0,0 +1,10 @@
+from pydantic import BaseSettings
+
+
+class Settings(BaseSettings):
+ app_name: str = "Awesome API"
+ admin_email: str
+ items_per_user: int = 50
+
+ class Config:
+ env_file = ".env"
diff --git a/docs_src/settings/app03/main.py b/docs_src/settings/app03/main.py
new file mode 100644
index 0000000000000..69bc8c6e0eb6b
--- /dev/null
+++ b/docs_src/settings/app03/main.py
@@ -0,0 +1,21 @@
+from functools import lru_cache
+
+from fastapi import Depends, FastAPI
+
+from . import config
+
+app = FastAPI()
+
+
+@lru_cache()
+def get_settings():
+ return config.Settings()
+
+
+@app.get("/info")
+async def info(settings: config.Settings = Depends(get_settings)):
+ return {
+ "app_name": settings.app_name,
+ "admin_email": settings.admin_email,
+ "items_per_user": settings.items_per_user,
+ }
diff --git a/docs_src/settings/tutorial001.py b/docs_src/settings/tutorial001.py
new file mode 100644
index 0000000000000..0cfd1b6632f0b
--- /dev/null
+++ b/docs_src/settings/tutorial001.py
@@ -0,0 +1,21 @@
+from fastapi import FastAPI
+from pydantic import BaseSettings
+
+
+class Settings(BaseSettings):
+ app_name: str = "Awesome API"
+ admin_email: str
+ items_per_user: int = 50
+
+
+settings = Settings()
+app = FastAPI()
+
+
+@app.get("/info")
+async def info():
+ return {
+ "app_name": settings.app_name,
+ "admin_email": settings.admin_email,
+ "items_per_user": settings.items_per_user,
+ }
diff --git a/docs/src/sql_databases_peewee/sql_app/__init__.py b/docs_src/sql_databases/__init__.py
similarity index 100%
rename from docs/src/sql_databases_peewee/sql_app/__init__.py
rename to docs_src/sql_databases/__init__.py
diff --git a/docs/src/websockets/__init__.py b/docs_src/sql_databases/sql_app/__init__.py
similarity index 100%
rename from docs/src/websockets/__init__.py
rename to docs_src/sql_databases/sql_app/__init__.py
diff --git a/docs/src/sql_databases/sql_app/alt_main.py b/docs_src/sql_databases/sql_app/alt_main.py
similarity index 100%
rename from docs/src/sql_databases/sql_app/alt_main.py
rename to docs_src/sql_databases/sql_app/alt_main.py
diff --git a/docs/src/sql_databases/sql_app/crud.py b/docs_src/sql_databases/sql_app/crud.py
similarity index 100%
rename from docs/src/sql_databases/sql_app/crud.py
rename to docs_src/sql_databases/sql_app/crud.py
diff --git a/docs/src/sql_databases/sql_app/database.py b/docs_src/sql_databases/sql_app/database.py
similarity index 88%
rename from docs/src/sql_databases/sql_app/database.py
rename to docs_src/sql_databases/sql_app/database.py
index 73fc456a24c26..45a8b9f6942b3 100644
--- a/docs/src/sql_databases/sql_app/database.py
+++ b/docs_src/sql_databases/sql_app/database.py
@@ -2,7 +2,7 @@
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
-SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
+SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
engine = create_engine(
diff --git a/docs/src/sql_databases/sql_app/main.py b/docs_src/sql_databases/sql_app/main.py
similarity index 98%
rename from docs/src/sql_databases/sql_app/main.py
rename to docs_src/sql_databases/sql_app/main.py
index 33f63d332c4d8..e7508c59d45d0 100644
--- a/docs/src/sql_databases/sql_app/main.py
+++ b/docs_src/sql_databases/sql_app/main.py
@@ -13,8 +13,8 @@
# Dependency
def get_db():
+ db = SessionLocal()
try:
- db = SessionLocal()
yield db
finally:
db.close()
diff --git a/docs/src/sql_databases/sql_app/models.py b/docs_src/sql_databases/sql_app/models.py
similarity index 100%
rename from docs/src/sql_databases/sql_app/models.py
rename to docs_src/sql_databases/sql_app/models.py
diff --git a/docs/src/sql_databases/sql_app/schemas.py b/docs_src/sql_databases/sql_app/schemas.py
similarity index 100%
rename from docs/src/sql_databases/sql_app/schemas.py
rename to docs_src/sql_databases/sql_app/schemas.py
diff --git a/tests/test_tutorial/test_application_configuration/__init__.py b/docs_src/sql_databases/sql_app/tests/__init__.py
similarity index 100%
rename from tests/test_tutorial/test_application_configuration/__init__.py
rename to docs_src/sql_databases/sql_app/tests/__init__.py
diff --git a/docs_src/sql_databases/sql_app/tests/test_sql_app.py b/docs_src/sql_databases/sql_app/tests/test_sql_app.py
new file mode 100644
index 0000000000000..c60c3356f85ed
--- /dev/null
+++ b/docs_src/sql_databases/sql_app/tests/test_sql_app.py
@@ -0,0 +1,47 @@
+from fastapi.testclient import TestClient
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from ..database import Base
+from ..main import app, get_db
+
+SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
+
+engine = create_engine(
+ SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
+)
+TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
+
+
+Base.metadata.create_all(bind=engine)
+
+
+def override_get_db():
+ try:
+ db = TestingSessionLocal()
+ yield db
+ finally:
+ db.close()
+
+
+app.dependency_overrides[get_db] = override_get_db
+
+client = TestClient(app)
+
+
+def test_create_user():
+ response = client.post(
+ "/users/",
+ json={"email": "deadpool@example.com", "password": "chimichangas4life"},
+ )
+ assert response.status_code == 200, response.text
+ data = response.json()
+ assert data["email"] == "deadpool@example.com"
+ assert "id" in data
+ user_id = data["id"]
+
+ response = client.get(f"/users/{user_id}")
+ assert response.status_code == 200, response.text
+ data = response.json()
+ assert data["email"] == "deadpool@example.com"
+ assert data["id"] == user_id
diff --git a/docs_src/sql_databases_peewee/__init__.py b/docs_src/sql_databases_peewee/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/docs_src/sql_databases_peewee/sql_app/__init__.py b/docs_src/sql_databases_peewee/sql_app/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/docs/src/sql_databases_peewee/sql_app/crud.py b/docs_src/sql_databases_peewee/sql_app/crud.py
similarity index 100%
rename from docs/src/sql_databases_peewee/sql_app/crud.py
rename to docs_src/sql_databases_peewee/sql_app/crud.py
diff --git a/docs/src/sql_databases_peewee/sql_app/database.py b/docs_src/sql_databases_peewee/sql_app/database.py
similarity index 100%
rename from docs/src/sql_databases_peewee/sql_app/database.py
rename to docs_src/sql_databases_peewee/sql_app/database.py
diff --git a/docs/src/sql_databases_peewee/sql_app/main.py b/docs_src/sql_databases_peewee/sql_app/main.py
similarity index 100%
rename from docs/src/sql_databases_peewee/sql_app/main.py
rename to docs_src/sql_databases_peewee/sql_app/main.py
diff --git a/docs/src/sql_databases_peewee/sql_app/models.py b/docs_src/sql_databases_peewee/sql_app/models.py
similarity index 100%
rename from docs/src/sql_databases_peewee/sql_app/models.py
rename to docs_src/sql_databases_peewee/sql_app/models.py
diff --git a/docs/src/sql_databases_peewee/sql_app/schemas.py b/docs_src/sql_databases_peewee/sql_app/schemas.py
similarity index 100%
rename from docs/src/sql_databases_peewee/sql_app/schemas.py
rename to docs_src/sql_databases_peewee/sql_app/schemas.py
diff --git a/docs/src/static_files/tutorial001.py b/docs_src/static_files/tutorial001.py
similarity index 100%
rename from docs/src/static_files/tutorial001.py
rename to docs_src/static_files/tutorial001.py
diff --git a/docs/src/sub_applications/tutorial001.py b/docs_src/sub_applications/tutorial001.py
similarity index 85%
rename from docs/src/sub_applications/tutorial001.py
rename to docs_src/sub_applications/tutorial001.py
index 3b1f77a82a3aa..57e627e8041d2 100644
--- a/docs/src/sub_applications/tutorial001.py
+++ b/docs_src/sub_applications/tutorial001.py
@@ -8,7 +8,7 @@ def read_main():
return {"message": "Hello World from main app"}
-subapi = FastAPI(openapi_prefix="/subapi")
+subapi = FastAPI()
@subapi.get("/sub")
diff --git a/docs/src/templates/static/styles.css b/docs_src/templates/static/styles.css
similarity index 100%
rename from docs/src/templates/static/styles.css
rename to docs_src/templates/static/styles.css
diff --git a/docs/src/templates/templates/item.html b/docs_src/templates/templates/item.html
similarity index 100%
rename from docs/src/templates/templates/item.html
rename to docs_src/templates/templates/item.html
diff --git a/docs/src/templates/tutorial001.py b/docs_src/templates/tutorial001.py
similarity index 100%
rename from docs/src/templates/tutorial001.py
rename to docs_src/templates/tutorial001.py
diff --git a/docs/src/using_request_directly/tutorial001.py b/docs_src/using_request_directly/tutorial001.py
similarity index 100%
rename from docs/src/using_request_directly/tutorial001.py
rename to docs_src/using_request_directly/tutorial001.py
diff --git a/docs_src/websockets/__init__.py b/docs_src/websockets/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/docs/src/websockets/tutorial001.py b/docs_src/websockets/tutorial001.py
similarity index 100%
rename from docs/src/websockets/tutorial001.py
rename to docs_src/websockets/tutorial001.py
diff --git a/docs/src/websockets/tutorial002.py b/docs_src/websockets/tutorial002.py
similarity index 100%
rename from docs/src/websockets/tutorial002.py
rename to docs_src/websockets/tutorial002.py
diff --git a/docs/src/wsgi/tutorial001.py b/docs_src/wsgi/tutorial001.py
similarity index 100%
rename from docs/src/wsgi/tutorial001.py
rename to docs_src/wsgi/tutorial001.py
index 7a4011e7e42cb..500ecf883eaf6 100644
--- a/docs/src/wsgi/tutorial001.py
+++ b/docs_src/wsgi/tutorial001.py
@@ -1,6 +1,6 @@
-from flask import Flask, escape, request
from fastapi import FastAPI
from fastapi.middleware.wsgi import WSGIMiddleware
+from flask import Flask, escape, request
flask_app = Flask(__name__)
diff --git a/fastapi/__init__.py b/fastapi/__init__.py
index af924de869cf2..a0244bfaf5291 100644
--- a/fastapi/__init__.py
+++ b/fastapi/__init__.py
@@ -1,6 +1,6 @@
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
-__version__ = "0.52.0"
+__version__ = "0.56.0"
from starlette import status
diff --git a/fastapi/applications.py b/fastapi/applications.py
index 8270e54fdf4d0..39e694fae971f 100644
--- a/fastapi/applications.py
+++ b/fastapi/applications.py
@@ -8,6 +8,7 @@
request_validation_exception_handler,
)
from fastapi.exceptions import RequestValidationError
+from fastapi.logger import logger
from fastapi.openapi.docs import (
get_redoc_html,
get_swagger_ui_html,
@@ -36,7 +37,6 @@ def __init__(
description: str = "",
version: str = "0.1.0",
openapi_url: Optional[str] = "/openapi.json",
- openapi_prefix: str = "",
default_response_class: Type[Response] = JSONResponse,
docs_url: Optional[str] = "/docs",
redoc_url: Optional[str] = "/redoc",
@@ -46,6 +46,8 @@ def __init__(
exception_handlers: Dict[Union[int, Type[Exception]], Callable] = None,
on_startup: Sequence[Callable] = None,
on_shutdown: Sequence[Callable] = None,
+ openapi_prefix: str = "",
+ root_path: str = "",
**extra: Dict[str, Any],
) -> None:
self.default_response_class = default_response_class
@@ -68,7 +70,15 @@ def __init__(
self.description = description
self.version = version
self.openapi_url = openapi_url
- self.openapi_prefix = openapi_prefix.rstrip("/")
+ # TODO: remove when discarding the openapi_prefix parameter
+ if openapi_prefix:
+ logger.warning(
+ '"openapi_prefix" has been deprecated in favor of "root_path", which '
+ "follows more closely the ASGI standard, is simpler, and more "
+ "automatic. Check the docs at "
+ "https://fastapi.tiangolo.com/advanced/sub-applications-proxy/"
+ )
+ self.root_path = root_path or openapi_prefix
self.docs_url = docs_url
self.redoc_url = redoc_url
self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url
@@ -81,13 +91,10 @@ def __init__(
if self.openapi_url:
assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"
assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'"
-
- if self.docs_url or self.redoc_url:
- assert self.openapi_url, "The openapi_url is required for the docs"
self.openapi_schema: Optional[Dict[str, Any]] = None
self.setup()
- def openapi(self) -> Dict:
+ def openapi(self, openapi_prefix: str = "") -> Dict:
if not self.openapi_schema:
self.openapi_schema = get_openapi(
title=self.title,
@@ -95,7 +102,7 @@ def openapi(self) -> Dict:
openapi_version=self.openapi_version,
description=self.description,
routes=self.routes,
- openapi_prefix=self.openapi_prefix,
+ openapi_prefix=openapi_prefix,
)
return self.openapi_schema
@@ -103,17 +110,22 @@ def setup(self) -> None:
if self.openapi_url:
async def openapi(req: Request) -> JSONResponse:
- return JSONResponse(self.openapi())
+ root_path = req.scope.get("root_path", "").rstrip("/")
+ return JSONResponse(self.openapi(root_path))
self.add_route(self.openapi_url, openapi, include_in_schema=False)
- openapi_url = self.openapi_prefix + self.openapi_url
if self.openapi_url and self.docs_url:
async def swagger_ui_html(req: Request) -> HTMLResponse:
+ root_path = req.scope.get("root_path", "").rstrip("/")
+ openapi_url = root_path + self.openapi_url
+ oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url
+ if oauth2_redirect_url:
+ oauth2_redirect_url = root_path + oauth2_redirect_url
return get_swagger_ui_html(
openapi_url=openapi_url,
title=self.title + " - Swagger UI",
- oauth2_redirect_url=self.swagger_ui_oauth2_redirect_url,
+ oauth2_redirect_url=oauth2_redirect_url,
init_oauth=self.swagger_ui_init_oauth,
)
@@ -132,6 +144,8 @@ async def swagger_ui_redirect(req: Request) -> HTMLResponse:
if self.openapi_url and self.redoc_url:
async def redoc_html(req: Request) -> HTMLResponse:
+ root_path = req.scope.get("root_path", "").rstrip("/")
+ openapi_url = root_path + self.openapi_url
return get_redoc_html(
openapi_url=openapi_url, title=self.title + " - ReDoc"
)
@@ -143,6 +157,8 @@ async def redoc_html(req: Request) -> HTMLResponse:
)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if self.root_path:
+ scope["root_path"] = self.root_path
if AsyncExitStack:
async with AsyncExitStack() as stack:
scope["fastapi_astack"] = stack
@@ -171,6 +187,8 @@ def add_api_route(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -197,6 +215,8 @@ def add_api_route(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -222,6 +242,8 @@ def api_route(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -250,6 +272,8 @@ def decorator(func: Callable) -> Callable:
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -309,6 +333,8 @@ def get(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -334,6 +360,8 @@ def get(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -359,6 +387,8 @@ def put(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -384,6 +414,8 @@ def put(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -409,6 +441,8 @@ def post(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -434,6 +468,8 @@ def post(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -459,6 +495,8 @@ def delete(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -484,6 +522,8 @@ def delete(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -509,6 +549,8 @@ def options(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -534,6 +576,8 @@ def options(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -559,6 +603,8 @@ def head(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -584,6 +630,8 @@ def head(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -609,6 +657,8 @@ def patch(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -634,6 +684,8 @@ def patch(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -659,6 +711,8 @@ def trace(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -684,6 +738,8 @@ def trace(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py
index 543479be8814b..1a660f5d355fa 100644
--- a/fastapi/dependencies/utils.py
+++ b/fastapi/dependencies/utils.py
@@ -188,6 +188,16 @@ def get_flat_dependant(
return flat_dependant
+def get_flat_params(dependant: Dependant) -> List[ModelField]:
+ flat_dependant = get_flat_dependant(dependant, skip_repeats=True)
+ return (
+ flat_dependant.path_params
+ + flat_dependant.query_params
+ + flat_dependant.header_params
+ + flat_dependant.cookie_params
+ )
+
+
def is_scalar_field(field: ModelField) -> bool:
field_info = get_field_info(field)
if not (
@@ -704,8 +714,14 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]:
first_param = flat_dependant.body_params[0]
field_info = get_field_info(first_param)
embed = getattr(field_info, "embed", None)
- if len(flat_dependant.body_params) == 1 and not embed:
+ body_param_names_set = set([param.name for param in flat_dependant.body_params])
+ if len(body_param_names_set) == 1 and not embed:
return get_schema_compatible_field(field=first_param)
+ # If one field requires to embed, all have to be embedded
+ # in case a sub-dependency is evaluated with a single unique body field
+ # That is combined (embedded) with other body fields
+ for param in flat_dependant.body_params:
+ setattr(get_field_info(param), "embed", True)
model_name = "Body_" + name
BodyModel = create_model(model_name)
for f in flat_dependant.body_params:
diff --git a/fastapi/encoders.py b/fastapi/encoders.py
index ae4794bae8d94..26ceb21445f15 100644
--- a/fastapi/encoders.py
+++ b/fastapi/encoders.py
@@ -34,7 +34,8 @@ def jsonable_encoder(
by_alias: bool = True,
skip_defaults: bool = None,
exclude_unset: bool = False,
- include_none: bool = True,
+ exclude_defaults: bool = False,
+ exclude_none: bool = False,
custom_encoder: dict = {},
sqlalchemy_safe: bool = True,
) -> Any:
@@ -58,8 +59,12 @@ def jsonable_encoder(
exclude=exclude,
by_alias=by_alias,
exclude_unset=bool(exclude_unset or skip_defaults),
+ exclude_none=exclude_none,
+ exclude_defaults=exclude_defaults,
)
else: # pragma: nocover
+ if exclude_defaults:
+ raise ValueError("Cannot use exclude_defaults")
obj_dict = obj.dict(
include=include,
exclude=exclude,
@@ -68,7 +73,8 @@ def jsonable_encoder(
)
return jsonable_encoder(
obj_dict,
- include_none=include_none,
+ exclude_none=exclude_none,
+ exclude_defaults=exclude_defaults,
custom_encoder=encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
@@ -87,14 +93,14 @@ def jsonable_encoder(
or (not isinstance(key, str))
or (not key.startswith("_sa"))
)
- and (value is not None or include_none)
+ and (value is not None or not exclude_none)
and ((include and key in include) or key not in exclude)
):
encoded_key = jsonable_encoder(
key,
by_alias=by_alias,
exclude_unset=exclude_unset,
- include_none=include_none,
+ exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
@@ -102,7 +108,7 @@ def jsonable_encoder(
value,
by_alias=by_alias,
exclude_unset=exclude_unset,
- include_none=include_none,
+ exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
@@ -118,7 +124,8 @@ def jsonable_encoder(
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
- include_none=include_none,
+ exclude_defaults=exclude_defaults,
+ exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
@@ -153,7 +160,8 @@ def jsonable_encoder(
data,
by_alias=by_alias,
exclude_unset=exclude_unset,
- include_none=include_none,
+ exclude_defaults=exclude_defaults,
+ exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py
index 91f90ec583785..b5778327bbad1 100644
--- a/fastapi/openapi/utils.py
+++ b/fastapi/openapi/utils.py
@@ -1,9 +1,10 @@
import http.client
-from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, cast
+from enum import Enum
+from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, cast
from fastapi import routing
from fastapi.dependencies.models import Dependant
-from fastapi.dependencies.utils import get_flat_dependant
+from fastapi.dependencies.utils import get_flat_dependant, get_flat_params
from fastapi.encoders import jsonable_encoder
from fastapi.openapi.constants import (
METHODS_WITH_BODY,
@@ -15,11 +16,14 @@
from fastapi.utils import (
generate_operation_id_for_path,
get_field_info,
- get_flat_models_from_routes,
get_model_definitions,
)
from pydantic import BaseModel
-from pydantic.schema import field_schema, get_model_name_map
+from pydantic.schema import (
+ field_schema,
+ get_flat_models_from_fields,
+ get_model_name_map,
+)
from pydantic.utils import lenient_issubclass
from starlette.responses import JSONResponse
from starlette.routing import BaseRoute
@@ -64,16 +68,6 @@
}
-def get_openapi_params(dependant: Dependant) -> List[ModelField]:
- flat_dependant = get_flat_dependant(dependant, skip_repeats=True)
- return (
- flat_dependant.path_params
- + flat_dependant.query_params
- + flat_dependant.header_params
- + flat_dependant.cookie_params
- )
-
-
def get_openapi_security_definitions(flat_dependant: Dependant) -> Tuple[Dict, List]:
security_definitions = {}
operation_security = []
@@ -81,7 +75,7 @@ def get_openapi_security_definitions(flat_dependant: Dependant) -> Tuple[Dict, L
security_definition = jsonable_encoder(
security_requirement.security_scheme.model,
by_alias=True,
- include_none=False,
+ exclude_none=True,
)
security_name = security_requirement.security_scheme.scheme_name
security_definitions[security_name] = security_definition
@@ -90,17 +84,22 @@ def get_openapi_security_definitions(flat_dependant: Dependant) -> Tuple[Dict, L
def get_openapi_operation_parameters(
+ *,
all_route_params: Sequence[ModelField],
+ model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str]
) -> List[Dict[str, Any]]:
parameters = []
for param in all_route_params:
field_info = get_field_info(param)
field_info = cast(Param, field_info)
+ # ignore mypy error until enum schemas are released
parameter = {
"name": param.alias,
"in": field_info.in_.value,
"required": param.required,
- "schema": field_schema(param, model_name_map={})[0],
+ "schema": field_schema(
+ param, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore
+ )[0],
}
if field_info.description:
parameter["description"] = field_info.description
@@ -111,13 +110,16 @@ def get_openapi_operation_parameters(
def get_openapi_operation_request_body(
- *, body_field: Optional[ModelField], model_name_map: Dict[Type[BaseModel], str]
+ *,
+ body_field: Optional[ModelField],
+ model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str]
) -> Optional[Dict]:
if not body_field:
return None
assert isinstance(body_field, ModelField)
+ # ignore mypy error until enum schemas are released
body_schema, _, _ = field_schema(
- body_field, model_name_map=model_name_map, ref_prefix=REF_PREFIX
+ body_field, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore
)
field_info = cast(Body, get_field_info(body_field))
request_media_type = field_info.media_type
@@ -176,8 +178,10 @@ def get_openapi_path(
operation.setdefault("security", []).extend(operation_security)
if security_definitions:
security_schemes.update(security_definitions)
- all_route_params = get_openapi_params(route.dependant)
- operation_parameters = get_openapi_operation_parameters(all_route_params)
+ all_route_params = get_flat_params(route.dependant)
+ operation_parameters = get_openapi_operation_parameters(
+ all_route_params=all_route_params, model_name_map=model_name_map
+ )
parameters.extend(operation_parameters)
if parameters:
operation["parameters"] = list(
@@ -270,6 +274,38 @@ def get_openapi_path(
return path, security_schemes, definitions
+def get_flat_models_from_routes(
+ routes: Sequence[BaseRoute],
+) -> Set[Union[Type[BaseModel], Type[Enum]]]:
+ body_fields_from_routes: List[ModelField] = []
+ responses_from_routes: List[ModelField] = []
+ request_fields_from_routes: List[ModelField] = []
+ callback_flat_models: Set[Union[Type[BaseModel], Type[Enum]]] = set()
+ for route in routes:
+ if getattr(route, "include_in_schema", None) and isinstance(
+ route, routing.APIRoute
+ ):
+ if route.body_field:
+ assert isinstance(
+ route.body_field, ModelField
+ ), "A request body must be a Pydantic Field"
+ body_fields_from_routes.append(route.body_field)
+ if route.response_field:
+ responses_from_routes.append(route.response_field)
+ if route.response_fields:
+ responses_from_routes.extend(route.response_fields.values())
+ if route.callbacks:
+ callback_flat_models |= get_flat_models_from_routes(route.callbacks)
+ params = get_flat_params(route.dependant)
+ request_fields_from_routes.extend(params)
+
+ flat_models = callback_flat_models | get_flat_models_from_fields(
+ body_fields_from_routes + responses_from_routes + request_fields_from_routes,
+ known_models=set(),
+ )
+ return flat_models
+
+
def get_openapi(
*,
title: str,
@@ -286,9 +322,11 @@ def get_openapi(
components: Dict[str, Dict] = {}
paths: Dict[str, Dict] = {}
flat_models = get_flat_models_from_routes(routes)
- model_name_map = get_model_name_map(flat_models)
+ # ignore mypy error until enum schemas are released
+ model_name_map = get_model_name_map(flat_models) # type: ignore
+ # ignore mypy error until enum schemas are released
definitions = get_model_definitions(
- flat_models=flat_models, model_name_map=model_name_map
+ flat_models=flat_models, model_name_map=model_name_map # type: ignore
)
for route in routes:
if isinstance(route, routing.APIRoute):
@@ -310,4 +348,4 @@ def get_openapi(
if components:
output["components"] = components
output["paths"] = paths
- return jsonable_encoder(OpenAPI(**output), by_alias=True, include_none=False)
+ return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True)
diff --git a/fastapi/routing.py b/fastapi/routing.py
index b36104869648a..3ac420e6e2296 100644
--- a/fastapi/routing.py
+++ b/fastapi/routing.py
@@ -48,6 +48,49 @@
from pydantic.fields import Field as ModelField # type: ignore
+def _prepare_response_content(
+ res: Any,
+ *,
+ by_alias: bool = True,
+ exclude_unset: bool,
+ exclude_defaults: bool = False,
+ exclude_none: bool = False,
+) -> Any:
+ if isinstance(res, BaseModel):
+ if PYDANTIC_1:
+ return res.dict(
+ by_alias=by_alias,
+ exclude_unset=exclude_unset,
+ exclude_defaults=exclude_defaults,
+ exclude_none=exclude_none,
+ )
+ else:
+ return res.dict(
+ by_alias=by_alias, skip_defaults=exclude_unset,
+ ) # pragma: nocover
+ elif isinstance(res, list):
+ return [
+ _prepare_response_content(
+ item,
+ exclude_unset=exclude_unset,
+ exclude_defaults=exclude_defaults,
+ exclude_none=exclude_none,
+ )
+ for item in res
+ ]
+ elif isinstance(res, dict):
+ return {
+ k: _prepare_response_content(
+ v,
+ exclude_unset=exclude_unset,
+ exclude_defaults=exclude_defaults,
+ exclude_none=exclude_none,
+ )
+ for k, v in res.items()
+ }
+ return res
+
+
async def serialize_response(
*,
field: ModelField = None,
@@ -56,17 +99,19 @@ async def serialize_response(
exclude: Union[SetIntStr, DictIntStrAny] = set(),
by_alias: bool = True,
exclude_unset: bool = False,
+ exclude_defaults: bool = False,
+ exclude_none: bool = False,
is_coroutine: bool = True,
) -> Any:
if field:
errors = []
- if exclude_unset and isinstance(response_content, BaseModel):
- if PYDANTIC_1:
- response_content = response_content.dict(exclude_unset=exclude_unset)
- else:
- response_content = response_content.dict(
- skip_defaults=exclude_unset
- ) # pragma: nocover
+ response_content = _prepare_response_content(
+ response_content,
+ by_alias=by_alias,
+ exclude_unset=exclude_unset,
+ exclude_defaults=exclude_defaults,
+ exclude_none=exclude_none,
+ )
if is_coroutine:
value, errors_ = field.validate(response_content, {}, loc=("response",))
else:
@@ -85,6 +130,8 @@ async def serialize_response(
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
+ exclude_defaults=exclude_defaults,
+ exclude_none=exclude_none,
)
else:
return jsonable_encoder(response_content)
@@ -113,6 +160,8 @@ def get_request_handler(
response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(),
response_model_by_alias: bool = True,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
dependency_overrides_provider: Any = None,
) -> Callable:
assert dependant.call is not None, "dependant.call must be a function"
@@ -159,6 +208,8 @@ async def app(request: Request) -> Response:
exclude=response_model_exclude,
by_alias=response_model_by_alias,
exclude_unset=response_model_exclude_unset,
+ exclude_defaults=response_model_exclude_defaults,
+ exclude_none=response_model_exclude_none,
is_coroutine=is_coroutine,
)
response = response_class(
@@ -237,6 +288,8 @@ def __init__(
response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(),
response_model_by_alias: bool = True,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Optional[Type[Response]] = None,
dependency_overrides_provider: Any = None,
@@ -308,6 +361,8 @@ def __init__(
self.response_model_exclude = response_model_exclude
self.response_model_by_alias = response_model_by_alias
self.response_model_exclude_unset = response_model_exclude_unset
+ self.response_model_exclude_defaults = response_model_exclude_defaults
+ self.response_model_exclude_none = response_model_exclude_none
self.include_in_schema = include_in_schema
self.response_class = response_class
@@ -334,6 +389,8 @@ def get_route_handler(self) -> Callable:
response_model_exclude=self.response_model_exclude,
response_model_by_alias=self.response_model_by_alias,
response_model_exclude_unset=self.response_model_exclude_unset,
+ response_model_exclude_defaults=self.response_model_exclude_defaults,
+ response_model_exclude_none=self.response_model_exclude_none,
dependency_overrides_provider=self.dependency_overrides_provider,
)
@@ -382,6 +439,8 @@ def add_api_route(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -411,6 +470,8 @@ def add_api_route(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -439,6 +500,8 @@ def api_route(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -468,6 +531,8 @@ def decorator(func: Callable) -> Callable:
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -480,7 +545,12 @@ def decorator(func: Callable) -> Callable:
def add_api_websocket_route(
self, path: str, endpoint: Callable, name: str = None
) -> None:
- route = APIWebSocketRoute(path, endpoint=endpoint, name=name)
+ route = APIWebSocketRoute(
+ path,
+ endpoint=endpoint,
+ name=name,
+ dependency_overrides_provider=self.dependency_overrides_provider,
+ )
self.routes.append(route)
def websocket(self, path: str, name: str = None) -> Callable:
@@ -537,6 +607,8 @@ def include_router(
response_model_exclude=route.response_model_exclude,
response_model_by_alias=route.response_model_by_alias,
response_model_exclude_unset=route.response_model_exclude_unset,
+ response_model_exclude_defaults=route.response_model_exclude_defaults,
+ response_model_exclude_none=route.response_model_exclude_none,
include_in_schema=route.include_in_schema,
response_class=route.response_class or default_response_class,
name=route.name,
@@ -583,6 +655,8 @@ def get(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -609,6 +683,8 @@ def get(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -634,6 +710,8 @@ def put(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -660,6 +738,8 @@ def put(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -685,6 +765,8 @@ def post(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -711,6 +793,8 @@ def post(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -736,6 +820,8 @@ def delete(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -762,6 +848,8 @@ def delete(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -787,6 +875,8 @@ def options(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -813,6 +903,8 @@ def options(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -838,6 +930,8 @@ def head(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -864,6 +958,8 @@ def head(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -889,6 +985,8 @@ def patch(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -915,6 +1013,8 @@ def patch(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
@@ -940,6 +1040,8 @@ def trace(
response_model_by_alias: bool = True,
response_model_skip_defaults: bool = None,
response_model_exclude_unset: bool = False,
+ response_model_exclude_defaults: bool = False,
+ response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: Type[Response] = None,
name: str = None,
@@ -966,6 +1068,8 @@ def trace(
response_model_exclude_unset=bool(
response_model_exclude_unset or response_model_skip_defaults
),
+ response_model_exclude_defaults=response_model_exclude_defaults,
+ response_model_exclude_none=response_model_exclude_none,
include_in_schema=include_in_schema,
response_class=response_class or self.default_response_class,
name=name,
diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py
index 781293bb9570d..c9edbae428c3c 100644
--- a/fastapi/security/oauth2.py
+++ b/fastapi/security/oauth2.py
@@ -81,7 +81,7 @@ def login(form_data: Oauth2PasswordRequestFormStrict = Depends()):
grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password".
This dependency is strict about it. If you want to be permissive, use instead the
- OAuth2PasswordRequestFormStrict dependency class.
+ OAuth2PasswordRequestForm dependency class.
username: username string. The OAuth2 spec requires the exact field name "username".
password: password string. The OAuth2 spec requires the exact field name "password".
scope: Optional string. Several scopes (each one a string) separated by spaces. E.g.
diff --git a/fastapi/utils.py b/fastapi/utils.py
index f24f280739d19..c9022fbc3b43b 100644
--- a/fastapi/utils.py
+++ b/fastapi/utils.py
@@ -1,17 +1,16 @@
import functools
import re
from dataclasses import is_dataclass
-from typing import Any, Dict, List, Optional, Sequence, Set, Type, Union, cast
+from enum import Enum
+from typing import Any, Dict, Optional, Set, Type, Union, cast
import fastapi
-from fastapi import routing
from fastapi.logger import logger
from fastapi.openapi.constants import REF_PREFIX
from pydantic import BaseConfig, BaseModel, create_model
from pydantic.class_validators import Validator
-from pydantic.schema import get_flat_models_from_fields, model_process_schema
+from pydantic.schema import model_process_schema
from pydantic.utils import lenient_issubclass
-from starlette.routing import BaseRoute
try:
from pydantic.fields import FieldInfo, ModelField, UndefinedType
@@ -50,38 +49,16 @@ def warning_response_model_skip_defaults_deprecated() -> None:
)
-def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]:
- body_fields_from_routes: List[ModelField] = []
- responses_from_routes: List[ModelField] = []
- callback_flat_models: Set[Type[BaseModel]] = set()
- for route in routes:
- if getattr(route, "include_in_schema", None) and isinstance(
- route, routing.APIRoute
- ):
- if route.body_field:
- assert isinstance(
- route.body_field, ModelField
- ), "A request body must be a Pydantic Field"
- body_fields_from_routes.append(route.body_field)
- if route.response_field:
- responses_from_routes.append(route.response_field)
- if route.response_fields:
- responses_from_routes.extend(route.response_fields.values())
- if route.callbacks:
- callback_flat_models |= get_flat_models_from_routes(route.callbacks)
- flat_models = callback_flat_models | get_flat_models_from_fields(
- body_fields_from_routes + responses_from_routes, known_models=set()
- )
- return flat_models
-
-
def get_model_definitions(
- *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str]
+ *,
+ flat_models: Set[Union[Type[BaseModel], Type[Enum]]],
+ model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
) -> Dict[str, Any]:
definitions: Dict[str, Dict] = {}
for model in flat_models:
+ # ignore mypy error until enum schemas are released
m_schema, m_definitions, m_nested_models = model_process_schema(
- model, model_name_map=model_name_map, ref_prefix=REF_PREFIX
+ model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore
)
definitions.update(m_definitions)
model_name = model_name_map[model]
@@ -131,17 +108,26 @@ def create_response_field(
)
-def create_cloned_field(field: ModelField) -> ModelField:
+def create_cloned_field(
+ field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None,
+) -> ModelField:
+ # _cloned_types has already cloned types, to support recursive models
+ if cloned_types is None:
+ cloned_types = dict()
original_type = field.type_
if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"):
original_type = original_type.__pydantic_model__ # type: ignore
use_type = original_type
if lenient_issubclass(original_type, BaseModel):
original_type = cast(Type[BaseModel], original_type)
- use_type = create_model(original_type.__name__, __base__=original_type)
- for f in original_type.__fields__.values():
- use_type.__fields__[f.name] = create_cloned_field(f)
-
+ use_type = cloned_types.get(original_type)
+ if use_type is None:
+ use_type = create_model(original_type.__name__, __base__=original_type)
+ cloned_types[original_type] = use_type
+ for f in original_type.__fields__.values():
+ use_type.__fields__[f.name] = create_cloned_field(
+ f, cloned_types=cloned_types
+ )
new_field = create_response_field(name=field.name, type_=use_type)
new_field.has_alias = field.has_alias
new_field.alias = field.alias
@@ -157,10 +143,13 @@ def create_cloned_field(field: ModelField) -> ModelField:
new_field.validate_always = field.validate_always
if field.sub_fields:
new_field.sub_fields = [
- create_cloned_field(sub_field) for sub_field in field.sub_fields
+ create_cloned_field(sub_field, cloned_types=cloned_types)
+ for sub_field in field.sub_fields
]
if field.key_field:
- new_field.key_field = create_cloned_field(field.key_field)
+ new_field.key_field = create_cloned_field(
+ field.key_field, cloned_types=cloned_types
+ )
new_field.validators = field.validators
if PYDANTIC_1:
new_field.pre_validators = field.pre_validators
diff --git a/mkdocs.yml b/mkdocs.yml
deleted file mode 100644
index b1f88184f10ee..0000000000000
--- a/mkdocs.yml
+++ /dev/null
@@ -1,148 +0,0 @@
-site_name: FastAPI
-site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
-site_url: https://fastapi.tiangolo.com/
-
-theme:
- name: 'material'
- palette:
- primary: 'teal'
- accent: 'amber'
- logo: 'img/icon-white.svg'
- favicon: 'img/favicon.png'
-
-repo_name: tiangolo/fastapi
-repo_url: https://github.com/tiangolo/fastapi
-edit_uri: ''
-google_analytics:
- - 'UA-133183413-1'
- - 'auto'
-
-nav:
- - FastAPI: 'index.md'
- - Features: 'features.md'
- - Python types intro: 'python-types.md'
- - Tutorial - User Guide:
- - Tutorial - User Guide - Intro: 'tutorial/index.md'
- - First Steps: 'tutorial/first-steps.md'
- - Path Parameters: 'tutorial/path-params.md'
- - Query Parameters: 'tutorial/query-params.md'
- - Request Body: 'tutorial/body.md'
- - Query Parameters and String Validations: 'tutorial/query-params-str-validations.md'
- - Path Parameters and Numeric Validations: 'tutorial/path-params-numeric-validations.md'
- - Body - Multiple Parameters: 'tutorial/body-multiple-params.md'
- - Body - Fields: 'tutorial/body-fields.md'
- - Body - Nested Models: 'tutorial/body-nested-models.md'
- - Extra data types: 'tutorial/extra-data-types.md'
- - Cookie Parameters: 'tutorial/cookie-params.md'
- - Header Parameters: 'tutorial/header-params.md'
- - Response Model: 'tutorial/response-model.md'
- - Extra Models: 'tutorial/extra-models.md'
- - Response Status Code: 'tutorial/response-status-code.md'
- - Form Data: 'tutorial/request-forms.md'
- - Request Files: 'tutorial/request-files.md'
- - Request Forms and Files: 'tutorial/request-forms-and-files.md'
- - Handling Errors: 'tutorial/handling-errors.md'
- - Path Operation Configuration: 'tutorial/path-operation-configuration.md'
- - JSON Compatible Encoder: 'tutorial/encoder.md'
- - Body - updates: 'tutorial/body-updates.md'
- - Dependencies:
- - First Steps: 'tutorial/dependencies/index.md'
- - Classes as Dependencies: 'tutorial/dependencies/classes-as-dependencies.md'
- - Sub-dependencies: 'tutorial/dependencies/sub-dependencies.md'
- - Dependencies in path operation decorators: 'tutorial/dependencies/dependencies-in-path-operation-decorators.md'
- - Dependencies with yield: 'tutorial/dependencies/dependencies-with-yield.md'
- - Security:
- - Security Intro: 'tutorial/security/index.md'
- - First Steps: 'tutorial/security/first-steps.md'
- - Get Current User: 'tutorial/security/get-current-user.md'
- - Simple OAuth2 with Password and Bearer: 'tutorial/security/simple-oauth2.md'
- - OAuth2 with Password (and hashing), Bearer with JWT tokens: 'tutorial/security/oauth2-jwt.md'
- - Middleware: 'tutorial/middleware.md'
- - CORS (Cross-Origin Resource Sharing): 'tutorial/cors.md'
- - SQL (Relational) Databases: 'tutorial/sql-databases.md'
- - Bigger Applications - Multiple Files: 'tutorial/bigger-applications.md'
- - Background Tasks: 'tutorial/background-tasks.md'
- - Application Configuration: 'tutorial/application-configuration.md'
- - Static Files: 'tutorial/static-files.md'
- - Testing: 'tutorial/testing.md'
- - Debugging: 'tutorial/debugging.md'
- - Advanced User Guide:
- - Advanced User Guide - Intro: 'advanced/index.md'
- - Path Operation Advanced Configuration: 'advanced/path-operation-advanced-configuration.md'
- - Additional Status Codes: 'advanced/additional-status-codes.md'
- - Return a Response Directly: 'advanced/response-directly.md'
- - Custom Response - HTML, Stream, File, others: 'advanced/custom-response.md'
- - Additional Responses in OpenAPI: 'advanced/additional-responses.md'
- - Response Cookies: 'advanced/response-cookies.md'
- - Response Headers: 'advanced/response-headers.md'
- - Response - Change Status Code: 'advanced/response-change-status-code.md'
- - Advanced Dependencies: 'advanced/advanced-dependencies.md'
- - Advanced Security:
- - Advanced Security - Intro: 'advanced/security/index.md'
- - OAuth2 scopes: 'advanced/security/oauth2-scopes.md'
- - HTTP Basic Auth: 'advanced/security/http-basic-auth.md'
- - Using the Request Directly: 'advanced/using-request-directly.md'
- - Advanced Middleware: 'advanced/middleware.md'
- - SQL (Relational) Databases with Peewee: 'advanced/sql-databases-peewee.md'
- - Async SQL (Relational) Databases: 'advanced/async-sql-databases.md'
- - NoSQL (Distributed / Big Data) Databases: 'advanced/nosql-databases.md'
- - Sub Applications - Behind a Proxy, Mounts: 'advanced/sub-applications-proxy.md'
- - Templates: 'advanced/templates.md'
- - GraphQL: 'advanced/graphql.md'
- - WebSockets: 'advanced/websockets.md'
- - 'Events: startup - shutdown': 'advanced/events.md'
- - Custom Request and APIRoute class: 'advanced/custom-request-and-route.md'
- - Testing WebSockets: 'advanced/testing-websockets.md'
- - 'Testing Events: startup - shutdown': 'advanced/testing-events.md'
- - Testing Dependencies with Overrides: 'advanced/testing-dependencies.md'
- - Extending OpenAPI: 'advanced/extending-openapi.md'
- - OpenAPI Callbacks: 'advanced/openapi-callbacks.md'
- - Including WSGI - Flask, Django, others: 'advanced/wsgi.md'
- - Concurrency and async / await: 'async.md'
- - Deployment: 'deployment.md'
- - Project Generation - Template: 'project-generation.md'
- - Alternatives, Inspiration and Comparisons: 'alternatives.md'
- - History, Design and Future: 'history-design-future.md'
- - External Links and Articles: 'external-links.md'
- - Benchmarks: 'benchmarks.md'
- - Help FastAPI - Get Help: 'help-fastapi.md'
- - Development - Contributing: 'contributing.md'
- - Release Notes: 'release-notes.md'
-
-markdown_extensions:
- - toc:
- permalink: true
- - markdown.extensions.codehilite:
- guess_lang: false
- - markdown_include.include:
- base_path: docs
- - admonition
- - codehilite
- - extra
- - pymdownx.superfences:
- custom_fences:
- - name: mermaid
- class: mermaid
- format: !!python/name:pymdownx.superfences.fence_div_format
-
-extra:
- social:
- - type: 'github'
- link: 'https://github.com/tiangolo/typer'
- - type: 'twitter'
- link: 'https://twitter.com/tiangolo'
- - type: 'linkedin'
- link: 'https://www.linkedin.com/in/tiangolo'
- - type: 'rss'
- link: 'https://dev.to/tiangolo'
- - type: 'medium'
- link: 'https://medium.com/@tiangolo'
- - type: 'globe'
- link: 'https://tiangolo.com'
-
-extra_css:
- - 'css/custom.css'
-
-extra_javascript:
- - 'https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js'
- - 'js/custom.js'
diff --git a/pyproject.toml b/pyproject.toml
index 58e53c3eec2f5..07610fca0872f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -58,13 +58,15 @@ test = [
"async_generator",
"python-multipart",
"aiofiles",
- "ujson",
"flask"
]
doc = [
"mkdocs",
"mkdocs-material",
- "markdown-include"
+ "markdown-include",
+ "typer",
+ "typer-cli",
+ "pyyaml"
]
dev = [
"pyjwt",
@@ -83,6 +85,7 @@ all = [
"pyyaml",
"graphene",
"ujson",
+ "orjson",
"email_validator",
"uvicorn",
"async_exit_stack",
diff --git a/scripts/build-docs.sh b/scripts/build-docs.sh
index 4f4ae2f74e403..383ad3f4465c7 100755
--- a/scripts/build-docs.sh
+++ b/scripts/build-docs.sh
@@ -1,5 +1,6 @@
#!/usr/bin/env bash
-python -m mkdocs build
+set -e
+set -x
-cp ./docs/index.md ./README.md
+python ./scripts/docs.py build-all
diff --git a/scripts/docs.py b/scripts/docs.py
new file mode 100644
index 0000000000000..33297dd8f7a81
--- /dev/null
+++ b/scripts/docs.py
@@ -0,0 +1,357 @@
+import os
+import shutil
+from http.server import HTTPServer, SimpleHTTPRequestHandler
+from pathlib import Path
+from typing import Dict, Optional, Tuple
+
+import mkdocs.commands.build
+import mkdocs.commands.serve
+import mkdocs.config
+import mkdocs.utils
+import typer
+import yaml
+
+app = typer.Typer()
+
+mkdocs_name = "mkdocs.yml"
+
+missing_translation_snippet = """
+{!../../../docs/missing-translation.md!}
+"""
+
+docs_path = Path("docs")
+en_docs_path = Path("docs/en")
+en_config_path: Path = en_docs_path / mkdocs_name
+
+
+def get_en_config() -> dict:
+ return mkdocs.utils.yaml_load(en_config_path.read_text(encoding="utf-8"))
+
+
+def get_lang_paths():
+ return sorted(docs_path.iterdir())
+
+
+def lang_callback(lang: Optional[str]):
+ if lang is None:
+ return
+ if not lang.isalpha() or len(lang) != 2:
+ typer.echo("Use a 2 letter language code, like: es")
+ raise typer.Abort()
+ lang = lang.lower()
+ return lang
+
+
+def complete_existing_lang(incomplete: str):
+ lang_path: Path
+ for lang_path in get_lang_paths():
+ if lang_path.is_dir() and lang_path.name.startswith(incomplete):
+ yield lang_path.name
+
+
+def get_base_lang_config(lang: str):
+ en_config = get_en_config()
+ fastapi_url_base = "https://fastapi.tiangolo.com/"
+ new_config = en_config.copy()
+ new_config["site_url"] = en_config["site_url"] + f"{lang}/"
+ new_config["theme"]["logo"] = fastapi_url_base + en_config["theme"]["logo"]
+ new_config["theme"]["favicon"] = fastapi_url_base + en_config["theme"]["favicon"]
+ new_config["theme"]["language"] = lang
+ new_config["nav"] = en_config["nav"][:2]
+ extra_css = []
+ css: str
+ for css in en_config["extra_css"]:
+ if css.startswith("http"):
+ extra_css.append(css)
+ else:
+ extra_css.append(fastapi_url_base + css)
+ new_config["extra_css"] = extra_css
+
+ extra_js = []
+ js: str
+ for js in en_config["extra_javascript"]:
+ if js.startswith("http"):
+ extra_js.append(js)
+ else:
+ extra_js.append(fastapi_url_base + js)
+ new_config["extra_javascript"] = extra_js
+ return new_config
+
+
+@app.command()
+def new_lang(lang: str = typer.Argument(..., callback=lang_callback)):
+ """
+ Generate a new docs translation directory for the language LANG.
+
+ LANG should be a 2-letter language code, like: en, es, de, pt, etc.
+ """
+ new_path: Path = Path("docs") / lang
+ if new_path.exists():
+ typer.echo(f"The language was already created: {lang}")
+ raise typer.Abort()
+ new_path.mkdir()
+ new_config = get_base_lang_config(lang)
+ new_config_path: Path = Path(new_path) / mkdocs_name
+ new_config_path.write_text(
+ yaml.dump(new_config, sort_keys=False, width=200, allow_unicode=True),
+ encoding="utf-8",
+ )
+ new_config_docs_path: Path = new_path / "docs"
+ new_config_docs_path.mkdir()
+ en_index_path: Path = en_docs_path / "docs" / "index.md"
+ new_index_path: Path = new_config_docs_path / "index.md"
+ en_index_content = en_index_path.read_text(encoding="utf-8")
+ new_index_content = f"{missing_translation_snippet}\n\n{en_index_content}"
+ new_index_path.write_text(new_index_content, encoding="utf-8")
+ typer.secho(f"Successfully initialized: {new_path}", color=typer.colors.GREEN)
+ update_languages(lang=None)
+
+
+@app.command()
+def build_lang(
+ lang: str = typer.Argument(
+ ..., callback=lang_callback, autocompletion=complete_existing_lang
+ )
+):
+ """
+ Build the docs for a language, filling missing pages with translation notifications.
+ """
+ lang_path: Path = Path("docs") / lang
+ if not lang_path.is_dir():
+ typer.echo(f"The language translation doesn't seem to exist yet: {lang}")
+ raise typer.Abort()
+ typer.echo(f"Building docs for: {lang}")
+ build_dir_path = Path("docs_build")
+ build_dir_path.mkdir(exist_ok=True)
+ build_lang_path = build_dir_path / lang
+ en_lang_path = Path("docs/en")
+ site_path = Path("site").absolute()
+ if lang == "en":
+ dist_path = site_path
+ else:
+ dist_path: Path = site_path / lang
+ shutil.rmtree(build_lang_path, ignore_errors=True)
+ shutil.copytree(lang_path, build_lang_path)
+ en_config_path: Path = en_lang_path / mkdocs_name
+ en_config: dict = mkdocs.utils.yaml_load(en_config_path.read_text(encoding="utf-8"))
+ nav = en_config["nav"]
+ lang_config_path: Path = lang_path / mkdocs_name
+ lang_config: dict = mkdocs.utils.yaml_load(
+ lang_config_path.read_text(encoding="utf-8")
+ )
+ lang_nav = lang_config["nav"]
+ # Exclude first 2 entries FastAPI and Languages, for custom handling
+ use_nav = nav[2:]
+ lang_use_nav = lang_nav[2:]
+ file_to_nav = get_file_to_nav_map(use_nav)
+ sections = get_sections(use_nav)
+ lang_file_to_nav = get_file_to_nav_map(lang_use_nav)
+ use_lang_file_to_nav = get_file_to_nav_map(lang_use_nav)
+ for file in file_to_nav:
+ file_path = Path(file)
+ lang_file_path: Path = build_lang_path / "docs" / file_path
+ en_file_path: Path = en_lang_path / "docs" / file_path
+ lang_file_path.parent.mkdir(parents=True, exist_ok=True)
+ if not lang_file_path.is_file():
+ en_text = en_file_path.read_text(encoding="utf-8")
+ lang_text = get_text_with_translate_missing(en_text)
+ lang_file_path.write_text(lang_text, encoding="utf-8")
+ file_key = file_to_nav[file]
+ use_lang_file_to_nav[file] = file_key
+ if file_key:
+ composite_key = ()
+ new_key = ()
+ for key_part in file_key:
+ composite_key += (key_part,)
+ key_first_file = sections[composite_key]
+ if key_first_file in lang_file_to_nav:
+ new_key = lang_file_to_nav[key_first_file]
+ else:
+ new_key += (key_part,)
+ use_lang_file_to_nav[file] = new_key
+ key_to_section = {(): []}
+ for file, file_key in use_lang_file_to_nav.items():
+ section = get_key_section(key_to_section=key_to_section, key=file_key)
+ section.append(file)
+ new_nav = key_to_section[()]
+ export_lang_nav = [lang_nav[0], nav[1]] + new_nav
+ lang_config["nav"] = export_lang_nav
+ build_lang_config_path: Path = build_lang_path / mkdocs_name
+ build_lang_config_path.write_text(
+ yaml.dump(lang_config, sort_keys=False, width=200, allow_unicode=True),
+ encoding="utf-8",
+ )
+ current_dir = os.getcwd()
+ os.chdir(build_lang_path)
+ mkdocs.commands.build.build(mkdocs.config.load_config(site_dir=str(dist_path)))
+ os.chdir(current_dir)
+ typer.secho(f"Successfully built docs for: {lang}", color=typer.colors.GREEN)
+
+
+@app.command()
+def build_all():
+ """
+ Build mkdocs site for en, and then build each language inside, end result is located
+ at directory ./site/ with each language inside.
+ """
+ site_path = Path("site").absolute()
+ update_languages(lang=None)
+ en_build_path: Path = docs_path / "en"
+ current_dir = os.getcwd()
+ os.chdir(en_build_path)
+ typer.echo(f"Building docs for: en")
+ mkdocs.commands.build.build(mkdocs.config.load_config(site_dir=str(site_path)))
+ os.chdir(current_dir)
+ for lang in get_lang_paths():
+ if lang == en_build_path or not lang.is_dir():
+ continue
+ build_lang(lang.name)
+ typer.echo("Copying en index.md to README.md")
+ en_index = en_build_path / "docs" / "index.md"
+ shutil.copyfile(en_index, "README.md")
+
+
+@app.command()
+def update_languages(
+ lang: str = typer.Argument(
+ None, callback=lang_callback, autocompletion=complete_existing_lang
+ )
+):
+ """
+ Update the mkdocs.yml file Languages section including all the available languages.
+
+ The LANG argument is a 2-letter language code. If it's not provided, update all the
+ mkdocs.yml files (for all the languages).
+ """
+ if lang is None:
+ for lang_path in get_lang_paths():
+ if lang_path.is_dir():
+ typer.echo(f"Updating {lang_path.name}")
+ update_config(lang_path.name)
+ else:
+ typer.echo(f"Updating {lang}")
+ update_config(lang)
+
+
+@app.command()
+def serve():
+ """
+ A quick server to preview a built site with translations.
+
+ For development, prefer the command live (or just mkdocs serve).
+
+ This is here only to preview a site with translations already built.
+
+ Make sure you run the build-all command first.
+ """
+ typer.echo("Warning: this is a very simple server.")
+ typer.echo("For development, use the command live instead.")
+ typer.echo("This is here only to preview a site with translations already built.")
+ typer.echo("Make sure you run the build-all command first.")
+ os.chdir("site")
+ server_address = ("", 8008)
+ server = HTTPServer(server_address, SimpleHTTPRequestHandler)
+ typer.echo(f"Serving at: http://127.0.0.1:8008")
+ server.serve_forever()
+
+
+@app.command()
+def live(
+ lang: str = typer.Argument(
+ None, callback=lang_callback, autocompletion=complete_existing_lang
+ )
+):
+ """
+ Serve with livereload a docs site for a specific language.
+
+ This only shows the actual translated files, not the placeholders created with
+ build-all.
+
+ Takes an optional LANG argument with the name of the language to serve, by default
+ en.
+ """
+ if lang is None:
+ lang = "en"
+ lang_path: Path = docs_path / lang
+ os.chdir(lang_path)
+ mkdocs.commands.serve.serve(dev_addr="127.0.0.1:8008")
+
+
+def update_config(lang: str):
+ lang_path: Path = docs_path / lang
+ config_path = lang_path / mkdocs_name
+ current_config: dict = mkdocs.utils.yaml_load(
+ config_path.read_text(encoding="utf-8")
+ )
+ if lang == "en":
+ config = get_en_config()
+ else:
+ config = get_base_lang_config(lang)
+ config["nav"] = current_config["nav"]
+ config["theme"]["language"] = current_config["theme"]["language"]
+ languages = [{"en": "/"}]
+ for lang in get_lang_paths():
+ if lang.name == "en" or not lang.is_dir():
+ continue
+ name = lang.name
+ languages.append({name: f"/{name}/"})
+ config["nav"][1] = {"Languages": languages}
+ config_path.write_text(
+ yaml.dump(config, sort_keys=False, width=200, allow_unicode=True),
+ encoding="utf-8",
+ )
+
+
+def get_key_section(
+ *, key_to_section: Dict[Tuple[str, ...], list], key: Tuple[str, ...]
+) -> list:
+ if key in key_to_section:
+ return key_to_section[key]
+ super_key = key[:-1]
+ title = key[-1]
+ super_section = get_key_section(key_to_section=key_to_section, key=super_key)
+ new_section = []
+ super_section.append({title: new_section})
+ key_to_section[key] = new_section
+ return new_section
+
+
+def get_text_with_translate_missing(text: str) -> str:
+ lines = text.splitlines()
+ lines.insert(1, missing_translation_snippet)
+ new_text = "\n".join(lines)
+ return new_text
+
+
+def get_file_to_nav_map(nav: list) -> Dict[str, Tuple[str, ...]]:
+ file_to_nav = {}
+ for item in nav:
+ if type(item) is str:
+ file_to_nav[item] = tuple()
+ elif type(item) is dict:
+ item_key = list(item.keys())[0]
+ sub_nav = item[item_key]
+ sub_file_to_nav = get_file_to_nav_map(sub_nav)
+ for k, v in sub_file_to_nav.items():
+ file_to_nav[k] = (item_key,) + v
+ return file_to_nav
+
+
+def get_sections(nav: list) -> Dict[Tuple[str, ...], str]:
+ sections = {}
+ for item in nav:
+ if type(item) is str:
+ continue
+ elif type(item) is dict:
+ item_key = list(item.keys())[0]
+ sub_nav = item[item_key]
+ sections[(item_key,)] = sub_nav[0]
+ sub_sections = get_sections(sub_nav)
+ for k, v in sub_sections.items():
+ new_key = (item_key,) + k
+ sections[new_key] = v
+ return sections
+
+
+if __name__ == "__main__":
+ app()
diff --git a/scripts/format-imports.sh b/scripts/format-imports.sh
index cfa66bbd46069..d2c0b7a5874a1 100755
--- a/scripts/format-imports.sh
+++ b/scripts/format-imports.sh
@@ -2,5 +2,5 @@
set -x
# Sort imports one per line, so autoflake can remove unused imports
-isort --recursive --force-single-line-imports --thirdparty fastapi --apply fastapi tests docs/src
+isort --recursive --force-single-line-imports --thirdparty fastapi --apply fastapi tests docs_src scripts
sh ./scripts/format.sh
diff --git a/scripts/format.sh b/scripts/format.sh
index c11eaf749483b..07ce78f699c0a 100755
--- a/scripts/format.sh
+++ b/scripts/format.sh
@@ -1,6 +1,6 @@
#!/bin/sh -e
set -x
-autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place docs/src/ fastapi tests --exclude=__init__.py
-black fastapi tests docs/src
-isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --thirdparty fastapi --apply fastapi tests docs/src
+autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place docs_src fastapi tests scripts --exclude=__init__.py
+black fastapi tests docs_src scripts
+isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --thirdparty fastapi --thirdparty pydantic --thirdparty starlette --apply fastapi tests docs_src scripts
diff --git a/scripts/lint.sh b/scripts/lint.sh
index 6472f18454adc..ec0f7f41bfcf5 100755
--- a/scripts/lint.sh
+++ b/scripts/lint.sh
@@ -5,4 +5,4 @@ set -x
mypy fastapi
black fastapi tests --check
-isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --check-only --thirdparty fastapi fastapi tests
+isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --check-only --thirdparty fastapi --thirdparty fastapi --thirdparty pydantic --thirdparty starlette fastapi tests
diff --git a/scripts/test.sh b/scripts/test.sh
index d1a4cf630ee39..54fd7410bc309 100755
--- a/scripts/test.sh
+++ b/scripts/test.sh
@@ -3,12 +3,8 @@
set -e
set -x
-# Remove temporary DB
-if [ -f ./test.db ]; then
- rm ./test.db
-fi
bash ./scripts/lint.sh
# Check README.md is up to date
-diff --brief docs/index.md README.md
-export PYTHONPATH=./docs/src
-pytest --cov=fastapi --cov=tests --cov=docs/src --cov-report=term-missing ${@}
+diff --brief docs/en/docs/index.md README.md
+export PYTHONPATH=./docs_src
+pytest --cov=fastapi --cov=tests --cov=docs/src --cov-report=term-missing tests ${@}
diff --git a/tests/test_additional_properties.py b/tests/test_additional_properties.py
index de38ce050538f..9e15e6ed06042 100644
--- a/tests/test_additional_properties.py
+++ b/tests/test_additional_properties.py
@@ -100,11 +100,11 @@ def foo(items: Items):
def test_additional_properties_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_additional_properties_post():
response = client.post("/foo", json={"items": {"foo": 1, "bar": 2}})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"foo": 1, "bar": 2}
diff --git a/tests/test_additional_response_extra.py b/tests/test_additional_response_extra.py
index a20036cc7fd17..1df1891e059c2 100644
--- a/tests/test_additional_response_extra.py
+++ b/tests/test_additional_response_extra.py
@@ -42,11 +42,11 @@ def read_item():
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_path_operation():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"id": "foo"}
diff --git a/tests/test_additional_responses_custom_validationerror.py b/tests/test_additional_responses_custom_validationerror.py
index ce21bca24e597..811fe69221272 100644
--- a/tests/test_additional_responses_custom_validationerror.py
+++ b/tests/test_additional_responses_custom_validationerror.py
@@ -96,5 +96,5 @@ async def a(id):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_additional_responses_default_validationerror.py b/tests/test_additional_responses_default_validationerror.py
index c7f56367b588e..6ea372ce8d696 100644
--- a/tests/test_additional_responses_default_validationerror.py
+++ b/tests/test_additional_responses_default_validationerror.py
@@ -81,5 +81,5 @@ async def a(id):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_additional_responses_response_class.py b/tests/test_additional_responses_response_class.py
index 4d4e1db891197..aa549b1636ead 100644
--- a/tests/test_additional_responses_response_class.py
+++ b/tests/test_additional_responses_response_class.py
@@ -113,5 +113,5 @@ async def b():
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_additional_responses_router.py b/tests/test_additional_responses_router.py
index bc5efeb035a36..d2b73058f7e92 100644
--- a/tests/test_additional_responses_router.py
+++ b/tests/test_additional_responses_router.py
@@ -89,23 +89,23 @@ async def c():
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_a():
response = client.get("/a")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == "a"
def test_b():
response = client.get("/b")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == "b"
def test_c():
response = client.get("/c")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == "c"
diff --git a/tests/test_application.py b/tests/test_application.py
index f4d294e1b7fb2..f6d77460a4032 100644
--- a/tests/test_application.py
+++ b/tests/test_application.py
@@ -1128,7 +1128,7 @@ def test_get_path(path, expected_status, expected_response):
def test_swagger_ui():
response = client.get("/docs")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "swagger-ui-dist" in response.text
assert (
@@ -1139,13 +1139,13 @@ def test_swagger_ui():
def test_swagger_ui_oauth2_redirect():
response = client.get("/docs/oauth2-redirect")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "window.opener.swaggerUIRedirectOauth2" in response.text
def test_redoc():
response = client.get("/redoc")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "redoc@next" in response.text
diff --git a/tests/test_custom_swagger_ui_redirect.py b/tests/test_custom_swagger_ui_redirect.py
index ac724f8fb46ec..996734be219fe 100644
--- a/tests/test_custom_swagger_ui_redirect.py
+++ b/tests/test_custom_swagger_ui_redirect.py
@@ -16,7 +16,7 @@ async def read_items():
def test_swagger_ui():
response = client.get("/docs")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "swagger-ui-dist" in response.text
print(client.base_url)
@@ -28,7 +28,7 @@ def test_swagger_ui():
def test_swagger_ui_oauth2_redirect():
response = client.get(swagger_ui_oauth2_redirect_url)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "window.opener.swaggerUIRedirectOauth2" in response.text
diff --git a/tests/test_dependency_cache.py b/tests/test_dependency_cache.py
index dc7a14cd4b56c..65ed7f946459e 100644
--- a/tests/test_dependency_cache.py
+++ b/tests/test_dependency_cache.py
@@ -41,28 +41,28 @@ async def get_sub_counter_no_cache(
def test_normal_counter():
counter_holder["counter"] = 0
response = client.get("/counter/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"counter": 1}
response = client.get("/counter/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"counter": 2}
def test_sub_counter():
counter_holder["counter"] = 0
response = client.get("/sub-counter/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"counter": 1, "subcounter": 1}
response = client.get("/sub-counter/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"counter": 2, "subcounter": 2}
def test_sub_counter_no_cache():
counter_holder["counter"] = 0
response = client.get("/sub-counter-no-cache/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"counter": 2, "subcounter": 1}
response = client.get("/sub-counter-no-cache/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"counter": 4, "subcounter": 3}
diff --git a/tests/test_dependency_class.py b/tests/test_dependency_class.py
index 4b3bd724322b1..ba2e3cfcfe381 100644
--- a/tests/test_dependency_class.py
+++ b/tests/test_dependency_class.py
@@ -66,5 +66,5 @@ async def get_asynchronous_method_dependency(
)
def test_class_dependency(route, value):
response = client.get(route, params={"value": value})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == value
diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py
index 5090e5459d117..847a41dce03ea 100644
--- a/tests/test_dependency_contextmanager.py
+++ b/tests/test_dependency_contextmanager.py
@@ -206,7 +206,7 @@ async def bg(state: dict):
def test_async_state():
assert state["/async"] == f"asyncgen not started"
response = client.get("/async")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == f"asyncgen started"
assert state["/async"] == f"asyncgen completed"
@@ -214,7 +214,7 @@ def test_async_state():
def test_sync_state():
assert state["/sync"] == f"generator not started"
response = client.get("/sync")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == f"generator started"
assert state["/sync"] == f"generator completed"
@@ -237,7 +237,7 @@ def test_sync_raise_other():
def test_async_raise():
response = client.get("/async_raise")
- assert response.status_code == 500
+ assert response.status_code == 500, response.text
assert state["/async_raise"] == "asyncgen raise finalized"
assert "/async_raise" in errors
errors.clear()
@@ -272,7 +272,7 @@ def test_background_tasks():
def test_sync_raise():
response = client.get("/sync_raise")
- assert response.status_code == 500
+ assert response.status_code == 500, response.text
assert state["/sync_raise"] == "generator raise finalized"
assert "/sync_raise" in errors
errors.clear()
@@ -280,14 +280,14 @@ def test_sync_raise():
def test_sync_async_state():
response = client.get("/sync_async")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == f"asyncgen started"
assert state["/async"] == f"asyncgen completed"
def test_sync_sync_state():
response = client.get("/sync_sync")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == f"generator started"
assert state["/sync"] == f"generator completed"
@@ -308,7 +308,7 @@ def test_sync_sync_raise_other():
def test_sync_async_raise():
response = client.get("/sync_async_raise")
- assert response.status_code == 500
+ assert response.status_code == 500, response.text
assert state["/async_raise"] == "asyncgen raise finalized"
assert "/async_raise" in errors
errors.clear()
@@ -316,7 +316,7 @@ def test_sync_async_raise():
def test_sync_sync_raise():
response = client.get("/sync_sync_raise")
- assert response.status_code == 500
+ assert response.status_code == 500, response.text
assert state["/sync_raise"] == "generator raise finalized"
assert "/sync_raise" in errors
errors.clear()
diff --git a/tests/test_dependency_duplicates.py b/tests/test_dependency_duplicates.py
new file mode 100644
index 0000000000000..5e15812b67042
--- /dev/null
+++ b/tests/test_dependency_duplicates.py
@@ -0,0 +1,232 @@
+from typing import List
+
+from fastapi import Depends, FastAPI
+from fastapi.testclient import TestClient
+from pydantic import BaseModel
+
+app = FastAPI()
+
+client = TestClient(app)
+
+
+class Item(BaseModel):
+ data: str
+
+
+def duplicate_dependency(item: Item):
+ return item
+
+
+def dependency(item2: Item):
+ return item2
+
+
+def sub_duplicate_dependency(
+ item: Item, sub_item: Item = Depends(duplicate_dependency)
+):
+ return [item, sub_item]
+
+
+@app.post("/with-duplicates")
+async def with_duplicates(item: Item, item2: Item = Depends(duplicate_dependency)):
+ return [item, item2]
+
+
+@app.post("/no-duplicates")
+async def no_duplicates(item: Item, item2: Item = Depends(dependency)):
+ return [item, item2]
+
+
+@app.post("/with-duplicates-sub")
+async def no_duplicates_sub(
+ item: Item, sub_items: List[Item] = Depends(sub_duplicate_dependency)
+):
+ return [item, sub_items]
+
+
+openapi_schema = {
+ "openapi": "3.0.2",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/with-duplicates": {
+ "post": {
+ "summary": "With Duplicates",
+ "operationId": "with_duplicates_with_duplicates_post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ },
+ "/no-duplicates": {
+ "post": {
+ "summary": "No Duplicates",
+ "operationId": "no_duplicates_no_duplicates_post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Body_no_duplicates_no_duplicates_post"
+ }
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ },
+ "/with-duplicates-sub": {
+ "post": {
+ "summary": "No Duplicates Sub",
+ "operationId": "no_duplicates_sub_with_duplicates_sub_post",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {"$ref": "#/components/schemas/Item"}
+ }
+ },
+ "required": True,
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ },
+ },
+ "components": {
+ "schemas": {
+ "Body_no_duplicates_no_duplicates_post": {
+ "title": "Body_no_duplicates_no_duplicates_post",
+ "required": ["item", "item2"],
+ "type": "object",
+ "properties": {
+ "item": {"$ref": "#/components/schemas/Item"},
+ "item2": {"$ref": "#/components/schemas/Item"},
+ },
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ "Item": {
+ "title": "Item",
+ "required": ["data"],
+ "type": "object",
+ "properties": {"data": {"title": "Data", "type": "string"}},
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {"type": "string"},
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ }
+ },
+}
+
+
+def test_openapi_schema():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200, response.text
+ assert response.json() == openapi_schema
+
+
+def test_no_duplicates_invalid():
+ response = client.post("/no-duplicates", json={"item": {"data": "myitem"}})
+ assert response.status_code == 422, response.text
+ assert response.json() == {
+ "detail": [
+ {
+ "loc": ["body", "item2"],
+ "msg": "field required",
+ "type": "value_error.missing",
+ }
+ ]
+ }
+
+
+def test_no_duplicates():
+ response = client.post(
+ "/no-duplicates",
+ json={"item": {"data": "myitem"}, "item2": {"data": "myitem2"}},
+ )
+ assert response.status_code == 200, response.text
+ assert response.json() == [{"data": "myitem"}, {"data": "myitem2"}]
+
+
+def test_duplicates():
+ response = client.post("/with-duplicates", json={"data": "myitem"})
+ assert response.status_code == 200, response.text
+ assert response.json() == [{"data": "myitem"}, {"data": "myitem"}]
+
+
+def test_sub_duplicates():
+ response = client.post("/with-duplicates-sub", json={"data": "myitem"})
+ assert response.status_code == 200, response.text
+ assert response.json() == [
+ {"data": "myitem"},
+ [{"data": "myitem"}, {"data": "myitem"}],
+ ]
diff --git a/tests/test_deprecated_openapi_prefix.py b/tests/test_deprecated_openapi_prefix.py
new file mode 100644
index 0000000000000..df7e69bd56237
--- /dev/null
+++ b/tests/test_deprecated_openapi_prefix.py
@@ -0,0 +1,43 @@
+from fastapi import FastAPI, Request
+from fastapi.testclient import TestClient
+
+app = FastAPI(openapi_prefix="/api/v1")
+
+
+@app.get("/app")
+def read_main(request: Request):
+ return {"message": "Hello World", "root_path": request.scope.get("root_path")}
+
+
+client = TestClient(app)
+
+openapi_schema = {
+ "openapi": "3.0.2",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/api/v1/app": {
+ "get": {
+ "summary": "Read Main",
+ "operationId": "read_main_app_get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ }
+ }
+ },
+}
+
+
+def test_openapi():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200
+ assert response.json() == openapi_schema
+
+
+def test_main():
+ response = client.get("/app")
+ assert response.status_code == 200
+ assert response.json() == {"message": "Hello World", "root_path": "/api/v1"}
diff --git a/tests/test_empty_router.py b/tests/test_empty_router.py
index ccca5dbd34fce..186ceb347e048 100644
--- a/tests/test_empty_router.py
+++ b/tests/test_empty_router.py
@@ -21,11 +21,11 @@ def get_empty():
def test_use_empty():
with client:
response = client.get("/prefix")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == ["OK"]
response = client.get("/prefix/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == ["OK"]
diff --git a/tests/test_extra_routes.py b/tests/test_extra_routes.py
index 150ae1e078735..a2459b3588d27 100644
--- a/tests/test_extra_routes.py
+++ b/tests/test_extra_routes.py
@@ -314,47 +314,47 @@ def trace_item(item_id: str):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_api_route():
response = client.get("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo"}
def test_get_api_route_not_decorated():
response = client.get("/items-not-decorated/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo"}
def test_delete():
response = client.delete("/items/foo", json={"name": "Foo"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo", "item": {"name": "Foo", "price": None}}
def test_head():
response = client.head("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["x-fastapi-item-id"] == "foo"
def test_options():
response = client.options("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["x-fastapi-item-id"] == "foo"
def test_patch():
response = client.patch("/items/foo", json={"name": "Foo"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo", "item": {"name": "Foo", "price": None}}
def test_trace():
response = client.request("trace", "/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["content-type"] == "message/http"
diff --git a/tests/test_filter_pydantic_sub_model.py b/tests/test_filter_pydantic_sub_model.py
index 9d631cc0215f7..9ce753d1e2179 100644
--- a/tests/test_filter_pydantic_sub_model.py
+++ b/tests/test_filter_pydantic_sub_model.py
@@ -127,13 +127,13 @@ async def get_model_a(name: str, model_c=Depends(get_model_c)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_filter_sub_model():
response = client.get("/model/modelA")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {
"name": "modelA",
"description": "model-a-desc",
diff --git a/tests/test_forms_from_non_typing_sequences.py b/tests/test_forms_from_non_typing_sequences.py
index a34ec44c29612..be917eab7e2e0 100644
--- a/tests/test_forms_from_non_typing_sequences.py
+++ b/tests/test_forms_from_non_typing_sequences.py
@@ -26,7 +26,7 @@ def test_python_list_param_as_form():
response = client.post(
"/form/python-list", data={"items": ["first", "second", "third"]}
)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == ["first", "second", "third"]
@@ -34,7 +34,7 @@ def test_python_set_param_as_form():
response = client.post(
"/form/python-set", data={"items": ["first", "second", "third"]}
)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert set(response.json()) == {"first", "second", "third"}
@@ -42,5 +42,5 @@ def test_python_tuple_param_as_form():
response = client.post(
"/form/python-tuple", data={"items": ["first", "second", "third"]}
)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == ["first", "second", "third"]
diff --git a/tests/test_include_route.py b/tests/test_include_route.py
index 61bf34f40400f..88696e2ba9800 100644
--- a/tests/test_include_route.py
+++ b/tests/test_include_route.py
@@ -18,5 +18,5 @@ def read_items(request: Request):
def test_sub_router():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"hello": "world"}
diff --git a/tests/test_infer_param_optionality.py b/tests/test_infer_param_optionality.py
index 6d189989777f7..166c3fcc780b7 100644
--- a/tests/test_infer_param_optionality.py
+++ b/tests/test_infer_param_optionality.py
@@ -46,21 +46,21 @@ def get_item(item_id: str, user_id: str = None):
def test_get_users():
"""Check that /users returns expected data"""
response = client.get("/users")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"user_id": "u1"}, {"user_id": "u2"}]
def test_get_user():
"""Check that /users/{user_id} returns expected data"""
response = client.get("/users/abc123")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"user_id": "abc123"}
def test_get_items_1():
"""Check that /items returns expected data"""
response = client.get("/items")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [
{"item_id": "i1", "user_id": "u1"},
{"item_id": "i2", "user_id": "u2"},
@@ -70,42 +70,42 @@ def test_get_items_1():
def test_get_items_2():
"""Check that /items returns expected data with user_id specified"""
response = client.get("/items?user_id=abc123")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "i2", "user_id": "abc123"}]
def test_get_item_1():
"""Check that /items/{item_id} returns expected data"""
response = client.get("/items/item01")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "item01"}
def test_get_item_2():
"""Check that /items/{item_id} returns expected data with user_id specified"""
response = client.get("/items/item01?user_id=abc123")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "item01", "user_id": "abc123"}
def test_get_users_items():
"""Check that /users/{user_id}/items returns expected data"""
response = client.get("/users/abc123/items")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "i2", "user_id": "abc123"}]
def test_get_users_item():
"""Check that /users/{user_id}/items returns expected data"""
response = client.get("/users/abc123/items/item01")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "item01", "user_id": "abc123"}
def test_schema_1():
"""Check that the user_id is a required path parameter under /users"""
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
r = response.json()
d = {
@@ -122,7 +122,7 @@ def test_schema_1():
def test_schema_2():
"""Check that the user_id is an optional query parameter under /items"""
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
r = response.json()
d = {
diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py
index f94771aaeed94..adee443a8943c 100644
--- a/tests/test_jsonable_encoder.py
+++ b/tests/test_jsonable_encoder.py
@@ -70,6 +70,12 @@ class ModelWithAlias(BaseModel):
foo: str = Field(..., alias="Foo")
+class ModelWithDefault(BaseModel):
+ foo: str = ...
+ bar: str = "bar"
+ bla: str = "bla"
+
+
@pytest.fixture(
name="model_with_path", params=[PurePath, PurePosixPath, PureWindowsPath]
)
@@ -121,6 +127,16 @@ def test_encode_model_with_alias():
assert jsonable_encoder(model) == {"Foo": "Bar"}
+def test_encode_model_with_default():
+ model = ModelWithDefault(foo="foo", bar="bar")
+ assert jsonable_encoder(model) == {"foo": "foo", "bar": "bar", "bla": "bla"}
+ assert jsonable_encoder(model, exclude_unset=True) == {"foo": "foo", "bar": "bar"}
+ assert jsonable_encoder(model, exclude_defaults=True) == {"foo": "foo"}
+ assert jsonable_encoder(model, exclude_unset=True, exclude_defaults=True) == {
+ "foo": "foo"
+ }
+
+
def test_custom_encoders():
class safe_datetime(datetime):
pass
diff --git a/tests/test_modules_same_name_body/test_main.py b/tests/test_modules_same_name_body/test_main.py
index e73b5c408b5ea..b0d3330c72b2c 100644
--- a/tests/test_modules_same_name_body/test_main.py
+++ b/tests/test_modules_same_name_body/test_main.py
@@ -125,31 +125,31 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_post_a():
data = {"a": 2, "b": "foo"}
response = client.post("/a/compute", json=data)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
data = response.json()
def test_post_a_invalid():
data = {"a": "bar", "b": "foo"}
response = client.post("/a/compute", json=data)
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
def test_post_b():
data = {"a": 2, "b": "foo"}
response = client.post("/b/compute/", json=data)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
data = response.json()
def test_post_b_invalid():
data = {"a": "bar", "b": "foo"}
response = client.post("/b/compute/", json=data)
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
diff --git a/tests/test_multi_body_errors.py b/tests/test_multi_body_errors.py
index 23e6b64d556ec..f198042619537 100644
--- a/tests/test_multi_body_errors.py
+++ b/tests/test_multi_body_errors.py
@@ -139,23 +139,23 @@ def save_item_no_body(item: List[Item]):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_put_correct_body():
response = client.post("/items/", json=[{"name": "Foo", "age": 5}])
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item": [{"name": "Foo", "age": 5}]}
def test_jsonable_encoder_requiring_error():
response = client.post("/items/", json=[{"name": "Foo", "age": -1.0}])
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == single_error
def test_put_incorrect_body_multiple():
response = client.post("/items/", json=[{"age": "five"}, {"age": "six"}])
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == multiple_errors
diff --git a/tests/test_multi_query_errors.py b/tests/test_multi_query_errors.py
index 467ed9f4fb6c1..69ea87a9b65cc 100644
--- a/tests/test_multi_query_errors.py
+++ b/tests/test_multi_query_errors.py
@@ -102,17 +102,17 @@ def read_items(q: List[int] = Query(None)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_multi_query():
response = client.get("/items/?q=5&q=6")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"q": [5, 6]}
def test_multi_query_incorrect():
response = client.get("/items/?q=five&q=six")
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == multiple_errors
diff --git a/tests/test_no_swagger_ui_redirect.py b/tests/test_no_swagger_ui_redirect.py
index b403fa64c9400..0df9a46e57891 100644
--- a/tests/test_no_swagger_ui_redirect.py
+++ b/tests/test_no_swagger_ui_redirect.py
@@ -14,7 +14,7 @@ async def read_items():
def test_swagger_ui():
response = client.get("/docs")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert "swagger-ui-dist" in response.text
print(client.base_url)
@@ -23,7 +23,7 @@ def test_swagger_ui():
def test_swagger_ui_no_oauth2_redirect():
response = client.get("/docs/oauth2-redirect")
- assert response.status_code == 404
+ assert response.status_code == 404, response.text
def test_response():
diff --git a/tests/test_param_class.py b/tests/test_param_class.py
index 3066f22bfabba..bbb9eefcc3d7d 100644
--- a/tests/test_param_class.py
+++ b/tests/test_param_class.py
@@ -15,11 +15,11 @@ def read_items(q: str = Param(None)):
def test_default_param_query_none():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"q": None}
def test_default_param_query():
response = client.get("/items/?q=foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"q": "foo"}
diff --git a/tests/test_param_in_path_and_dependency.py b/tests/test_param_in_path_and_dependency.py
index 214d90174096f..0a94c2151316d 100644
--- a/tests/test_param_in_path_and_dependency.py
+++ b/tests/test_param_in_path_and_dependency.py
@@ -90,4 +90,4 @@ def test_reused_param():
def test_read_users():
response = client.get("/users/42")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
diff --git a/tests/test_path.py b/tests/test_path.py
index 26b65e695d220..d1a58bc66174d 100644
--- a/tests/test_path.py
+++ b/tests/test_path.py
@@ -8,13 +8,13 @@
def test_text_get():
response = client.get("/text")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == "Hello World"
def test_nonexistent():
response = client.get("/nonexistent")
- assert response.status_code == 404
+ assert response.status_code == 404, response.text
assert response.json() == {"detail": "Not Found"}
diff --git a/tests/test_put_no_body.py b/tests/test_put_no_body.py
index 95dbf03d2c8ec..1c2cfac891f52 100644
--- a/tests/test_put_no_body.py
+++ b/tests/test_put_no_body.py
@@ -81,17 +81,17 @@ def save_item_no_body(item_id: str):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_put_no_body():
response = client.put("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo"}
def test_put_no_body_with_body():
response = client.put("/items/foo", json={"name": "Foo"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo"}
diff --git a/tests/test_request_body_parameters_media_type.py b/tests/test_request_body_parameters_media_type.py
index 2eecd45eaa105..e3bd916729545 100644
--- a/tests/test_request_body_parameters_media_type.py
+++ b/tests/test_request_body_parameters_media_type.py
@@ -55,7 +55,7 @@ async def create_shop(
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
openapi_schema = response.json()
assert (
openapi_schema["paths"]["/products"]["post"]["requestBody"]
diff --git a/tests/test_response_change_status_code.py b/tests/test_response_change_status_code.py
index d401b81b05cf7..377ce7897a630 100644
--- a/tests/test_response_change_status_code.py
+++ b/tests/test_response_change_status_code.py
@@ -22,5 +22,5 @@ async def get_main():
def test_dependency_set_status_code():
response = client.get("/")
- assert response.status_code == 201
+ assert response.status_code == 201, response.text
assert response.json() == {"msg": "Hello World"}
diff --git a/tests/test_response_class_no_mediatype.py b/tests/test_response_class_no_mediatype.py
index ab869c3c5dbce..eb8500f3a872d 100644
--- a/tests/test_response_class_no_mediatype.py
+++ b/tests/test_response_class_no_mediatype.py
@@ -110,5 +110,5 @@ async def b():
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_response_code_no_body.py b/tests/test_response_code_no_body.py
index 7d658d0cf7c47..45e2fabc7ef79 100644
--- a/tests/test_response_code_no_body.py
+++ b/tests/test_response_code_no_body.py
@@ -104,5 +104,5 @@ async def b():
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_response_model_sub_types.py b/tests/test_response_model_sub_types.py
index 3f146481280bf..fd972e6a3d472 100644
--- a/tests/test_response_model_sub_types.py
+++ b/tests/test_response_model_sub_types.py
@@ -145,16 +145,16 @@ def valid4():
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_path_operations():
response = client.get("/valid1")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
response = client.get("/valid2")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
response = client.get("/valid3")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
response = client.get("/valid4")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
diff --git a/tests/test_router_events.py b/tests/test_router_events.py
index 5aeb966f30478..5ff1fdf9f2059 100644
--- a/tests/test_router_events.py
+++ b/tests/test_router_events.py
@@ -77,7 +77,7 @@ def test_router_events():
assert state.router_shutdown is False
assert state.sub_router_shutdown is False
response = client.get("/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello World"}
assert state.app_startup is True
assert state.router_startup is True
diff --git a/tests/test_router_prefix_with_template.py b/tests/test_router_prefix_with_template.py
index b331c24bdf42f..163b213ff845c 100644
--- a/tests/test_router_prefix_with_template.py
+++ b/tests/test_router_prefix_with_template.py
@@ -19,5 +19,5 @@ def read_user(segment: str, id: str):
def test_get():
response = client.get("/seg/users/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"segment": "seg", "id": "foo"}
diff --git a/tests/test_security_api_key_cookie.py b/tests/test_security_api_key_cookie.py
index 6b9642988103e..a5b2e44f0ce50 100644
--- a/tests/test_security_api_key_cookie.py
+++ b/tests/test_security_api_key_cookie.py
@@ -52,17 +52,17 @@ def read_current_user(current_user: User = Depends(get_current_user)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_api_key():
response = client.get("/users/me", cookies={"key": "secret"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
response = client.get("/users/me")
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Not authenticated"}
diff --git a/tests/test_security_api_key_cookie_optional.py b/tests/test_security_api_key_cookie_optional.py
index 0f3da9ad5edc0..96a64f09a6e7d 100644
--- a/tests/test_security_api_key_cookie_optional.py
+++ b/tests/test_security_api_key_cookie_optional.py
@@ -59,17 +59,17 @@ def read_current_user(current_user: User = Depends(get_current_user)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_api_key():
response = client.get("/users/me", cookies={"key": "secret"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
response = client.get("/users/me")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
diff --git a/tests/test_security_api_key_header.py b/tests/test_security_api_key_header.py
index a871a65fe419f..d53395f9991ac 100644
--- a/tests/test_security_api_key_header.py
+++ b/tests/test_security_api_key_header.py
@@ -52,17 +52,17 @@ def read_current_user(current_user: User = Depends(get_current_user)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_api_key():
response = client.get("/users/me", headers={"key": "secret"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
response = client.get("/users/me")
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Not authenticated"}
diff --git a/tests/test_security_api_key_header_optional.py b/tests/test_security_api_key_header_optional.py
index f71bac9cf6ccf..4ab599c2ddd28 100644
--- a/tests/test_security_api_key_header_optional.py
+++ b/tests/test_security_api_key_header_optional.py
@@ -58,17 +58,17 @@ def read_current_user(current_user: Optional[User] = Depends(get_current_user)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_api_key():
response = client.get("/users/me", headers={"key": "secret"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
response = client.get("/users/me")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
diff --git a/tests/test_security_api_key_query.py b/tests/test_security_api_key_query.py
index 228f2a7a3baf9..4844c65e22ad4 100644
--- a/tests/test_security_api_key_query.py
+++ b/tests/test_security_api_key_query.py
@@ -52,17 +52,17 @@ def read_current_user(current_user: User = Depends(get_current_user)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_api_key():
response = client.get("/users/me?key=secret")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
response = client.get("/users/me")
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Not authenticated"}
diff --git a/tests/test_security_api_key_query_optional.py b/tests/test_security_api_key_query_optional.py
index ddbdd55671edd..9339b7b3aa0c0 100644
--- a/tests/test_security_api_key_query_optional.py
+++ b/tests/test_security_api_key_query_optional.py
@@ -58,17 +58,17 @@ def read_current_user(current_user: Optional[User] = Depends(get_current_user)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_api_key():
response = client.get("/users/me?key=secret")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "secret"}
def test_security_api_key_no_key():
response = client.get("/users/me")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
diff --git a/tests/test_security_http_base.py b/tests/test_security_http_base.py
index 7e2c191ef1037..89471627968fa 100644
--- a/tests/test_security_http_base.py
+++ b/tests/test_security_http_base.py
@@ -40,17 +40,17 @@ def read_current_user(credentials: HTTPAuthorizationCredentials = Security(secur
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_http_base():
response = client.get("/users/me", headers={"Authorization": "Other foobar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Other", "credentials": "foobar"}
def test_security_http_base_no_credentials():
response = client.get("/users/me")
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Not authenticated"}
diff --git a/tests/test_security_http_base_optional.py b/tests/test_security_http_base_optional.py
index 4cc757dfb43bd..5a50f9b88c54d 100644
--- a/tests/test_security_http_base_optional.py
+++ b/tests/test_security_http_base_optional.py
@@ -46,17 +46,17 @@ def read_current_user(
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_http_base():
response = client.get("/users/me", headers={"Authorization": "Other foobar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Other", "credentials": "foobar"}
def test_security_http_base_no_credentials():
response = client.get("/users/me")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
diff --git a/tests/test_security_http_basic_optional.py b/tests/test_security_http_basic_optional.py
index b80fadff312e5..289bd5c74cfe5 100644
--- a/tests/test_security_http_basic_optional.py
+++ b/tests/test_security_http_basic_optional.py
@@ -46,20 +46,20 @@ def read_current_user(credentials: Optional[HTTPBasicCredentials] = Security(sec
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_http_basic():
auth = HTTPBasicAuth(username="john", password="secret")
response = client.get("/users/me", auth=auth)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "john", "password": "secret"}
def test_security_http_basic_no_credentials():
response = client.get("/users/me")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
@@ -67,7 +67,7 @@ def test_security_http_basic_invalid_credentials():
response = client.get(
"/users/me", headers={"Authorization": "Basic notabase64token"}
)
- assert response.status_code == 401
+ assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == "Basic"
assert response.json() == {"detail": "Invalid authentication credentials"}
@@ -76,6 +76,6 @@ def test_security_http_basic_non_basic_credentials():
payload = b64encode(b"johnsecret").decode("ascii")
auth_header = f"Basic {payload}"
response = client.get("/users/me", headers={"Authorization": auth_header})
- assert response.status_code == 401
+ assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == "Basic"
assert response.json() == {"detail": "Invalid authentication credentials"}
diff --git a/tests/test_security_http_basic_realm.py b/tests/test_security_http_basic_realm.py
index 117c9ef0244d2..54867c2e01b57 100644
--- a/tests/test_security_http_basic_realm.py
+++ b/tests/test_security_http_basic_realm.py
@@ -43,21 +43,21 @@ def read_current_user(credentials: HTTPBasicCredentials = Security(security)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_http_basic():
auth = HTTPBasicAuth(username="john", password="secret")
response = client.get("/users/me", auth=auth)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "john", "password": "secret"}
def test_security_http_basic_no_credentials():
response = client.get("/users/me")
assert response.json() == {"detail": "Not authenticated"}
- assert response.status_code == 401
+ assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
@@ -65,7 +65,7 @@ def test_security_http_basic_invalid_credentials():
response = client.get(
"/users/me", headers={"Authorization": "Basic notabase64token"}
)
- assert response.status_code == 401
+ assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
assert response.json() == {"detail": "Invalid authentication credentials"}
@@ -74,6 +74,6 @@ def test_security_http_basic_non_basic_credentials():
payload = b64encode(b"johnsecret").decode("ascii")
auth_header = f"Basic {payload}"
response = client.get("/users/me", headers={"Authorization": auth_header})
- assert response.status_code == 401
+ assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"'
assert response.json() == {"detail": "Invalid authentication credentials"}
diff --git a/tests/test_security_http_bearer.py b/tests/test_security_http_bearer.py
index a05fbf4472b0d..39d8c84029d87 100644
--- a/tests/test_security_http_bearer.py
+++ b/tests/test_security_http_bearer.py
@@ -40,23 +40,23 @@ def read_current_user(credentials: HTTPAuthorizationCredentials = Security(secur
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_http_bearer():
response = client.get("/users/me", headers={"Authorization": "Bearer foobar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Bearer", "credentials": "foobar"}
def test_security_http_bearer_no_credentials():
response = client.get("/users/me")
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Not authenticated"}
def test_security_http_bearer_incorrect_scheme_credentials():
response = client.get("/users/me", headers={"Authorization": "Basic notreally"})
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Invalid authentication credentials"}
diff --git a/tests/test_security_http_bearer_optional.py b/tests/test_security_http_bearer_optional.py
index f1f202abb61dd..2e7dfb8a4e7c4 100644
--- a/tests/test_security_http_bearer_optional.py
+++ b/tests/test_security_http_bearer_optional.py
@@ -46,23 +46,23 @@ def read_current_user(
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_http_bearer():
response = client.get("/users/me", headers={"Authorization": "Bearer foobar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Bearer", "credentials": "foobar"}
def test_security_http_bearer_no_credentials():
response = client.get("/users/me")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_security_http_bearer_incorrect_scheme_credentials():
response = client.get("/users/me", headers={"Authorization": "Basic notreally"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
diff --git a/tests/test_security_http_digest.py b/tests/test_security_http_digest.py
index e6b9919916bfc..8388824ff2bde 100644
--- a/tests/test_security_http_digest.py
+++ b/tests/test_security_http_digest.py
@@ -40,19 +40,19 @@ def read_current_user(credentials: HTTPAuthorizationCredentials = Security(secur
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_http_digest():
response = client.get("/users/me", headers={"Authorization": "Digest foobar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Digest", "credentials": "foobar"}
def test_security_http_digest_no_credentials():
response = client.get("/users/me")
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Not authenticated"}
@@ -60,5 +60,5 @@ def test_security_http_digest_incorrect_scheme_credentials():
response = client.get(
"/users/me", headers={"Authorization": "Other invalidauthorization"}
)
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Invalid authentication credentials"}
diff --git a/tests/test_security_http_digest_optional.py b/tests/test_security_http_digest_optional.py
index 83c4539351fd0..2177b819f3b26 100644
--- a/tests/test_security_http_digest_optional.py
+++ b/tests/test_security_http_digest_optional.py
@@ -46,19 +46,19 @@ def read_current_user(
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_http_digest():
response = client.get("/users/me", headers={"Authorization": "Digest foobar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"scheme": "Digest", "credentials": "foobar"}
def test_security_http_digest_no_credentials():
response = client.get("/users/me")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
@@ -66,5 +66,5 @@ def test_security_http_digest_incorrect_scheme_credentials():
response = client.get(
"/users/me", headers={"Authorization": "Other invalidauthorization"}
)
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Invalid authentication credentials"}
diff --git a/tests/test_security_oauth2.py b/tests/test_security_oauth2.py
index 3f96846d48c67..266dab6e5a7b9 100644
--- a/tests/test_security_oauth2.py
+++ b/tests/test_security_oauth2.py
@@ -156,25 +156,25 @@ def read_current_user(current_user: "User" = Depends(get_current_user)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_oauth2():
response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "Other footokenbar"}
def test_security_oauth2_password_bearer_no_header():
response = client.get("/users/me")
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Not authenticated"}
diff --git a/tests/test_security_oauth2_authorization_code_bearer.py b/tests/test_security_oauth2_authorization_code_bearer.py
index ab088d67c7973..3e0155e1fa9f0 100644
--- a/tests/test_security_oauth2_authorization_code_bearer.py
+++ b/tests/test_security_oauth2_authorization_code_bearer.py
@@ -55,23 +55,23 @@ async def read_items(token: Optional[str] = Security(oauth2_scheme)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_no_token():
response = client.get("/items")
- assert response.status_code == 401
+ assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
def test_incorrect_token():
response = client.get("/items", headers={"Authorization": "Non-existent testtoken"})
- assert response.status_code == 401
+ assert response.status_code == 401, response.text
assert response.json() == {"detail": "Not authenticated"}
def test_token():
response = client.get("/items", headers={"Authorization": "Bearer testtoken"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"token": "testtoken"}
diff --git a/tests/test_security_oauth2_optional.py b/tests/test_security_oauth2_optional.py
index 8732dd03701dc..06967bd766081 100644
--- a/tests/test_security_oauth2_optional.py
+++ b/tests/test_security_oauth2_optional.py
@@ -160,25 +160,25 @@ def read_current_user(current_user: Optional[User] = Depends(get_current_user)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_oauth2():
response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "Other footokenbar"}
def test_security_oauth2_password_bearer_no_header():
response = client.get("/users/me")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
diff --git a/tests/test_security_oauth2_password_bearer_optional.py b/tests/test_security_oauth2_password_bearer_optional.py
index 0c36796aef8af..3d6637d4a5a6d 100644
--- a/tests/test_security_oauth2_password_bearer_optional.py
+++ b/tests/test_security_oauth2_password_bearer_optional.py
@@ -49,23 +49,23 @@ async def read_items(token: Optional[str] = Security(oauth2_scheme)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_no_token():
response = client.get("/items")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
def test_token():
response = client.get("/items", headers={"Authorization": "Bearer testtoken"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"token": "testtoken"}
def test_incorrect_token():
response = client.get("/items", headers={"Authorization": "Notexistent testtoken"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
diff --git a/tests/test_security_openid_connect.py b/tests/test_security_openid_connect.py
index 07596ecfe0214..8203961bedb01 100644
--- a/tests/test_security_openid_connect.py
+++ b/tests/test_security_openid_connect.py
@@ -52,23 +52,23 @@ def read_current_user(current_user: User = Depends(get_current_user)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_oauth2():
response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "Other footokenbar"}
def test_security_oauth2_password_bearer_no_header():
response = client.get("/users/me")
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "Not authenticated"}
diff --git a/tests/test_security_openid_connect_optional.py b/tests/test_security_openid_connect_optional.py
index 8aff16f282250..4577dfebb02f4 100644
--- a/tests/test_security_openid_connect_optional.py
+++ b/tests/test_security_openid_connect_optional.py
@@ -58,23 +58,23 @@ def read_current_user(current_user: Optional[User] = Depends(get_current_user)):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_security_oauth2():
response = client.get("/users/me", headers={"Authorization": "Bearer footokenbar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "Bearer footokenbar"}
def test_security_oauth2_password_other_header():
response = client.get("/users/me", headers={"Authorization": "Other footokenbar"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"username": "Other footokenbar"}
def test_security_oauth2_password_bearer_no_header():
response = client.get("/users/me")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Create an account first"}
diff --git a/tests/test_serialize_response_model.py b/tests/test_serialize_response_model.py
new file mode 100644
index 0000000000000..adb7fda344f6a
--- /dev/null
+++ b/tests/test_serialize_response_model.py
@@ -0,0 +1,154 @@
+from typing import Dict, List
+
+from fastapi import FastAPI
+from pydantic import BaseModel, Field
+from starlette.testclient import TestClient
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str = Field(..., alias="aliased_name")
+ price: float = None
+ owner_ids: List[int] = None
+
+
+@app.get("/items/valid", response_model=Item)
+def get_valid():
+ return Item(aliased_name="valid", price=1.0)
+
+
+@app.get("/items/coerce", response_model=Item)
+def get_coerce():
+ return Item(aliased_name="coerce", price="1.0")
+
+
+@app.get("/items/validlist", response_model=List[Item])
+def get_validlist():
+ return [
+ Item(aliased_name="foo"),
+ Item(aliased_name="bar", price=1.0),
+ Item(aliased_name="baz", price=2.0, owner_ids=[1, 2, 3]),
+ ]
+
+
+@app.get("/items/validdict", response_model=Dict[str, Item])
+def get_validdict():
+ return {
+ "k1": Item(aliased_name="foo"),
+ "k2": Item(aliased_name="bar", price=1.0),
+ "k3": Item(aliased_name="baz", price=2.0, owner_ids=[1, 2, 3]),
+ }
+
+
+@app.get(
+ "/items/valid-exclude-unset", response_model=Item, response_model_exclude_unset=True
+)
+def get_valid_exclude_unset():
+ return Item(aliased_name="valid", price=1.0)
+
+
+@app.get(
+ "/items/coerce-exclude-unset",
+ response_model=Item,
+ response_model_exclude_unset=True,
+)
+def get_coerce_exclude_unset():
+ return Item(aliased_name="coerce", price="1.0")
+
+
+@app.get(
+ "/items/validlist-exclude-unset",
+ response_model=List[Item],
+ response_model_exclude_unset=True,
+)
+def get_validlist_exclude_unset():
+ return [
+ Item(aliased_name="foo"),
+ Item(aliased_name="bar", price=1.0),
+ Item(aliased_name="baz", price=2.0, owner_ids=[1, 2, 3]),
+ ]
+
+
+@app.get(
+ "/items/validdict-exclude-unset",
+ response_model=Dict[str, Item],
+ response_model_exclude_unset=True,
+)
+def get_validdict_exclude_unset():
+ return {
+ "k1": Item(aliased_name="foo"),
+ "k2": Item(aliased_name="bar", price=1.0),
+ "k3": Item(aliased_name="baz", price=2.0, owner_ids=[1, 2, 3]),
+ }
+
+
+client = TestClient(app)
+
+
+def test_valid():
+ response = client.get("/items/valid")
+ response.raise_for_status()
+ assert response.json() == {"aliased_name": "valid", "price": 1.0, "owner_ids": None}
+
+
+def test_coerce():
+ response = client.get("/items/coerce")
+ response.raise_for_status()
+ assert response.json() == {
+ "aliased_name": "coerce",
+ "price": 1.0,
+ "owner_ids": None,
+ }
+
+
+def test_validlist():
+ response = client.get("/items/validlist")
+ response.raise_for_status()
+ assert response.json() == [
+ {"aliased_name": "foo", "price": None, "owner_ids": None},
+ {"aliased_name": "bar", "price": 1.0, "owner_ids": None},
+ {"aliased_name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]},
+ ]
+
+
+def test_validdict():
+ response = client.get("/items/validdict")
+ response.raise_for_status()
+ assert response.json() == {
+ "k1": {"aliased_name": "foo", "price": None, "owner_ids": None},
+ "k2": {"aliased_name": "bar", "price": 1.0, "owner_ids": None},
+ "k3": {"aliased_name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]},
+ }
+
+
+def test_valid_exclude_unset():
+ response = client.get("/items/valid-exclude-unset")
+ response.raise_for_status()
+ assert response.json() == {"aliased_name": "valid", "price": 1.0}
+
+
+def test_coerce_exclude_unset():
+ response = client.get("/items/coerce-exclude-unset")
+ response.raise_for_status()
+ assert response.json() == {"aliased_name": "coerce", "price": 1.0}
+
+
+def test_validlist_exclude_unset():
+ response = client.get("/items/validlist-exclude-unset")
+ response.raise_for_status()
+ assert response.json() == [
+ {"aliased_name": "foo"},
+ {"aliased_name": "bar", "price": 1.0},
+ {"aliased_name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]},
+ ]
+
+
+def test_validdict_exclude_unset():
+ response = client.get("/items/validdict-exclude-unset")
+ response.raise_for_status()
+ assert response.json() == {
+ "k1": {"aliased_name": "foo"},
+ "k2": {"aliased_name": "bar", "price": 1.0},
+ "k3": {"aliased_name": "baz", "price": 2.0, "owner_ids": [1, 2, 3]},
+ }
diff --git a/tests/test_skip_defaults.py b/tests/test_skip_defaults.py
index c9a85a305a3c3..ed84df66c40b2 100644
--- a/tests/test_skip_defaults.py
+++ b/tests/test_skip_defaults.py
@@ -18,11 +18,53 @@ class Model(BaseModel):
class ModelSubclass(Model):
y: int
+ z: int = 0
+ w: int = None
+
+
+class ModelDefaults(BaseModel):
+ w: Optional[str] = None
+ x: Optional[str] = None
+ y: str = "y"
+ z: str = "z"
@app.get("/", response_model=Model, response_model_exclude_unset=True)
def get() -> ModelSubclass:
- return ModelSubclass(sub={}, y=1)
+ return ModelSubclass(sub={}, y=1, z=0)
+
+
+@app.get(
+ "/exclude_unset", response_model=ModelDefaults, response_model_exclude_unset=True
+)
+def get() -> ModelDefaults:
+ return ModelDefaults(x=None, y="y")
+
+
+@app.get(
+ "/exclude_defaults",
+ response_model=ModelDefaults,
+ response_model_exclude_defaults=True,
+)
+def get() -> ModelDefaults:
+ return ModelDefaults(x=None, y="y")
+
+
+@app.get(
+ "/exclude_none", response_model=ModelDefaults, response_model_exclude_none=True
+)
+def get() -> ModelDefaults:
+ return ModelDefaults(x=None, y="y")
+
+
+@app.get(
+ "/exclude_unset_none",
+ response_model=ModelDefaults,
+ response_model_exclude_unset=True,
+ response_model_exclude_none=True,
+)
+def get() -> ModelDefaults:
+ return ModelDefaults(x=None, y="y")
client = TestClient(app)
@@ -31,3 +73,23 @@ def get() -> ModelSubclass:
def test_return_defaults():
response = client.get("/")
assert response.json() == {"sub": {}}
+
+
+def test_return_exclude_unset():
+ response = client.get("/exclude_unset")
+ assert response.json() == {"x": None, "y": "y"}
+
+
+def test_return_exclude_defaults():
+ response = client.get("/exclude_defaults")
+ assert response.json() == {}
+
+
+def test_return_exclude_none():
+ response = client.get("/exclude_none")
+ assert response.json() == {"y": "y", "z": "z"}
+
+
+def test_return_exclude_unset_none():
+ response = client.get("/exclude_unset_none")
+ assert response.json() == {"y": "y"}
diff --git a/tests/test_starlette_exception.py b/tests/test_starlette_exception.py
index 6cd9b8208b034..c83af6ca5b5f5 100644
--- a/tests/test_starlette_exception.py
+++ b/tests/test_starlette_exception.py
@@ -126,31 +126,31 @@ async def create_item(item_id: str):
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_item():
response = client.get("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item": "The Foo Wrestlers"}
def test_get_item_not_found():
response = client.get("/items/bar")
- assert response.status_code == 404
+ assert response.status_code == 404, response.text
assert response.headers.get("x-error") == "Some custom header"
assert response.json() == {"detail": "Item not found"}
def test_get_starlette_item():
response = client.get("/starlette-items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item": "The Foo Wrestlers"}
def test_get_starlette_item_not_found():
response = client.get("/starlette-items/bar")
- assert response.status_code == 404
+ assert response.status_code == 404, response.text
assert response.headers.get("x-error") is None
assert response.json() == {"detail": "Item not found"}
diff --git a/tests/test_starlette_urlconvertors.py b/tests/test_starlette_urlconvertors.py
index 97fa41f2986c2..1ea22116c8702 100644
--- a/tests/test_starlette_urlconvertors.py
+++ b/tests/test_starlette_urlconvertors.py
@@ -25,7 +25,7 @@ def path_convertor(param: str = Path(...)):
def test_route_converters_int():
# Test integer conversion
response = client.get("/int/5")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"int": 5}
assert app.url_path_for("int_convertor", param=5) == "/int/5"
@@ -33,7 +33,7 @@ def test_route_converters_int():
def test_route_converters_float():
# Test float conversion
response = client.get("/float/25.5")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"float": 25.5}
assert app.url_path_for("float_convertor", param=25.5) == "/float/25.5"
@@ -41,7 +41,7 @@ def test_route_converters_float():
def test_route_converters_path():
# Test path conversion
response = client.get("/path/some/example")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"path": "some/example"}
diff --git a/tests/test_sub_callbacks.py b/tests/test_sub_callbacks.py
index c5a22e8b7c5ce..3de3cea9939d6 100644
--- a/tests/test_sub_callbacks.py
+++ b/tests/test_sub_callbacks.py
@@ -221,7 +221,7 @@ def test_get():
response = client.post(
"/invoices/", json={"id": "fooinvoice", "customer": "John", "total": 5.3}
)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Invoice received"}
diff --git a/tests/test_swagger_ui_init_oauth.py b/tests/test_swagger_ui_init_oauth.py
index fc6b265dbcb3a..371cd72fb7529 100644
--- a/tests/test_swagger_ui_init_oauth.py
+++ b/tests/test_swagger_ui_init_oauth.py
@@ -16,7 +16,7 @@ async def read_items():
def test_swagger_ui():
response = client.get("/docs")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
print(response.text)
assert f"ui.initOAuth" in response.text
assert f'"appName": "The Predendapp"' in response.text
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial001.py b/tests/test_tutorial/test_additional_responses/test_tutorial001.py
index b6ba63f5ab6e8..82dec78adaa4a 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial001.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial001.py
@@ -100,17 +100,17 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_path_operation():
response = client.get("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"id": "foo", "value": "there goes my hero"}
def test_path_operation_not_found():
response = client.get("/items/bar")
- assert response.status_code == 404
+ assert response.status_code == 404, response.text
assert response.json() == {"message": "Item not found"}
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial002.py b/tests/test_tutorial/test_additional_responses/test_tutorial002.py
index 09a06d957771e..274c95663f256 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial002.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial002.py
@@ -96,20 +96,20 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_path_operation():
response = client.get("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"id": "foo", "value": "there goes my hero"}
def test_path_operation_img():
- shutil.copy("./docs/img/favicon.png", "./image.png")
+ shutil.copy("./docs/en/docs/img/favicon.png", "./image.png")
response = client.get("/items/foo?img=1")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["Content-Type"] == "image/png"
assert len(response.content)
os.remove("./image.png")
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial003.py b/tests/test_tutorial/test_additional_responses/test_tutorial003.py
index 52144f7ae29ec..6787f9d29afff 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial003.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial003.py
@@ -101,17 +101,17 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_path_operation():
response = client.get("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"id": "foo", "value": "there goes my hero"}
def test_path_operation_not_found():
response = client.get("/items/bar")
- assert response.status_code == 404
+ assert response.status_code == 404, response.text
assert response.json() == {"message": "Item not found"}
diff --git a/tests/test_tutorial/test_additional_responses/test_tutorial004.py b/tests/test_tutorial/test_additional_responses/test_tutorial004.py
index d1285c8ea2009..d7456630ef477 100644
--- a/tests/test_tutorial/test_additional_responses/test_tutorial004.py
+++ b/tests/test_tutorial/test_additional_responses/test_tutorial004.py
@@ -99,20 +99,20 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_path_operation():
response = client.get("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"id": "foo", "value": "there goes my hero"}
def test_path_operation_img():
- shutil.copy("./docs/img/favicon.png", "./image.png")
+ shutil.copy("./docs/en/docs/img/favicon.png", "./image.png")
response = client.get("/items/foo?img=1")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.headers["Content-Type"] == "image/png"
assert len(response.content)
os.remove("./image.png")
diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py
index ccfe343dc46c1..e2131c71ba5c1 100644
--- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py
+++ b/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py
@@ -7,11 +7,11 @@
def test_update():
response = client.put("/items/foo", json={"name": "Wrestlers"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"name": "Wrestlers", "size": None}
def test_create():
response = client.put("/items/red", json={"name": "Chillies"})
- assert response.status_code == 201
+ assert response.status_code == 201, response.text
assert response.json() == {"name": "Chillies", "size": None}
diff --git a/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py b/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py
index f49f50f0cd506..fb5058bcd3e4b 100644
--- a/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py
+++ b/tests/test_tutorial/test_advanced_middleware/test_tutorial001.py
@@ -6,9 +6,9 @@
def test_middleware():
client = TestClient(app, base_url="https://testserver")
response = client.get("/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
client = TestClient(app)
response = client.get("/", allow_redirects=False)
- assert response.status_code == 307
+ assert response.status_code == 307, response.text
assert response.headers["location"] == "https://testserver/"
diff --git a/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py b/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py
index da1d60ba8d95d..bac2dea8ba5a1 100644
--- a/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py
+++ b/tests/test_tutorial/test_advanced_middleware/test_tutorial002.py
@@ -6,10 +6,10 @@
def test_middleware():
client = TestClient(app, base_url="http://example.com")
response = client.get("/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
client = TestClient(app, base_url="http://subdomain.example.com")
response = client.get("/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
client = TestClient(app, base_url="http://invalidhost")
response = client.get("/")
- assert response.status_code == 400
+ assert response.status_code == 400, response.text
diff --git a/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py b/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py
index 0d482b81c2338..230a5742df342 100644
--- a/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py
+++ b/tests/test_tutorial/test_advanced_middleware/test_tutorial003.py
@@ -14,9 +14,9 @@ async def large():
def test_middleware():
response = client.get("/large", headers={"accept-encoding": "gzip"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.text == "x" * 4000
assert response.headers["Content-Encoding"] == "gzip"
assert int(response.headers["Content-Length"]) < 4000
response = client.get("/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
diff --git a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py
index 553f42c2f4526..17214f874ca02 100644
--- a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py
+++ b/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py
@@ -113,7 +113,7 @@
def test_openapi_schema():
with TestClient(app) as client:
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
@@ -121,11 +121,11 @@ def test_create_read():
with TestClient(app) as client:
note = {"text": "Foo bar", "completed": False}
response = client.post("/notes/", json=note)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
data = response.json()
assert data["text"] == note["text"]
assert data["completed"] == note["completed"]
assert "id" in data
response = client.get(f"/notes/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert data in response.json()
diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial001.py b/tests/test_tutorial/test_background_tasks/test_tutorial001.py
index a1381a9d5a9ef..8c8628982542a 100644
--- a/tests/test_tutorial/test_background_tasks/test_tutorial001.py
+++ b/tests/test_tutorial/test_background_tasks/test_tutorial001.py
@@ -13,7 +13,7 @@ def test():
if log.is_file():
os.remove(log) # pragma: no cover
response = client.post("/send-notification/foo@example.com")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"message": "Notification sent in the background"}
with open("./log.txt") as f:
assert "notification for foo@example.com: some notification" in f.read()
diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002.py b/tests/test_tutorial/test_background_tasks/test_tutorial002.py
index 861e83aef081b..d3ad37271000a 100644
--- a/tests/test_tutorial/test_background_tasks/test_tutorial002.py
+++ b/tests/test_tutorial/test_background_tasks/test_tutorial002.py
@@ -13,7 +13,7 @@ def test():
if log.is_file():
os.remove(log) # pragma: no cover
response = client.post("/send-notification/foo@example.com?q=some-query")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"message": "Message sent"}
with open("./log.txt") as f:
assert "found query: some-query\nmessage to foo@example.com" in f.read()
diff --git a/tests/test_tutorial/test_behind_a_proxy/__init__.py b/tests/test_tutorial/test_behind_a_proxy/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py
new file mode 100644
index 0000000000000..8b3b526edc38a
--- /dev/null
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial001.py
@@ -0,0 +1,36 @@
+from fastapi.testclient import TestClient
+
+from behind_a_proxy.tutorial001 import app
+
+client = TestClient(app, root_path="/api/v1")
+
+openapi_schema = {
+ "openapi": "3.0.2",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/api/v1/app": {
+ "get": {
+ "summary": "Read Main",
+ "operationId": "read_main_app_get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ }
+ }
+ },
+}
+
+
+def test_openapi():
+ response = client.get("/openapi.json")
+ assert response.status_code == 200
+ assert response.json() == openapi_schema
+
+
+def test_main():
+ response = client.get("/app")
+ assert response.status_code == 200
+ assert response.json() == {"message": "Hello World", "root_path": "/api/v1"}
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial001.py b/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py
similarity index 67%
rename from tests/test_tutorial/test_custom_response/test_tutorial001.py
rename to tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py
index 0152d0134c9e2..0a889c4697f55 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial001.py
+++ b/tests/test_tutorial/test_behind_a_proxy/test_tutorial002.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from custom_response.tutorial001 import app
+from behind_a_proxy.tutorial002 import app
client = TestClient(app)
@@ -8,29 +8,29 @@
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
- "/items/": {
+ "/api/v1/app": {
"get": {
+ "summary": "Read Main",
+ "operationId": "read_main_app_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
}
},
- "summary": "Read Items",
- "operationId": "read_items_items__get",
}
}
},
}
-def test_openapi_schema():
+def test_openapi():
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == openapi_schema
-def test_get_custom_response():
- response = client.get("/items/")
+def test_main():
+ response = client.get("/app")
assert response.status_code == 200
- assert response.json() == [{"item_id": "Foo"}]
+ assert response.json() == {"message": "Hello World", "root_path": "/api/v1"}
diff --git a/tests/test_tutorial/test_bigger_applications/test_main.py b/tests/test_tutorial/test_bigger_applications/test_main.py
index b60bd6499c385..1a90ba05bb5de 100644
--- a/tests/test_tutorial/test_bigger_applications/test_main.py
+++ b/tests/test_tutorial/test_bigger_applications/test_main.py
@@ -270,7 +270,7 @@ def test_get_path(path, expected_status, expected_response, headers):
def test_put_no_header():
response = client.put("/items/foo")
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
@@ -284,17 +284,17 @@ def test_put_no_header():
def test_put_invalid_header():
response = client.put("/items/foo", headers={"X-Token": "invalid"})
- assert response.status_code == 400
+ assert response.status_code == 400, response.text
assert response.json() == {"detail": "X-Token header invalid"}
def test_put():
response = client.put("/items/foo", headers={"X-Token": "fake-super-secret-token"})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo", "name": "The Fighters"}
def test_put_forbidden():
response = client.put("/items/bar", headers={"X-Token": "fake-super-secret-token"})
- assert response.status_code == 403
+ assert response.status_code == 403, response.text
assert response.json() == {"detail": "You can only update the item: foo"}
diff --git a/tests/test_tutorial/test_body/test_tutorial001.py b/tests/test_tutorial/test_body/test_tutorial001.py
index f3aded151eb3b..293981a09d8f4 100644
--- a/tests/test_tutorial/test_body/test_tutorial001.py
+++ b/tests/test_tutorial/test_body/test_tutorial001.py
@@ -85,7 +85,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
@@ -176,5 +176,5 @@ def test_post_body(path, body, expected_status, expected_response):
def test_post_broken_body():
response = client.post("/items/", data={"name": "Foo", "price": 50.5})
- assert response.status_code == 400
+ assert response.status_code == 400, response.text
assert response.json() == {"detail": "There was an error parsing the body"}
diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001.py b/tests/test_tutorial/test_body_fields/test_tutorial001.py
index a437c62ec17b1..b5e95a3cf6edf 100644
--- a/tests/test_tutorial/test_body_fields/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_fields/test_tutorial001.py
@@ -120,7 +120,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
index 6241396f361c8..19972668dc74f 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py
@@ -103,7 +103,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
index d93da39fce182..d228f9f67f702 100644
--- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
+++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py
@@ -114,7 +114,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
index 7ea7e5c74f63a..8a9f395331082 100644
--- a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
+++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py
@@ -77,21 +77,21 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_post_body():
data = {"2": 2.2, "3": 3.3}
response = client.post("/index-weights/", json=data)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == data
def test_post_invalid_body():
data = {"foo": 2.2, "3": 3.3}
response = client.post("/index-weights/", json=data)
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001.py b/tests/test_tutorial/test_body_updates/test_tutorial001.py
index d0777655601f7..b5f77af120184 100644
--- a/tests/test_tutorial/test_body_updates/test_tutorial001.py
+++ b/tests/test_tutorial/test_body_updates/test_tutorial001.py
@@ -133,13 +133,13 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get():
response = client.get("/items/baz")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {
"name": "Baz",
"description": None,
diff --git a/tests/test_tutorial/test_conditional_openapi/__init__.py b/tests/test_tutorial/test_conditional_openapi/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py b/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py
new file mode 100644
index 0000000000000..1914b7c2ce0e0
--- /dev/null
+++ b/tests/test_tutorial/test_conditional_openapi/test_tutorial001.py
@@ -0,0 +1,46 @@
+import importlib
+
+from fastapi.testclient import TestClient
+
+from conditional_openapi import tutorial001
+
+openapi_schema = {
+ "openapi": "3.0.2",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/": {
+ "get": {
+ "summary": "Root",
+ "operationId": "root__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ }
+ },
+ }
+ }
+ },
+}
+
+
+def test_default_openapi():
+ client = TestClient(tutorial001.app)
+ response = client.get("/openapi.json")
+ assert response.json() == openapi_schema
+ response = client.get("/docs")
+ assert response.status_code == 200, response.text
+ response = client.get("/redoc")
+ assert response.status_code == 200, response.text
+
+
+def test_disable_openapi(monkeypatch):
+ monkeypatch.setenv("OPENAPI_URL", "")
+ importlib.reload(tutorial001)
+ client = TestClient(tutorial001.app)
+ response = client.get("/openapi.json")
+ assert response.status_code == 404, response.text
+ response = client.get("/docs")
+ assert response.status_code == 404, response.text
+ response = client.get("/redoc")
+ assert response.status_code == 404, response.text
diff --git a/tests/test_tutorial/test_cors/test_tutorial001.py b/tests/test_tutorial/test_cors/test_tutorial001.py
index dc3078e481417..e3f6b73501d4b 100644
--- a/tests/test_tutorial/test_cors/test_tutorial001.py
+++ b/tests/test_tutorial/test_cors/test_tutorial001.py
@@ -12,7 +12,7 @@ def test_cors():
"Access-Control-Request-Headers": "X-Example",
}
response = client.options("/", headers=headers)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.text == "OK"
assert (
response.headers["access-control-allow-origin"]
@@ -23,7 +23,7 @@ def test_cors():
# Test standard response
headers = {"Origin": "https://localhost.tiangolo.com"}
response = client.get("/", headers=headers)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello World"}
assert (
response.headers["access-control-allow-origin"]
@@ -32,6 +32,6 @@ def test_cors():
# Test non-CORS response
response = client.get("/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"message": "Hello World"}
assert "access-control-allow-origin" not in response.headers
diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py
index 73905f9f5db3e..376b1f69ba6fd 100644
--- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py
+++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial003.py
@@ -15,4 +15,4 @@ def test_get_timed():
response = client.get("/timed")
assert response.json() == {"message": "It's the time of my life"}
assert "X-Response-Time" in response.headers
- assert float(response.headers["X-Response-Time"]) > 0
+ assert float(response.headers["X-Response-Time"]) >= 0
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial001b.py b/tests/test_tutorial/test_custom_response/test_tutorial001b.py
index 08f372897d567..b061ef20bb950 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial001b.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial001b.py
@@ -26,11 +26,11 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_custom_response():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "Foo"}]
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial004.py b/tests/test_tutorial/test_custom_response/test_tutorial004.py
index c9d120058699a..9cc27705f92d9 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial004.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial004.py
@@ -37,11 +37,11 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_custom_response():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.text == html_contents
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial005.py b/tests/test_tutorial/test_custom_response/test_tutorial005.py
index 4755408e2ccf0..d5a74308c3682 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial005.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial005.py
@@ -26,11 +26,11 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get():
response = client.get("/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.text == "Hello World"
diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006.py b/tests/test_tutorial/test_custom_response/test_tutorial006.py
index 2a90568c46f75..07daf2cf2b558 100644
--- a/tests/test_tutorial/test_custom_response/test_tutorial006.py
+++ b/tests/test_tutorial/test_custom_response/test_tutorial006.py
@@ -7,5 +7,5 @@
def test_get():
response = client.get("/typer", allow_redirects=False)
- assert response.status_code == 307
+ assert response.status_code == 307, response.text
assert response.headers["location"] == "https://typer.tiangolo.com"
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001.py b/tests/test_tutorial/test_dependencies/test_tutorial001.py
index 353e5c8ab7b0d..73d65cf50c73b 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial001.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial001.py
@@ -128,7 +128,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004.py b/tests/test_tutorial/test_dependencies/test_tutorial004.py
index 7e41bbd3b503c..bf62e9cbc3687 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial004.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial004.py
@@ -86,7 +86,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006.py b/tests/test_tutorial/test_dependencies/test_tutorial006.py
index 62f13f07a5c95..f3279bfe64e92 100644
--- a/tests/test_tutorial/test_dependencies/test_tutorial006.py
+++ b/tests/test_tutorial/test_dependencies/test_tutorial006.py
@@ -79,13 +79,13 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_no_headers():
response = client.get("/items/")
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
@@ -104,7 +104,7 @@ def test_get_no_headers():
def test_get_invalid_one_header():
response = client.get("/items/", headers={"X-Token": "invalid"})
- assert response.status_code == 400
+ assert response.status_code == 400, response.text
assert response.json() == {"detail": "X-Token header invalid"}
@@ -112,7 +112,7 @@ def test_get_invalid_second_header():
response = client.get(
"/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"}
)
- assert response.status_code == 400
+ assert response.status_code == 400, response.text
assert response.json() == {"detail": "X-Key header invalid"}
@@ -124,5 +124,5 @@ def test_get_valid_headers():
"X-Key": "fake-super-secret-key",
},
)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"item": "Foo"}, {"item": "Bar"}]
diff --git a/tests/test_tutorial/test_events/test_tutorial001.py b/tests/test_tutorial/test_events/test_tutorial001.py
index ebd3550af5bc7..2ab89b069e1cc 100644
--- a/tests/test_tutorial/test_events/test_tutorial001.py
+++ b/tests/test_tutorial/test_events/test_tutorial001.py
@@ -72,8 +72,8 @@
def test_events():
with TestClient(app) as client:
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
response = client.get("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"name": "Fighters"}
diff --git a/tests/test_tutorial/test_events/test_tutorial002.py b/tests/test_tutorial/test_events/test_tutorial002.py
index bb18802473866..c06ea3f1cbb13 100644
--- a/tests/test_tutorial/test_events/test_tutorial002.py
+++ b/tests/test_tutorial/test_events/test_tutorial002.py
@@ -25,10 +25,10 @@
def test_events():
with TestClient(app) as client:
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"name": "Foo"}]
with open("log.txt") as log:
assert "Application shutdown" in log.read()
diff --git a/tests/test_tutorial/test_extending_openapi/test_tutorial001.py b/tests/test_tutorial/test_extending_openapi/test_tutorial001.py
index c0cb8ddaa6fbf..88997f59d6db6 100644
--- a/tests/test_tutorial/test_extending_openapi/test_tutorial001.py
+++ b/tests/test_tutorial/test_extending_openapi/test_tutorial001.py
@@ -31,14 +31,14 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"name": "Foo"}]
diff --git a/tests/test_tutorial/test_extending_openapi/test_tutorial002.py b/tests/test_tutorial/test_extending_openapi/test_tutorial002.py
index 592fd84209016..06fb62f85249f 100644
--- a/tests/test_tutorial/test_extending_openapi/test_tutorial002.py
+++ b/tests/test_tutorial/test_extending_openapi/test_tutorial002.py
@@ -19,24 +19,24 @@ def client():
def test_swagger_ui_html(client: TestClient):
response = client.get("/docs")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert "/static/swagger-ui-bundle.js" in response.text
assert "/static/swagger-ui.css" in response.text
def test_swagger_ui_oauth2_redirect_html(client: TestClient):
response = client.get("/docs/oauth2-redirect")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert "window.opener.swaggerUIRedirectOauth2" in response.text
def test_redoc_html(client: TestClient):
response = client.get("/redoc")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert "/static/redoc.standalone.js" in response.text
def test_api(client: TestClient):
response = client.get("/users/john")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json()["message"] == "Hello john"
diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py
index 9695bce26d7bc..72de6308bec5e 100644
--- a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py
+++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py
@@ -113,7 +113,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
@@ -134,5 +134,5 @@ def test_extra_types():
}
)
response = client.put(f"/items/{item_id}", json=data)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == expected_response
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial003.py b/tests/test_tutorial/test_extra_models/test_tutorial003.py
index 2662a5710011f..150b899c6df37 100644
--- a/tests/test_tutorial/test_extra_models/test_tutorial003.py
+++ b/tests/test_tutorial/test_extra_models/test_tutorial003.py
@@ -102,13 +102,13 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_car():
response = client.get("/items/item1")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {
"description": "All my friends drive a low rider",
"type": "car",
@@ -117,7 +117,7 @@ def test_get_car():
def test_get_plane():
response = client.get("/items/item2")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {
"description": "Music is my aeroplane, it's my aeroplane",
"type": "plane",
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial004.py b/tests/test_tutorial/test_extra_models/test_tutorial004.py
index cb3bb33602ee3..08f859656cb83 100644
--- a/tests/test_tutorial/test_extra_models/test_tutorial004.py
+++ b/tests/test_tutorial/test_extra_models/test_tutorial004.py
@@ -47,13 +47,13 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_items():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [
{"name": "Foo", "description": "There comes my hero"},
{"name": "Red", "description": "It's my aeroplane"},
diff --git a/tests/test_tutorial/test_extra_models/test_tutorial005.py b/tests/test_tutorial/test_extra_models/test_tutorial005.py
index 413c147758cd7..bce5efecef293 100644
--- a/tests/test_tutorial/test_extra_models/test_tutorial005.py
+++ b/tests/test_tutorial/test_extra_models/test_tutorial005.py
@@ -34,11 +34,11 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_items():
response = client.get("/keyword-weights/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"foo": 2.3, "bar": 3.4}
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial001.py b/tests/test_tutorial/test_handling_errors/test_tutorial001.py
index da8ee9864a3c4..5a80bc5f60787 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial001.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial001.py
@@ -73,18 +73,18 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_item():
response = client.get("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item": "The Foo Wrestlers"}
def test_get_item_not_found():
response = client.get("/items/bar")
- assert response.status_code == 404
+ assert response.status_code == 404, response.text
assert response.headers.get("x-error") is None
assert response.json() == {"detail": "Item not found"}
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial002.py b/tests/test_tutorial/test_handling_errors/test_tutorial002.py
index f822ae0a1b707..4ffce6b2c1453 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial002.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial002.py
@@ -73,18 +73,18 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_item_header():
response = client.get("/items-header/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item": "The Foo Wrestlers"}
def test_get_item_not_found_header():
response = client.get("/items-header/bar")
- assert response.status_code == 404
+ assert response.status_code == 404, response.text
assert response.headers.get("x-error") == "There goes my error"
assert response.json() == {"detail": "Item not found"}
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial003.py b/tests/test_tutorial/test_handling_errors/test_tutorial003.py
index f63dc10d2bbd1..48da5db7cef58 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial003.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial003.py
@@ -73,19 +73,19 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get():
response = client.get("/unicorns/shinny")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"unicorn_name": "shinny"}
def test_get_exception():
response = client.get("/unicorns/yolo")
- assert response.status_code == 418
+ assert response.status_code == 418, response.text
assert response.json() == {
"message": "Oops! yolo did something. There goes a rainbow..."
}
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial004.py b/tests/test_tutorial/test_handling_errors/test_tutorial004.py
index eb8d629ece567..58b97c0034c4b 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial004.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial004.py
@@ -73,13 +73,13 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_validation_error():
response = client.get("/items/foo")
- assert response.status_code == 400
+ assert response.status_code == 400, response.text
validation_error_str_lines = [
b"1 validation error for Request",
b"path -> item_id",
@@ -90,11 +90,11 @@ def test_get_validation_error():
def test_get_http_error():
response = client.get("/items/3")
- assert response.status_code == 418
+ assert response.status_code == 418, response.text
assert response.content == b"Nope! I don't like 3."
def test_get():
response = client.get("/items/2")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": 2}
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial005.py b/tests/test_tutorial/test_handling_errors/test_tutorial005.py
index f62c05ae5f233..f974466d15979 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial005.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial005.py
@@ -82,13 +82,13 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_post_validation_error():
response = client.post("/items/", json={"title": "towel", "size": "XL"})
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
@@ -104,5 +104,5 @@ def test_post_validation_error():
def test_post():
data = {"title": "towel", "size": 5}
response = client.post("/items/", json=data)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == data
diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial006.py b/tests/test_tutorial/test_handling_errors/test_tutorial006.py
index 87d9df4e17706..2b945fe908ac3 100644
--- a/tests/test_tutorial/test_handling_errors/test_tutorial006.py
+++ b/tests/test_tutorial/test_handling_errors/test_tutorial006.py
@@ -73,13 +73,13 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get_validation_error():
response = client.get("/items/foo")
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
@@ -93,11 +93,11 @@ def test_get_validation_error():
def test_get_http_error():
response = client.get("/items/3")
- assert response.status_code == 418
+ assert response.status_code == 418, response.text
assert response.json() == {"detail": "Nope! I don't like 3."}
def test_get():
response = client.get("/items/2")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": 2}
diff --git a/tests/test_tutorial/test_metadata/__init__.py b/tests/test_tutorial/test_metadata/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/tests/test_tutorial/test_application_configuration/test_tutorial001.py b/tests/test_tutorial/test_metadata/test_tutorial001.py
similarity index 86%
rename from tests/test_tutorial/test_application_configuration/test_tutorial001.py
rename to tests/test_tutorial/test_metadata/test_tutorial001.py
index 40c545e0357ec..5f00d39570af0 100644
--- a/tests/test_tutorial/test_application_configuration/test_tutorial001.py
+++ b/tests/test_tutorial/test_metadata/test_tutorial001.py
@@ -1,6 +1,6 @@
from fastapi.testclient import TestClient
-from application_configuration.tutorial001 import app
+from metadata.tutorial001 import app
client = TestClient(app)
@@ -30,11 +30,11 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_items():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"name": "Foo"}]
diff --git a/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py b/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py
index 8340542f6fd52..337e703d20910 100644
--- a/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py
+++ b/tests/test_tutorial/test_openapi_callbacks/test_tutorial001.py
@@ -165,7 +165,7 @@ def test_get():
response = client.post(
"/invoices/", json={"id": "fooinvoice", "customer": "John", "total": 5.3}
)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"msg": "Invoice received"}
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py
index 9ec8bf2e9fc37..ca94ff1f14290 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial001.py
@@ -26,11 +26,11 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "Foo"}]
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py
index 036ea138a7fec..1aa001ad4f4e9 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial002.py
@@ -26,11 +26,11 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "Foo"}]
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py
index f5c26c767ab0b..16559a33e7cf2 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial003.py
@@ -13,11 +13,11 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_get():
response = client.get("/items/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == [{"item_id": "Foo"}]
diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py
index 099710e926015..f092703dfb783 100644
--- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py
+++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py
@@ -96,13 +96,13 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_query_params_str_validations():
response = client.post("/items/", json={"name": "Foo", "price": 42})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {
"name": "Foo",
"price": 42,
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
index b78263c8e6643..107fae09c29a7 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
@@ -96,13 +96,13 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_query_params_str_validations():
response = client.post("/items/", json={"name": "Foo", "price": 42})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {
"name": "Foo",
"price": 42,
diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
index 5534cb5709b2c..bfcd4541183b9 100644
--- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
+++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
@@ -55,7 +55,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_tutorial/test_path_params/test_tutorial004.py b/tests/test_tutorial/test_path_params/test_tutorial004.py
index a7004b91ad988..a3343744f524e 100644
--- a/tests/test_tutorial/test_path_params/test_tutorial004.py
+++ b/tests/test_tutorial/test_path_params/test_tutorial004.py
@@ -26,8 +26,8 @@
},
},
},
- "summary": "Read User Me",
- "operationId": "read_user_me_files__file_path__get",
+ "summary": "Read File",
+ "operationId": "read_file_files__file_path__get",
"parameters": [
{
"required": True,
@@ -73,19 +73,19 @@
def test_openapi():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_file_path():
response = client.get("/files/home/johndoe/myfile.txt")
print(response.content)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"file_path": "home/johndoe/myfile.txt"}
def test_root_file_path():
response = client.get("/files//home/johndoe/myfile.txt")
print(response.content)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"file_path": "/home/johndoe/myfile.txt"}
diff --git a/tests/test_tutorial/test_path_params/test_tutorial005.py b/tests/test_tutorial/test_path_params/test_tutorial005.py
index b7eac1fd25ba3..836a6264b22bc 100644
--- a/tests/test_tutorial/test_path_params/test_tutorial005.py
+++ b/tests/test_tutorial/test_path_params/test_tutorial005.py
@@ -76,10 +76,84 @@
}
+openapi_schema2 = {
+ "openapi": "3.0.2",
+ "info": {"title": "FastAPI", "version": "0.1.0"},
+ "paths": {
+ "/model/{model_name}": {
+ "get": {
+ "summary": "Get Model",
+ "operationId": "get_model_model__model_name__get",
+ "parameters": [
+ {
+ "required": True,
+ "schema": {"$ref": "#/components/schemas/ModelName"},
+ "name": "model_name",
+ "in": "path",
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {"application/json": {"schema": {}}},
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ },
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/ValidationError"},
+ }
+ },
+ },
+ "ModelName": {
+ "title": "ModelName",
+ "enum": ["alexnet", "resnet", "lenet"],
+ "type": "string",
+ "description": "An enumeration.",
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": ["loc", "msg", "type"],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {"type": "string"},
+ },
+ "msg": {"title": "Message", "type": "string"},
+ "type": {"title": "Error Type", "type": "string"},
+ },
+ },
+ }
+ },
+}
+
+
def test_openapi():
response = client.get("/openapi.json")
- assert response.status_code == 200
- assert response.json() == openapi_schema
+ assert response.status_code == 200, response.text
+ data = response.json()
+ assert data == openapi_schema or data == openapi_schema2
@pytest.mark.parametrize(
diff --git a/tests/test_tutorial/test_query_params/test_tutorial007.py b/tests/test_tutorial/test_query_params/test_tutorial007.py
index 3dc4f1803c5dc..335c103a15a15 100644
--- a/tests/test_tutorial/test_query_params/test_tutorial007.py
+++ b/tests/test_tutorial/test_query_params/test_tutorial007.py
@@ -79,17 +79,17 @@
def test_openapi():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_read_item():
response = client.get("/items/foo")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo", "limit": None}
def test_read_item_query():
response = client.get("/items/foo?limit=5")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"item_id": "foo", "limit": 5}
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py
index cce30d8a002fd..8bdba00b771fb 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial001.py
@@ -83,7 +83,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
index a498bca824a6a..fb37f4be211ca 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
@@ -77,19 +77,19 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_multi_query_values():
url = "/items/?q=foo&q=bar"
response = client.get(url)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"q": ["foo", "bar"]}
def test_query_no_values():
url = "/items/"
response = client.get(url)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"q": None}
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
index f7fcfe5e24cda..c05d8ac217082 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
@@ -78,19 +78,19 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_default_query_values():
url = "/items/"
response = client.get(url)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"q": ["foo", "bar"]}
def test_multi_query_values():
url = "/items/?q=baz&q=foobar"
response = client.get(url)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"q": ["baz", "foobar"]}
diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
index d645c4a697aa2..7b1eab2b7def2 100644
--- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
+++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
@@ -73,19 +73,19 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
def test_multi_query_values():
url = "/items/?q=foo&q=bar"
response = client.get(url)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"q": ["foo", "bar"]}
def test_query_no_values():
url = "/items/"
response = client.get(url)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"q": None}
diff --git a/tests/test_tutorial/test_request_files/test_tutorial001.py b/tests/test_tutorial/test_request_files/test_tutorial001.py
index fdf4eb25455df..9aea331f32a37 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial001.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial001.py
@@ -125,7 +125,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
@@ -142,13 +142,13 @@ def test_openapi_schema():
def test_post_form_no_body():
response = client.post("/files/")
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == file_required
def test_post_body_json():
response = client.post("/files/", json={"file": "Foo"})
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == file_required
@@ -159,7 +159,7 @@ def test_post_file(tmpdir):
client = TestClient(app)
response = client.post("/files/", files={"file": open(path, "rb")})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"file_size": 14}
@@ -171,7 +171,7 @@ def test_post_large_file(tmpdir):
client = TestClient(app)
response = client.post("/files/", files={"file": open(path, "rb")})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"file_size": default_pydantic_max_size + 1}
@@ -182,5 +182,5 @@ def test_post_upload_file(tmpdir):
client = TestClient(app)
response = client.post("/uploadfile/", files={"file": open(path, "rb")})
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"filename": "test.txt"}
diff --git a/tests/test_tutorial/test_request_files/test_tutorial002.py b/tests/test_tutorial/test_request_files/test_tutorial002.py
index 811e0f1c730e5..24e9eae2f5b9e 100644
--- a/tests/test_tutorial/test_request_files/test_tutorial002.py
+++ b/tests/test_tutorial/test_request_files/test_tutorial002.py
@@ -145,7 +145,7 @@
def test_openapi_schema():
response = client.get("/openapi.json")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == openapi_schema
@@ -162,13 +162,13 @@ def test_openapi_schema():
def test_post_form_no_body():
response = client.post("/files/")
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == file_required
def test_post_body_json():
response = client.post("/files/", json={"file": "Foo"})
- assert response.status_code == 422
+ assert response.status_code == 422, response.text
assert response.json() == file_required
@@ -188,7 +188,7 @@ def test_post_files(tmpdir):
("files", ("test2.txt", open(path2, "rb"))),
),
)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"file_sizes": [14, 15]}
@@ -208,12 +208,12 @@ def test_post_upload_file(tmpdir):
("files", ("test2.txt", open(path2, "rb"))),
),
)
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert response.json() == {"filenames": ["test.txt", "test2.txt"]}
def test_get_root():
client = TestClient(app)
response = client.get("/")
- assert response.status_code == 200
+ assert response.status_code == 200, response.text
assert b"