diff --git a/.env b/.env new file mode 100644 index 0000000000000..7032423628aa4 --- /dev/null +++ b/.env @@ -0,0 +1 @@ +PYTHONPATH=./docs_src diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000000000..0ffc101a3f235 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [tiangolo] diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index d64ca6b4027c7..0000000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: "[BUG]" -labels: bug -assignees: '' - ---- - -### Describe the bug - -Write here a clear and concise description of what the bug is. - -### To Reproduce - -Steps to reproduce the behavior with a minimum self-contained file. - -Replace each part with your own scenario: - -1. Create a file with: - -```Python -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/") -def read_root(): - return {"Hello": "World"} -``` - -3. Open the browser and call the endpoint `/`. -4. It returns a JSON with `{"Hello": "World"}`. -5. But I expected it to return `{"Hello": "Sara"}`. - -### Expected behavior - -Add a clear and concise description of what you expected to happen. - -### Screenshots - -If applicable, add screenshots to help explain your problem. - -### Environment - -- OS: [e.g. Linux / Windows / macOS] -- FastAPI Version [e.g. 0.3.0], get it with: - -```bash -python -c "import fastapi; print(fastapi.__version__)" -``` - -- Python version, get it with: - -```bash -python --version -``` - -### Additional context - -Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 15b94028ec9ec..75c02cc1fd5f6 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,26 +1,104 @@ --- name: Feature request about: Suggest an idea for this project -title: "[FEATURE]" +title: "" labels: enhancement assignees: '' --- -### Is your feature request related to a problem +### First check -Is your feature request related to a problem? +* [ ] I added a very descriptive title to this issue. +* [ ] I used the GitHub search to find a similar issue and didn't find it. +* [ ] I searched the FastAPI documentation, with the integrated search. +* [ ] I already searched in Google "How to X in FastAPI" and didn't find any information. +* [ ] I already read and followed all the tutorial in the docs and didn't find an answer. +* [ ] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic). +* [ ] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui). +* [ ] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc). +* [ ] After submitting this, I commit to: + * Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there. + * Or, I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future. + * Implement a Pull Request for a confirmed bug. -Add a clear and concise description of what the problem is. Ex. I want to be able to [...] but I can't because [...] + + +### Example + +Here's a self-contained [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with my use case: + + + +```Python +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} +``` + +### Description + + + +* Open the browser and call the endpoint `/`. +* It returns a JSON with `{"Hello": "World"}`. +* I would like it to have an extra parameter to teleport me to the moon and back. ### The solution you would like -Add a clear and concise description of what you want to happen. + + +I would like it to have a `teleport_to_moon` parameter that defaults to `False`, and can be set to `True` to teleport me: + +```Python +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/", teleport_to_moon=True) +def read_root(): + return {"Hello": "World"} +``` ### Describe alternatives you've considered -Add a clear and concise description of any alternative solutions or features you've considered. + + +To wait for Space X moon travel plans to drop down long after they release them. But I would rather teleport. + +### Environment + +* OS: [e.g. Linux / Windows / macOS]: +* FastAPI Version [e.g. 0.3.0]: + +To know the FastAPI version use: + +```bash +python -c "import fastapi; print(fastapi.__version__)" +``` + +* Python version: + +To know the Python version use: + +```bash +python --version +``` ### Additional context -Add any other context or screenshots about the feature request here. + diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md index cc91b23395460..c4953891630ec 100644 --- a/.github/ISSUE_TEMPLATE/question.md +++ b/.github/ISSUE_TEMPLATE/question.md @@ -1,24 +1,81 @@ --- -name: Question -about: Ask a question -title: "[QUESTION]" +name: Question or Problem +about: Ask a question or ask about a problem +title: "" labels: question -assignees: '' +assignees: "" --- ### First check +* [ ] I added a very descriptive title to this issue. * [ ] I used the GitHub search to find a similar issue and didn't find it. * [ ] I searched the FastAPI documentation, with the integrated search. * [ ] I already searched in Google "How to X in FastAPI" and didn't find any information. +* [ ] I already read and followed all the tutorial in the docs and didn't find an answer. +* [ ] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic). +* [ ] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui). +* [ ] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc). +* [ ] After submitting this, I commit to one of: + * Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there. + * I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future. + * Implement a Pull Request for a confirmed bug. + + + +### Example + +Here's a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with my use case: + + + +```Python +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} +``` ### Description -How can I [...]? + + +* Open the browser and call the endpoint `/`. +* It returns a JSON with `{"Hello": "World"}`. +* But I expected it to return `{"Hello": "Sara"}`. + +### Environment + +* OS: [e.g. Linux / Windows / macOS]: +* FastAPI Version [e.g. 0.3.0]: + +To know the FastAPI version use: + +```bash +python -c "import fastapi; print(fastapi.__version__)" +``` + +* Python version: + +To know the Python version use: -Is it possible to [...]? +```bash +python --version +``` ### Additional context -Add any other context or screenshots about the feature request here. + diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 77f1c274c1adc..60f8e4b4ae4ef 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -16,8 +16,8 @@ jobs: run: python3.7 -m pip install flit - name: Install docs extras run: python3.7 -m flit install --extras doc - - name: Build MkDocs - run: python3.7 -m mkdocs build + - name: Build Docs + run: python3.7 ./scripts/docs.py build-all - name: Deploy to Netlify uses: nwtgck/actions-netlify@v1.0.3 with: diff --git a/.github/workflows/main.yml b/.github/workflows/issue-manager.yml similarity index 60% rename from .github/workflows/main.yml rename to .github/workflows/issue-manager.yml index 5e0a496842b47..712930e0ba320 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/issue-manager.yml @@ -1,15 +1,24 @@ +name: Issue Manager + on: schedule: - - cron: "0 0 * * *" + - cron: "0 0 * * *" + issue_comment: + types: + - created + - edited + issues: + types: + - labeled jobs: issue-manager: runs-on: ubuntu-latest steps: - - uses: tiangolo/issue-manager@master - with: - token: ${{ secrets.GITHUB_TOKEN }} - config: > + - uses: tiangolo/issue-manager@0.2.0 + with: + token: ${{ secrets.GITHUB_TOKEN }} + config: > { "answered": { "users": ["tiangolo", "dmontagu"], diff --git a/.gitignore b/.gitignore index f110dc59725eb..505c67b88c6f4 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,5 @@ test.db log.txt Pipfile.lock env3.* +env +docs_build diff --git a/README.md b/README.md index 8801c1af57b63..b74421fa9d5aa 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Build Status - Coverage + Coverage Package version @@ -33,7 +33,7 @@ The key features are: * **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). -* **Fast to code**: Increase the speed to develop features by about 200% to 300% *. +* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * * **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * * **Intuitive**: Great editor support. Completion everywhere. Less time debugging. * **Easy**: Designed to be easy to use and learn. Less time reading docs. @@ -45,37 +45,51 @@ The key features are: ## Opinions -"*[...] 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.*" +"_[...] 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)
--- -"*I’m over the moon excited about **FastAPI**. It’s so fun!*" +"_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!_"
Brian Okken - Python Bytes podcast host (ref)
--- -"*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.*" +"_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._"
Timothy Crosley - Hug creator (ref)
--- -"*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 [...]*" +"_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 [...]*" +"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
--- -"*We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]*" +## **Typer**, the FastAPI of CLIs -
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ ---- +If you are building a CLI app to be used in the terminal instead of a web API, check out **Typer**. + +**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀 ## Requirements @@ -88,16 +102,28 @@ FastAPI stands on the shoulders of giants: ## Installation -```bash -pip install fastapi +
+ +```console +$ pip install fastapi + +---> 100% ``` +
+ You will also need an ASGI server, for production such as Uvicorn or Hypercorn. -```bash -pip install uvicorn +
+ +```console +$ pip install uvicorn + +---> 100% ``` +
+ ## Example ### Create it @@ -151,10 +177,20 @@ If you don't know, check the _"In a hurry?"_ section about + +```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. ``` + +
About the command uvicorn main:app --reload... diff --git a/docs/advanced/sub-applications-proxy.md b/docs/advanced/sub-applications-proxy.md deleted file mode 100644 index e75a4e9d3aaf8..0000000000000 --- a/docs/advanced/sub-applications-proxy.md +++ /dev/null @@ -1,92 +0,0 @@ -There are at least two situations where you could need to create your **FastAPI** application using some specific paths. - -But then you need to set them up to be served with a path prefix. - -It could happen if you have a: - -* **Proxy** server. -* You are "**mounting**" a FastAPI application inside another FastAPI application (or inside another ASGI application, like Starlette). - -## Proxy - -Having a proxy in this case means that you could declare a path at `/app`, but then, you could need to add a layer on top (the Proxy) that would put your **FastAPI** application under a path like `/api/v1`. - -In this case, the original path `/app` will actually be served at `/api/v1/app`. - -Even though your application "thinks" it is serving at `/app`. - -And the Proxy could be re-writing the path "on the fly" to keep your application convinced that it is serving at `/app`. - -Up to here, everything would work as normally. - -But then, when you open the integrated docs, they would expect to get the OpenAPI schema at `/openapi.json`, instead of `/api/v1/openapi.json`. - -So, the frontend (that runs in the browser) would try to reach `/openapi.json` and wouldn't be able to get the OpenAPI schema. - -So, it's needed that the frontend looks for the OpenAPI schema at `/api/v1/openapi.json`. - -And it's also needed that the returned JSON OpenAPI schema has the defined path at `/api/v1/app` (behind the proxy) instead of `/app`. - ---- - -For these cases, you can declare an `openapi_prefix` parameter in your `FastAPI` application. - -See the section below, about "mounting", for an example. - -## Mounting a **FastAPI** application - -"Mounting" means adding a complete "independent" application in a specific path, that then takes care of handling all the sub-paths. - -You could want to do this if you have several "independent" applications that you want to separate, having their own independent OpenAPI schema and user interfaces. - -### Top-level application - -First, create the main, top-level, **FastAPI** application, and its *path operations*: - -```Python hl_lines="3 6 7 8" -{!./src/sub_applications/tutorial001.py!} -``` - -### Sub-application - -Then, create your sub-application, and its *path operations*. - -This sub-application is just another standard FastAPI application, but this is the one that will be "mounted". - -When creating the sub-application, use the parameter `openapi_prefix`. In this case, with a prefix of `/subapi`: - -```Python hl_lines="11 14 15 16" -{!./src/sub_applications/tutorial001.py!} -``` - -### Mount the sub-application - -In your top-level application, `app`, mount the sub-application, `subapi`. - -Here you need to make sure you use the same path that you used for the `openapi_prefix`, in this case, `/subapi`: - -```Python hl_lines="11 19" -{!./src/sub_applications/tutorial001.py!} -``` - -## Check the automatic API docs - -Now, run `uvicorn`, if your file is at `main.py`, it would be: - -```bash -uvicorn main:app --reload -``` - -And open the docs at http://127.0.0.1:8000/docs. - -You will see the automatic API docs for the main app, including only its own paths: - - - -And then, open the docs for the sub-application, at http://127.0.0.1:8000/subapi/docs. - -You will see the automatic API docs for the sub-application, including only its own sub-paths, with their correct prefix: - - - -If you try interacting with any of the two user interfaces, they will work, because the browser will be able to talk to the correct path (or sub-path). diff --git a/docs/contributing.md b/docs/contributing.md deleted file mode 100644 index 9cf663605bc85..0000000000000 --- a/docs/contributing.md +++ /dev/null @@ -1,175 +0,0 @@ -First, you might want to see the basic ways to [help FastAPI and get help](help-fastapi.md){.internal-link target=_blank}. - -## Developing - -If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment. - -### Virtual environment with `venv` - -You can create a virtual environment in a directory using Python's `venv` module: - -```console -$ python -m venv env -``` - -That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment. - -### Activate the environment - -Activate the new environment with: - -```console -$ source ./env/bin/activate -``` - -Or in Windows' PowerShell: - -```console -$ .\env\Scripts\Activate.ps1 -``` - -Or if you use Bash for Windows (e.g. Git Bash): - -```console -$ source ./env/Scripts/activate -``` - -To check it worked, use: - -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 - -Or in Windows PowerShell: - -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` -!!! tip - Every time you install a new package with `pip` under that environment, activate the environment again. - - This makes sure that if you use a terminal program installed by that package (like `flit`), you use the one from your local environment and not any other that could be installed globally. - -### Flit - -**FastAPI** uses Flit to build, package and publish the project. - -After activating the environment as described above, install `flit`: - -```console -$ pip install flit -``` - -Now re-activate the environment to make sure you are using the `flit` you just installed (and not a global one). - -And now use `flit` to install the development dependencies: - -```console -$ flit install --deps develop --symlink -``` - -It will install all the dependencies and your local FastAPI in your local environment. - -#### Using your local FastAPI - -If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code. - -And if you update that local FastAPI source code, as it is installed with `--symlink`, when you run that Python file again, it will use the fresh version of FastAPI you just edited. - -That way, you don't have to "install" your local version to be able to test every change. - -### Format - -There is a script that you can run that will format and clean all your code: - -```console -$ bash scripts/format.sh -``` - -It will also auto-sort all your imports. - -For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above: - -```console -$ flit install --symlink -``` - -### Format imports - -There is another script that formats all the imports and makes sure you don't have unused imports: - -```console -$ bash scripts/format-imports.sh -``` - -As it runs one command after the other and modifies and reverts many files, it takes a bit longer to run, so it might be easier to use `scripts/format.sh` frequently and `scripts/format-imports.sh` only before committing. - -## Docs - -The documentation uses MkDocs. - -All the documentation is in Markdown format in the directory `./docs`. - -Many of the tutorials have blocks of code. - -In most of the cases, these blocks of code are actual complete applications that can be run as is. - -In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs/src/` directory. - -And those Python files are included/injected in the documentation when generating the site. - -### Docs for tests - -Most of the tests actually run against the example source files in the documentation. - -This helps making sure that: - -* The documentation is up to date. -* The documentation examples can be run as is. -* Most of the features are covered by the documentation, ensured by test coverage. - -During local development, there is a script that builds the site and checks for any changes, live-reloading: - -```console -$ bash scripts/docs-live.sh -``` - -It will serve the documentation on `http://0.0.0.0:8008`. - -That way, you can edit the documentation/source files and see the changes live. - -### Apps and docs at the same time - -If you run the examples with, e.g.: - -```console -$ uvicorn tutorial001:app --reload -``` - -as Uvicorn by default will use the port `8000`, the documentation on port `8008` won't clash. - -## Tests - -There is a script that you can run locally to test all the code and generate coverage reports in HTML: - -```console -$ bash scripts/test-cov-html.sh -``` - -This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. - -### Tests in your editor - -If you want to use the integrated tests in your editor add `./docs/src` to your `PYTHONPATH` variable. - -For example, in VS Code you can create a file `.env` with: - -```env -PYTHONPATH=./docs/src -``` diff --git a/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md similarity index 97% rename from docs/advanced/additional-responses.md rename to docs/en/docs/advanced/additional-responses.md index 71c4cf61d279a..4b2abaada3109 100644 --- a/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -1,3 +1,5 @@ +# Additional Responses in OpenAPI + !!! warning This is a rather advanced topic. @@ -22,7 +24,7 @@ Each of those response `dict`s can have a key `model`, containing a Pydantic mod For example, to declare another response with a status code `404` and a Pydantic model `Message`, you can write: ```Python hl_lines="18 23" -{!./src/additional_responses/tutorial001.py!} +{!../../../docs_src/additional_responses/tutorial001.py!} ``` !!! note @@ -167,7 +169,7 @@ You can use this same `responses` parameter to add different media types for the For example, you can add an additional media type of `image/png`, declaring that your *path operation* can return a JSON object (with media type `application/json`) or a PNG image: ```Python hl_lines="17 18 19 20 21 22 23 24 28" -{!./src/additional_responses/tutorial002.py!} +{!../../../docs_src/additional_responses/tutorial002.py!} ``` !!! note @@ -191,7 +193,7 @@ For example, you can declare a response with a status code `404` that uses a Pyd And a response with a status code `200` that uses your `response_model`, but includes a custom `example`: ```Python hl_lines="20 21 22 23 24 25 26 27 28 29 30 31" -{!./src/additional_responses/tutorial003.py!} +{!../../../docs_src/additional_responses/tutorial003.py!} ``` It will all be combined and included in your OpenAPI, and shown in the API docs: @@ -227,7 +229,7 @@ You can use that technique to re-use some predefined responses in your *path ope For example: ```Python hl_lines="11 12 13 14 15 24" -{!./src/additional_responses/tutorial004.py!} +{!../../../docs_src/additional_responses/tutorial004.py!} ``` ## More information about OpenAPI responses diff --git a/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md similarity index 95% rename from docs/advanced/additional-status-codes.md rename to docs/en/docs/advanced/additional-status-codes.md index 14a867c989c88..b9a32cfa3b661 100644 --- a/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -1,3 +1,5 @@ +# Additional Status Codes + By default, **FastAPI** will return the responses using a `JSONResponse`, putting the content you return from your *path operation* inside of that `JSONResponse`. It will use the default status code or the one you set in your *path operation*. @@ -13,7 +15,7 @@ But you also want it to accept new items. And when the items didn't exist before To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want: ```Python hl_lines="2 19" -{!./src/additional_status_codes/tutorial001.py!} +{!../../../docs_src/additional_status_codes/tutorial001.py!} ``` !!! warning diff --git a/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md similarity index 91% rename from docs/advanced/advanced-dependencies.md rename to docs/en/docs/advanced/advanced-dependencies.md index ec796362a847d..5e79776cacddd 100644 --- a/docs/advanced/advanced-dependencies.md +++ b/docs/en/docs/advanced/advanced-dependencies.md @@ -1,3 +1,5 @@ +# Advanced Dependencies + ## Parameterized dependencies All the dependencies we have seen are a fixed function or class. @@ -17,7 +19,7 @@ Not the class itself (which is already a callable), but an instance of that clas To do that, we declare a method `__call__`: ```Python hl_lines="10" -{!./src/dependencies/tutorial011.py!} +{!../../../docs_src/dependencies/tutorial011.py!} ``` In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later. @@ -27,7 +29,7 @@ In this case, this `__call__` is what **FastAPI** will use to check for addition And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency: ```Python hl_lines="7" -{!./src/dependencies/tutorial011.py!} +{!../../../docs_src/dependencies/tutorial011.py!} ``` In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code. @@ -37,7 +39,7 @@ In this case, **FastAPI** won't ever touch or care about `__init__`, we will use We could create an instance of this class with: ```Python hl_lines="16" -{!./src/dependencies/tutorial011.py!} +{!../../../docs_src/dependencies/tutorial011.py!} ``` And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`. @@ -55,7 +57,7 @@ checker(q="somequery") ...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`: ```Python hl_lines="20" -{!./src/dependencies/tutorial011.py!} +{!../../../docs_src/dependencies/tutorial011.py!} ``` !!! tip diff --git a/docs/advanced/async-sql-databases.md b/docs/en/docs/advanced/async-sql-databases.md similarity index 90% rename from docs/advanced/async-sql-databases.md rename to docs/en/docs/advanced/async-sql-databases.md index c7d0b86dff3ed..523bc91bf4726 100644 --- a/docs/advanced/async-sql-databases.md +++ b/docs/en/docs/advanced/async-sql-databases.md @@ -1,3 +1,5 @@ +# Async SQL (Relational) Databases + You can also use `encode/databases` with **FastAPI** to connect to databases using `async` and `await`. It is compatible with: @@ -22,7 +24,7 @@ Later, for your production application, you might want to use a database server * Create a table `notes` using the `metadata` object. ```Python hl_lines="4 14 16 17 18 19 20 21 22" -{!./src/async_sql_databases/tutorial001.py!} +{!../../../docs_src/async_sql_databases/tutorial001.py!} ``` !!! tip @@ -37,7 +39,7 @@ Later, for your production application, you might want to use a database server * Create a `database` object. ```Python hl_lines="3 9 12" -{!./src/async_sql_databases/tutorial001.py!} +{!../../../docs_src/async_sql_databases/tutorial001.py!} ``` !!! tip @@ -53,7 +55,7 @@ Here, this section would run directly, right before starting your **FastAPI** ap * Create all the tables from the `metadata` object. ```Python hl_lines="25 26 27 28" -{!./src/async_sql_databases/tutorial001.py!} +{!../../../docs_src/async_sql_databases/tutorial001.py!} ``` ## Create models @@ -64,7 +66,7 @@ Create Pydantic models for: * Notes to be returned (`Note`). ```Python hl_lines="31 32 33 36 37 38 39" -{!./src/async_sql_databases/tutorial001.py!} +{!../../../docs_src/async_sql_databases/tutorial001.py!} ``` By creating these Pydantic models, the input data will be validated, serialized (converted), and annotated (documented). @@ -77,7 +79,7 @@ So, you will be able to see it all in the interactive API docs. * Create event handlers to connect and disconnect from the database. ```Python hl_lines="42 45 46 47 50 51 52" -{!./src/async_sql_databases/tutorial001.py!} +{!../../../docs_src/async_sql_databases/tutorial001.py!} ``` ## Read notes @@ -85,7 +87,7 @@ So, you will be able to see it all in the interactive API docs. Create the *path operation function* to read notes: ```Python hl_lines="55 56 57 58" -{!./src/async_sql_databases/tutorial001.py!} +{!../../../docs_src/async_sql_databases/tutorial001.py!} ``` !!! Note @@ -102,7 +104,7 @@ That documents (and validates, serializes, filters) the output data, as a `list` Create the *path operation function* to create notes: ```Python hl_lines="61 62 63 64 65" -{!./src/async_sql_databases/tutorial001.py!} +{!../../../docs_src/async_sql_databases/tutorial001.py!} ``` !!! Note diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md new file mode 100644 index 0000000000000..660e374a43019 --- /dev/null +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -0,0 +1,281 @@ +# Behind a Proxy + +In some situations, you might need to use a **proxy** server like Traefik or Nginx with a configuration that adds an extra path prefix that is not seen by your application. + +In these cases you can use `root_path` to configure your application. + +The `root_path` is a mechanism provided by the ASGI specification (that FastAPI is built on, through Starlette). + +The `root_path` is used to handle these specific cases. + +And it's also used internally when mounting sub-applications. + +## Proxy with a stripped path prefix + +Having a proxy with a stripped path prefix, in this case, means that you could declare a path at `/app` in your code, but then, you add a layer on top (the proxy) that would put your **FastAPI** application under a path like `/api/v1`. + +In this case, the original path `/app` would actually be served at `/api/v1/app`. + +Even though all your code is written assuming there's just `/app`. + +And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to Uvicorn, keep your application convinced that it is serving at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`. + +Up to here, everything would work as normally. + +But then, when you open the integrated docs UI (the frontend), it would expect to get the OpenAPI schema at `/openapi.json`, instead of `/api/v1/openapi.json`. + +So, the frontend (that runs in the browser) would try to reach `/openapi.json` and wouldn't be able to get the OpenAPI schema. + +Because we have a proxy with a path prefix of `/api/v1` for our app, the frontend needs to fetch the OpenAPI schema at `/api/v1/openapi.json`. + +```mermaid +graph LR + +browser("Browser") +proxy["Proxy on http://0.0.0.0:9999/api/v1/app"] +server["Server on http://127.0.0.1:8000/app"] + +browser --> proxy +proxy --> server +``` + +!!! tip + The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server. + +The docs UI would also need that the JSON payload with the OpenAPI schema has the path defined as `/api/v1/app` (behind the proxy) instead of `/app`. For example, something like: + +```JSON hl_lines="5" +{ + "openapi": "3.0.2", + // More stuff here + "paths": { + "/api/v1/app": { + // More stuff here + } + } +} +``` + +In this example, the "Proxy" could be something like **Traefik**. And the server would be something like **Uvicorn**, running your FastAPI application. + +### Providing the `root_path` + +To achieve this, you can use the command line option `--root-path` like: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +If you use Hypercorn, it also has the option `--root-path`. + +!!! note "Technical Details" + The ASGI specification defines a `root_path` for this use case. + + And the `--root-path` command line option provides that `root_path`. + +### Checking the current `root_path` + +You can get the current `root_path` used by your application for each request, it is part of the `scope` dictionary (that's part of the ASGI spec). + +Here we are including it in the message just for demonstration purposes. + +```Python hl_lines="8" +{!../../../docs_src/behind_a_proxy/tutorial001.py!} +``` + +Then, if you start Uvicorn with: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +The response would be something like: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +### Setting the `root_path` in the FastAPI app + +Alternatively, if you don't have a way to provide a command line option like `--root-path` or equivalent, you can set the `root_path` parameter when creating your FastAPI app: + +```Python hl_lines="3" +{!../../../docs_src/behind_a_proxy/tutorial002.py!} +``` + +Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn. + +### About `root_path` + +Have in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app. + +But if you go with your browser to http://127.0.0.1:8000/app you will see the normal response: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +So, it won't expect to be accessed at `http://127.0.0.1:8000/api/v1/app`. + +Uvicorn will expect the proxy to access Uvicorn at `http://127.0.0.1:8000/app`, and then it would be the proxy's responsibility to add the extra `/api/v1` prefix on top. + +## About proxies with a stripped path prefix + +Have in mind that a proxy with stripped path prefix is only one of the ways to configure it. + +Probably in many cases the default will be that the proxy doesn't have a stripped path prefix. + +In a case like that (without a stripped path prefix), the proxy would listen on something like `https://myawesomeapp.com`, and then if the browser goes to `https://myawesomeapp.com/api/v1/app` and your server (e.g. Uvicorn) listens on `http://127.0.0.1:8000` the proxy (without a stripped path prefix) would access Uvicorn at the same path: `http://127.0.0.1:8000/api/v1/app`. + +## Testing locally with Traefik + +You can easily run the experiment locally with a stripped path prefix using Traefik. + +Download Traefik, it's a single binary, you can extract the compressed file and run it directly from the terminal. + +Then create a file `traefik.toml` with: + +```TOML hl_lines="3" +[entryPoints] + [entryPoints.http] + address = ":9999" + +[providers] + [providers.file] + filename = "routes.toml" +``` + +This tells Traefik to listen on port 9999 and to use another file `routes.toml`. + +!!! tip + We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges. + +Now create that other file `routes.toml`: + +```TOML hl_lines="5 12 20" +[http] + [http.middlewares] + + [http.middlewares.api-stripprefix.stripPrefix] + prefixes = ["/api/v1"] + + [http.routers] + + [http.routers.app-http] + entryPoints = ["http"] + service = "app" + rule = "PathPrefix(`/api/v1`)" + middlewares = ["api-stripprefix"] + + [http.services] + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.app.loadBalancer.servers]] + url = "http://127.0.0.1:8000" +``` + +This file configures Traefik to use the path prefix `/api/v1`. + +And then it will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`. + +Now start Traefik: + +
+ +```console +$ ./traefik --configFile=traefik.toml + +INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml +``` + +
+ +And now start your app with Uvicorn, using the `--root-path` option: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Check the responses + +Now, if you go to the URL with the port for Uvicorn: http://127.0.0.1:8000/app, you will see the normal response: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +!!! tip + Notice that even though you are accessing it at `http://127.0.0.1:8000/app` it shows the `root_path` of `/api/v1`, taken from the option `--root-path`. + +And now open the URL with the port for Traefik, including the path prefix: http://127.0.0.1:9999/api/vi/app. + +We get the same response: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +but this time at the URL with the prefix path provided by the proxy: `/api/v1`. + +Of course, the idea here is that everyone would access the app through the proxy, so the version with the path prefix `/app/v1` is the "correct" one. + +And the version without the path prefix (`http://127.0.0.1:8000/app`), provided by Uvicorn directly, would be exclusively for the _proxy_ (Traefik) to access it. + +That demonstrates how the Proxy (Traefik) uses the path prefix and how the server (Uvicorn) uses the `root_path` from the option `--root-path`. + +### Check the docs UI + +But here's the fun part. ✨ + +The "official" way to access the app would be through the proxy with the path prefix that we defined. So, as we would expect, if you try the docs UI served by Uvicorn directly, without the path prefix in the URL, it won't work, because it expects to be accessed through the proxy. + +You can check it at http://127.0.0.1:8000/docs: + + + +But if we access the docs UI at the "official" URL using the proxy, at `/api/v1/docs`, it works correctly! 🎉 + +Right as we wanted it. ✔️ + +This is because FastAPI uses this `root_path` internally to tell the docs UI to use the URL for OpenAPI with the path prefix provided by `root_path`. + +You can check it at http://127.0.0.1:9999/api/v1/docs: + + + +## Mounting a sub-application + +If you need to mount a sub-application (as described in [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}) while also using a proxy with `root_path`, you can do it normally, as you would expect. + +FastAPI will internally use the `root_path` smartly, so it will just work. ✨ diff --git a/docs/en/docs/advanced/conditional-openapi.md b/docs/en/docs/advanced/conditional-openapi.md new file mode 100644 index 0000000000000..add16fbec519e --- /dev/null +++ b/docs/en/docs/advanced/conditional-openapi.md @@ -0,0 +1,58 @@ +# Conditional OpenAPI + +If you needed to, you could use settings and environment variables to configure OpenAPI conditionally depending on the environment, and even disable it entirely. + +## About security, APIs, and docs + +Hiding your documentation user interfaces in production *shouldn't* be the way to protect your API. + +That doesn't add any extra security to your API, the *path operations* will still be available where they are. + +If there's a security flaw in your code, it will still exist. + +Hiding the documentation just makes it more difficult to understand how to interact with your API, and could make it more difficult for you to debug it in production. It could be considered simply a form of Security through obscurity. + +If you want to secure your API, there are several better things you can do, for example: + +* Make sure you have well defined Pydantic models for your request bodies and responses. +* Configure any required permissions and roles using dependencies. +* Never store plaintext passwords, only password hashes. +* Implement and use well-known cryptographic tools, like Passlib and JWT tokens, etc. +* Add more granular permission controls with OAuth2 scopes where needed. +* ...etc. + +Nevertheless, you might have a very specific use case where you really need to disable the API docs for some environment (e.g. for production) or depending on configurations from environment variables. + +## Conditional OpenAPI from settings and env vars + +You can easily use the same Pydantic settings to configure your generated OpenAPI and the docs UIs. + +For example: + +```Python hl_lines="6 11" +{!../../../docs_src/conditional_openapi/tutorial001.py!} +``` + +Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`. + +And then we use it when creating the `FastAPI` app. + +Then you could disable OpenAPI (including the UI docs) by setting the environment variable `OPENAPI_URL` to the empty string, like: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Then if you go to the URLs at `/openapi.json`, `/docs`, or `/redoc` you will just get a `404 Not Found` error like: + +```JSON +{ + "detail": "Not Found" +} +``` diff --git a/docs/advanced/custom-request-and-route.md b/docs/en/docs/advanced/custom-request-and-route.md similarity index 91% rename from docs/advanced/custom-request-and-route.md rename to docs/en/docs/advanced/custom-request-and-route.md index 2e823143a74d9..6c5e97a18b003 100644 --- a/docs/advanced/custom-request-and-route.md +++ b/docs/en/docs/advanced/custom-request-and-route.md @@ -1,3 +1,5 @@ +# Custom Request and APIRoute class + In some cases, you may want to override the logic used by the `Request` and `APIRoute` classes. In particular, this may be a good alternative to logic in a middleware. @@ -35,7 +37,7 @@ If there's no `gzip` in the header, it will not try to decompress the body. That way, the same route class can handle gzip compressed or uncompressed requests. ```Python hl_lines="8 9 10 11 12 13 14 15" -{!./src/custom_request_and_route/tutorial001.py!} +{!../../../docs_src/custom_request_and_route/tutorial001.py!} ``` ### Create a custom `GzipRoute` class @@ -49,7 +51,7 @@ This method returns a function. And that function is what will receive a request Here we use it to create a `GzipRequest` from the original request. ```Python hl_lines="18 19 20 21 22 23 24 25 26" -{!./src/custom_request_and_route/tutorial001.py!} +{!../../../docs_src/custom_request_and_route/tutorial001.py!} ``` !!! note "Technical Details" @@ -83,13 +85,13 @@ We can also use this same approach to access the request body in an exception ha All we need to do is handle the request inside a `try`/`except` block: ```Python hl_lines="13 15" -{!./src/custom_request_and_route/tutorial002.py!} +{!../../../docs_src/custom_request_and_route/tutorial002.py!} ``` If an exception occurs, the`Request` instance will still be in scope, so we can read and make use of the request body when handling the error: ```Python hl_lines="16 17 18" -{!./src/custom_request_and_route/tutorial002.py!} +{!../../../docs_src/custom_request_and_route/tutorial002.py!} ``` ## Custom `APIRoute` class in a router @@ -97,11 +99,11 @@ If an exception occurs, the`Request` instance will still be in scope, so we can You can also set the `route_class` parameter of an `APIRouter`: ```Python hl_lines="26" -{!./src/custom_request_and_route/tutorial003.py!} +{!../../../docs_src/custom_request_and_route/tutorial003.py!} ``` In this example, the *path operations* under the `router` will use the custom `TimedRoute` class, and will have an extra `X-Response-Time` header in the response with the time it took to generate the response: ```Python hl_lines="13 14 15 16 17 18 19 20" -{!./src/custom_request_and_route/tutorial003.py!} +{!../../../docs_src/custom_request_and_route/tutorial003.py!} ``` diff --git a/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md similarity index 92% rename from docs/advanced/custom-response.md rename to docs/en/docs/advanced/custom-response.md index 21e7abee4bcb1..545a84436015c 100644 --- a/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -1,3 +1,5 @@ +# Custom Response - HTML, Stream, File, others + By default, **FastAPI** will return the responses using `JSONResponse`. You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}. @@ -20,7 +22,7 @@ For example, if you are squeezing performance, you can install and use + +```console +$ pip install aiofiles + +---> 100% ``` + + ### Serve the static files * Import `StaticFiles`. * "Mount" a `StaticFiles()` instance in a specific path. ```Python hl_lines="7 11" -{!./src/extending_openapi/tutorial002.py!} +{!../../../docs_src/extending_openapi/tutorial002.py!} ``` ### Test the static files @@ -199,7 +215,7 @@ The first step is to disable the automatic docs, as those use the CDN by default To disable them, set their URLs to `None` when creating your `FastAPI` app: ```Python hl_lines="9" -{!./src/extending_openapi/tutorial002.py!} +{!../../../docs_src/extending_openapi/tutorial002.py!} ``` ### Include the custom docs @@ -217,7 +233,7 @@ You can re-use FastAPI's internal functions to create the HTML pages for the doc And similarly for ReDoc... ```Python hl_lines="2 3 4 5 6 14 15 16 17 18 19 20 21 22 25 26 27 30 31 32 33 34 35 36" -{!./src/extending_openapi/tutorial002.py!} +{!../../../docs_src/extending_openapi/tutorial002.py!} ``` !!! tip @@ -232,7 +248,7 @@ And similarly for ReDoc... Now, to be able to test that everything works, create a *path operation*: ```Python hl_lines="39 40 41" -{!./src/extending_openapi/tutorial002.py!} +{!../../../docs_src/extending_openapi/tutorial002.py!} ``` ### Test it diff --git a/docs/advanced/graphql.md b/docs/en/docs/advanced/graphql.md similarity index 93% rename from docs/advanced/graphql.md rename to docs/en/docs/advanced/graphql.md index faeabf2d310b0..152754e9a543d 100644 --- a/docs/advanced/graphql.md +++ b/docs/en/docs/advanced/graphql.md @@ -1,3 +1,4 @@ +# GraphQL **FastAPI** has optional support for GraphQL (provided by Starlette directly), using the `graphene` library. @@ -10,7 +11,7 @@ GraphQL is implemented with Graphene, you can check NoSQL. Here we'll see an example using **Couchbase**, a document based NoSQL database. @@ -18,7 +20,7 @@ You can adapt it to any other NoSQL database like: For now, don't pay attention to the rest, only the imports: ```Python hl_lines="6 7 8" -{!./src/nosql_databases/tutorial001.py!} +{!../../../docs_src/nosql_databases/tutorial001.py!} ``` ## Define a constant to use as a "document type" @@ -28,7 +30,7 @@ We will use it later as a fixed field `type` in our documents. This is not required by Couchbase, but is a good practice that will help you afterwards. ```Python hl_lines="10" -{!./src/nosql_databases/tutorial001.py!} +{!../../../docs_src/nosql_databases/tutorial001.py!} ``` ## Add a function to get a `Bucket` @@ -53,7 +55,7 @@ This utility function will: * Return it. ```Python hl_lines="13 14 15 16 17 18 19 20 21 22" -{!./src/nosql_databases/tutorial001.py!} +{!../../../docs_src/nosql_databases/tutorial001.py!} ``` ## Create Pydantic models @@ -65,7 +67,7 @@ As **Couchbase** "documents" are actually just "JSON objects", we can model them First, let's create a `User` model: ```Python hl_lines="25 26 27 28 29" -{!./src/nosql_databases/tutorial001.py!} +{!../../../docs_src/nosql_databases/tutorial001.py!} ``` We will use this model in our *path operation function*, so, we don't include in it the `hashed_password`. @@ -79,7 +81,7 @@ This will have the data that is actually stored in the database. We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of our own `User`, because it will have all the attributes in `User` plus a couple more: ```Python hl_lines="32 33 34" -{!./src/nosql_databases/tutorial001.py!} +{!../../../docs_src/nosql_databases/tutorial001.py!} ``` !!! note @@ -99,7 +101,7 @@ Now create a function that will: By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily re-use it in multiple parts and also add unit tests for it: ```Python hl_lines="37 38 39 40 41 42 43" -{!./src/nosql_databases/tutorial001.py!} +{!../../../docs_src/nosql_databases/tutorial001.py!} ``` ### f-strings @@ -134,7 +136,7 @@ UserInDB(username="johndoe", hashed_password="some_hash") ### Create the `FastAPI` app ```Python hl_lines="47" -{!./src/nosql_databases/tutorial001.py!} +{!../../../docs_src/nosql_databases/tutorial001.py!} ``` ### Create the *path operation function* @@ -144,7 +146,7 @@ As our code is calling Couchbase and we are not using the threads", so, we can get just get the bucket directly and pass it to our utility functions: ```Python hl_lines="50 51 52 53 54" -{!./src/nosql_databases/tutorial001.py!} +{!../../../docs_src/nosql_databases/tutorial001.py!} ``` ## Recap diff --git a/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md similarity index 97% rename from docs/advanced/openapi-callbacks.md rename to docs/en/docs/advanced/openapi-callbacks.md index 8d3b0ac9e87d8..15c0ba2a1d45d 100644 --- a/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -1,3 +1,5 @@ +# OpenAPI Callbacks + You could create an API with a *path operation* that could trigger a request to an *external API* created by someone else (probably the same developer that would be *using* your API). The process that happens when your API app calls the *external API* is named a "callback". Because the software that the external developer wrote sends a request to your API and then your API *calls back*, sending a request to an *external API* (that was probably created by the same developer). @@ -30,7 +32,7 @@ It will have a *path operation* that will receive an `Invoice` body, and a query This part is pretty normal, most of the code is probably already familiar to you: ```Python hl_lines="8 9 10 11 12 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53" -{!./src/openapi_callbacks/tutorial001.py!} +{!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` !!! tip @@ -91,7 +93,7 @@ Because of that, you need to declare what will be the `default_response_class`, But as we are never calling `app.include_router(some_router)`, we need to set the `default_response_class` during creation of the `APIRouter`. ```Python hl_lines="3 24" -{!./src/openapi_callbacks/tutorial001.py!} +{!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### Create the callback *path operation* @@ -104,7 +106,7 @@ It should look just like a normal FastAPI *path operation*: * And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`. ```Python hl_lines="15 16 17 20 21 27 28 29 30 31" -{!./src/openapi_callbacks/tutorial001.py!} +{!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` There are 2 main differences from a normal *path operation*: @@ -171,7 +173,7 @@ At this point you have the *callback path operation(s)* needed (the one(s) that Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router: ```Python hl_lines="34" -{!./src/openapi_callbacks/tutorial001.py!} +{!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` !!! tip diff --git a/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md similarity index 82% rename from docs/advanced/path-operation-advanced-configuration.md rename to docs/en/docs/advanced/path-operation-advanced-configuration.md index eb5cc6a120075..7a3247a64ab4d 100644 --- a/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -1,3 +1,5 @@ +# Path Operation Advanced Configuration + ## OpenAPI operationId !!! warning @@ -8,7 +10,7 @@ You can set the OpenAPI `operationId` to be used in your *path operation* with t You would have to make sure that it is unique for each operation. ```Python hl_lines="6" -{!./src/path_operation_advanced_configuration/tutorial001.py!} +{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### Using the *path operation function* name as the operationId @@ -18,7 +20,7 @@ If you want to use your APIs' function names as `operationId`s, you can iterate You should do it after adding all your *path operations*. ```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!./src/path_operation_advanced_configuration/tutorial002.py!} +{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` !!! tip @@ -34,7 +36,7 @@ You should do it after adding all your *path operations*. To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`; ```Python hl_lines="6" -{!./src/path_operation_advanced_configuration/tutorial003.py!} +{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## Advanced description from docstring @@ -46,5 +48,5 @@ Adding an `\f` (an escaped "form feed" character) causes **FastAPI** to truncate It won't show up in the documentation, but other tools (such as Sphinx) will be able to use the rest. ```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!./src/path_operation_advanced_configuration/tutorial004.py!} +{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` diff --git a/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md similarity index 93% rename from docs/advanced/response-change-status-code.md rename to docs/en/docs/advanced/response-change-status-code.md index 1f10e12da9133..979cef3f05367 100644 --- a/docs/advanced/response-change-status-code.md +++ b/docs/en/docs/advanced/response-change-status-code.md @@ -1,3 +1,5 @@ +# Response - Change Status Code + You probably read before that you can set a default [Response Status Code](../tutorial/response-status-code.md){.internal-link target=_blank}. But in some cases you need to return a different status code than the default. @@ -19,7 +21,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set the `status_code` in that *temporal* response object. ```Python hl_lines="1 9 12" -{!./src/response_change_status_code/tutorial001.py!} +{!../../../docs_src/response_change_status_code/tutorial001.py!} ``` And then you can return any object you need, as you normally would (a `dict`, a database model, etc). diff --git a/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md similarity index 94% rename from docs/advanced/response-cookies.md rename to docs/en/docs/advanced/response-cookies.md index 8ce07bbf35c92..e46ae755f79d9 100644 --- a/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -1,3 +1,5 @@ +# Response Cookies + ## Use a `Response` parameter You can declare a parameter of type `Response` in your *path operation function*. @@ -5,7 +7,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set cookies in that *temporal* response object. ```Python hl_lines="1 8 9" -{!./src/response_cookies/tutorial002.py!} +{!../../../docs_src/response_cookies/tutorial002.py!} ``` And then you can return any object you need, as you normally would (a `dict`, a database model, etc). @@ -25,7 +27,7 @@ To do that, you can create a response as described in [Return a Response Directl Then set Cookies in it, and then return it: ```Python hl_lines="10 11 12" -{!./src/response_cookies/tutorial001.py!} +{!../../../docs_src/response_cookies/tutorial001.py!} ``` !!! tip diff --git a/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md similarity index 95% rename from docs/advanced/response-directly.md rename to docs/en/docs/advanced/response-directly.md index 1b123280878ef..f1dca1812b6d5 100644 --- a/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -1,3 +1,5 @@ +# Return a Response Directly + When you create a **FastAPI** *path operation* you can normally return any data from it: a `dict`, a `list`, a Pydantic model, a database model, etc. By default, **FastAPI** would automatically convert that return value to JSON using the `jsonable_encoder` explained in [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}. @@ -30,7 +32,7 @@ For example, you cannot put a Pydantic model in a `JSONResponse` without first c For those cases, you can use the `jsonable_encoder` to convert your data before passing it to a response: ```Python hl_lines="4 6 20 21" -{!./src/response_directly/tutorial001.py!} +{!../../../docs_src/response_directly/tutorial001.py!} ``` !!! note "Technical Details" @@ -49,7 +51,7 @@ Let's say that you want to return an `secrets` to check the username and password: ```Python hl_lines="1 11 12 13" -{!./src/security/tutorial007.py!} +{!../../../docs_src/security/tutorial007.py!} ``` This will ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. This would be similar to: @@ -101,5 +103,5 @@ That way, using `secrets.compare_digest()` in your application code, it will be After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again: ```Python hl_lines="15 16 17 18 19" -{!./src/security/tutorial007.py!} +{!../../../docs_src/security/tutorial007.py!} ``` diff --git a/docs/advanced/security/index.md b/docs/en/docs/advanced/security/index.md similarity index 95% rename from docs/advanced/security/index.md rename to docs/en/docs/advanced/security/index.md index 560af5a7cc58f..0c94986b5728e 100644 --- a/docs/advanced/security/index.md +++ b/docs/en/docs/advanced/security/index.md @@ -1,3 +1,5 @@ +# Advanced Security - Intro + ## Additional Features There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/){.internal-link target=_blank}. diff --git a/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md similarity index 97% rename from docs/advanced/security/oauth2-scopes.md rename to docs/en/docs/advanced/security/oauth2-scopes.md index 84c806bf888e4..a7842322137c9 100644 --- a/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -1,3 +1,5 @@ +# OAuth2 scopes + You can use OAuth2 scopes directly with **FastAPI**, they are integrated to work seamlessly. This would allow you to have a more fine-grained permission system, following the OAuth2 standard, integrated into your OpenAPI application (and the API docs). @@ -55,7 +57,7 @@ They are normally used to declare specific security permissions, for example: First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes: ```Python hl_lines="2 5 9 13 47 65 106 108 109 110 111 112 113 114 115 116 122 123 124 125 129 130 131 132 133 134 135 140 154" -{!./src/security/tutorial005.py!} +{!../../../docs_src/security/tutorial005.py!} ``` Now let's review those changes step by step. @@ -67,7 +69,7 @@ The first change is that now we are declaring the OAuth2 security scheme with tw The `scopes` parameter receives a `dict` with each scope as a key and the description as the value: ```Python hl_lines="63 64 65 66" -{!./src/security/tutorial005.py!} +{!../../../docs_src/security/tutorial005.py!} ``` Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize. @@ -92,7 +94,7 @@ And we return the scopes as part of the JWT token. But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined. ```Python hl_lines="155" -{!./src/security/tutorial005.py!} +{!../../../docs_src/security/tutorial005.py!} ``` ## Declare scopes in *path operations* and dependencies @@ -117,7 +119,7 @@ In this case, it requires the scope `me` (it could require more than one scope). We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels. ```Python hl_lines="5 140 167" -{!./src/security/tutorial005.py!} +{!../../../docs_src/security/tutorial005.py!} ``` !!! info "Technical Details" @@ -142,7 +144,7 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly). ```Python hl_lines="9 106" -{!./src/security/tutorial005.py!} +{!../../../docs_src/security/tutorial005.py!} ``` ## Use the `scopes` @@ -158,7 +160,7 @@ We create an `HTTPException` that we can re-use (`raise`) later at several point In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in in the `WWW-Authenticate` header (this is part of the spec). ```Python hl_lines="106 108 109 110 111 112 113 114 115 116" -{!./src/security/tutorial005.py!} +{!../../../docs_src/security/tutorial005.py!} ``` ## Verify the `username` and data shape @@ -176,7 +178,7 @@ Instead of, for example, a `dict`, or something else, as it could break the appl We also verify that we have a user with that username, and if not, we raise that same exception we created before. ```Python hl_lines="47 117 118 119 120 121 122 123 124 125 126 127 128" -{!./src/security/tutorial005.py!} +{!../../../docs_src/security/tutorial005.py!} ``` ## Verify the `scopes` @@ -186,7 +188,7 @@ We now verify that all the scopes required, by this dependency and all the depen For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`. ```Python hl_lines="129 130 131 132 133 134 135" -{!./src/security/tutorial005.py!} +{!../../../docs_src/security/tutorial005.py!} ``` ## Dependency tree and scopes diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md new file mode 100644 index 0000000000000..f30de226c7c22 --- /dev/null +++ b/docs/en/docs/advanced/settings.md @@ -0,0 +1,382 @@ +# Settings and Environment Variables + +In many cases your application could need some external settings or configurations, for example secret keys, database credentials, credentials for email services, etc. + +Most of these settings are variable (can change), like database URLs. And many could be sensitive, like secrets. + +For this reason it's common to provide them in environment variables that are read by the application. + +## Environment Variables + +!!! tip + If you already know what "environment variables" are and how to use them, feel free to skip to the next section below. + +An environment variable (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well). + +You can create and use environment variables in the shell, without needing Python: + +=== "Linux, macOS, Windows Bash" + +
+ + ```console + // You could create an env var MY_NAME with + $ export MY_NAME="Wade Wilson" + + // Then you could use it with other programs, like + $ echo "Hello $MY_NAME" + + Hello Wade Wilson + ``` + +
+ +=== "Windows PowerShell" + +
+ + ```console + // Create an env var MY_NAME + $ $Env:MY_NAME = "Wade Wilson" + + // Use it with other programs, like + $ echo "Hello $Env:MY_NAME" + + Hello Wade Wilson + ``` + +
+ +### Read env vars in Python + +You could also create environment variables outside of Python, in the terminal (or with any other method), and then read them in Python. + +For example you could have a file `main.py` with: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +!!! tip + The second argument to `os.getenv()` is the default value to return. + + If not provided, it's `None` by default, here we provide `"World"` as the default value to use. + +Then you could call that Python program: + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or settings. + +You can also create an environment variable only for a specific program invocation, that is only available to that program, and only for its duration. + +To do that, create it right before the program itself, on the same line: + +
+ +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
+ +!!! tip + You can read more about it at The Twelve-Factor App: Config. + +### Types and validation + +These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). + +That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or validation has to be done in code. + +## Pydantic `Settings` + +Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with Pydantic: Settings management. + +### Create the `Settings` object + +Import `BaseSettings` from Pydantic and create a sub-class, very much like with a Pydantic model. + +The same way as with Pydantic models, you declare class attributes with type annotations, and possibly default values. + +You can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`. + +```Python hl_lines="2 5 6 7 8 11" +{!../../../docs_src/settings/tutorial001.py!} +``` + +!!! tip + If you want something quick to copy and paste, don't use this example, use the last one below. + +Then, when you create an instance of that `Settings` class (in this case, in the `settings` object), Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable `APP_NAME` will still be read for the attribute `app_name`. + +Next it will convert and validate the data. So, when you use that `settings` object, you will have data of the types you declared (e.g. `items_per_user` will be an `int`). + +### Use the `settings` + +Then you can use the new `settings` object in your application: + +```Python hl_lines="18 19 20" +{!../../../docs_src/settings/tutorial001.py!} +``` + +### Run the server + +Next, you would run the server passing the configurations as environment variables, for example you could set an `ADMIN_EMAIL` and `APP_NAME` with: + +
+ +```console +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +!!! tip + To set multiple env vars for a single command just separate them with a space, and put them all before the command. + +And then the `admin_email` setting would be set to `"deadpool@example.com"`. + +The `app_name` would be `"ChimichangApp"`. + +And the `items_per_user` would keep its default value of `50`. + +## Settings in another module + +You could put those settings in another module file as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. + +For example, you could have a file `config.py` with: + +```Python +{!../../../docs_src/settings/app01/config.py!} +``` + +And then use it in a file `main.py`: + +```Python hl_lines="3 11 12 13" +{!../../../docs_src/settings/app01/main.py!} +``` + +!!! tip + You would also need a file `__init__.py` as you saw on [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. + +## Settings in a dependency + +In some occasions it might be useful to provide the settings from a dependency, instead of having a global object with `settings` that is used everywhere. + +This could be especially useful during testing, as it's very easy to override a dependency with your own custom settings. + +### The config file + +Coming from the previous example, your `config.py` file could look like: + +```Python hl_lines="10" +{!../../../docs_src/settings/app02/config.py!} +``` + +Notice that now we don't create a default instance `settings = Settings()`. + +### The main app file + +Now we create a dependency that returns a new `config.Settings()`. + +```Python hl_lines="5 11 12" +{!../../../docs_src/settings/app02/main.py!} +``` + +!!! tip + We'll discuss the `@lru_cache()` in a bit. + + For now you can assume `get_settings()` is a normal function. + +And then we can require it from the *path operation function* as a dependency and use it anywhere we need it. + +```Python hl_lines="16 18 19 20" +{!../../../docs_src/settings/app02/main.py!} +``` + +### Settings and testing + +Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`: + +```Python hl_lines="8 9 12 21" +{!../../../docs_src/settings/app02/test_main.py!} +``` + +In the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object. + +Then we can test that it is used. + +## Reading a `.env` file + +If you have many settings that possibly change a lot, maybe in different environments, it might be useful to put them on a file and then read them from it as if they were environment variables. + +This practice is common enough that it has a name, these environment variables are commonly placed in a file `.env`, and the file is called a "dotenv". + +!!! tip + A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS. + + But a dotenv file doesn't really have to have that exact filename. + +Pydantic has support for reading from these types of files using an external library. You can read more at Pydantic Settings: Dotenv (.env) support. + +!!! tip + For this to work, you need to `pip install python-dotenv`. + +### The `.env` file + +You could have a `.env` file with: + +```bash +ADMIN_EMAIL="deadpool@example.com" +APP_NAME="ChimichangApp" +``` + +### Read settings from `.env` + +And then update your `config.py` with: + +```Python hl_lines="9 10" +{!../../../docs_src/settings/app03/config.py!} +``` + +Here we create a class `Config` inside of your Pydantic `Settings` class, and set the `env_file` to the filename with the dotenv file we want to use. + +!!! tip + The `Config` class is used just for Pydantic configuration. You can read more at Pydantic Model Config + +### Creating the `Settings` only once with `lru_cache` + +Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then re-use the same settings object, instead of reading it for each request. + +But every time we do: + +```Python +config.Settings() +``` + +a new `Settings` object would be created, and at creation it would read the `.env` file again. + +If the dependency function was just like: + +```Python +def get_settings(): + return config.Settings() +``` + +we would create that object for each request, and we would be reading the `.env` file for each request. ⚠️ + +But as we are using the `@lru_cache()` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️ + +```Python hl_lines="1 10" +{!../../../docs_src/settings/app03/main.py!} +``` + +Then for any subsequent calls of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. + +#### `lru_cache` Technical Details + +`@lru_cache()` modifies the function it decorates to return the same value that was returned the first time, instead of computing it again, executing the code of the function every time. + +So, the function below it will be executed once for each combination of arguments. And then the values returned by each of those combinations of arguments will be used again and again whenever the function is called with exactly the same combination of arguments. + +For example, if you have a function: + +```Python +@lru_cache() +def say_hi(name: str, salutation: str = "Ms."): + return f"Hello {salutation} {name}" +``` + +your program could execute like this: + +```mermaid +sequenceDiagram + +participant code as Code +participant function as say_hi() +participant execute as Execute function + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Camila") + function ->> execute: execute function code + execute ->> code: return the result + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: return stored result + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick") + function ->> execute: execute function code + execute ->> code: return the result + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick", salutation="Mr.") + function ->> execute: execute function code + execute ->> code: return the result + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Rick") + function ->> code: return stored result + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: return stored result + end +``` + +In the case of our dependency `get_settings()`, the function doesn't even take any arguments, so it always returns the same value. + +That way, it behaves almost as if it was just a global variable. But as it uses a dependency function, then we can override it easily for testing. + +`@lru_cache()` is part of `functools` which is part of Python's standard library, you can read more about it in the Python docs for `@lru_cache()`. + +## Recap + +You can use Pydantic Settings to handle the settings or configurations for your application, with all the power of Pydantic models. + +* By using a dependency you can simplify testing. +* You can use `.env` files with it. +* Using `@lru_cache()` lets you avoid reading the dotenv file again and again for each request, while allowing you to override it during testing. diff --git a/docs/advanced/sql-databases-peewee.md b/docs/en/docs/advanced/sql-databases-peewee.md similarity index 94% rename from docs/advanced/sql-databases-peewee.md rename to docs/en/docs/advanced/sql-databases-peewee.md index 4c05daf7710f8..7610290066b01 100644 --- a/docs/advanced/sql-databases-peewee.md +++ b/docs/en/docs/advanced/sql-databases-peewee.md @@ -1,3 +1,5 @@ +# SQL (Relational) Databases with Peewee + !!! warning If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. @@ -60,7 +62,7 @@ Let's refer to the file `sql_app/database.py`. Let's first check all the normal Peewee code, create a Peewee database: ```Python hl_lines="3 5 22" -{!./src/sql_databases_peewee/sql_app/database.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` !!! tip @@ -112,7 +114,7 @@ This might seem a bit complex (and it actually is), you don't really need to com We will create a `PeeweeConnectionState`: ```Python hl_lines="10 11 12 13 14 15 16 17 18 19" -{!./src/sql_databases_peewee/sql_app/database.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` This class inherits from a special internal class used by Peewee. @@ -133,7 +135,7 @@ So, we need to do some extra tricks to make it work as if it was just using `thr Now, overwrite the `._state` internal attribute in the Peewee database `db` object using the new `PeeweeConnectionState`: ```Python hl_lines="24" -{!./src/sql_databases_peewee/sql_app/database.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` !!! tip @@ -160,7 +162,7 @@ This is the same you would do if you followed the Peewee tutorial and updated th Import `db` from `database` (the file `database.py` from above) and use it here. ```Python hl_lines="3 6 7 8 9 10 11 12 15 16 17 18 19 20 21" -{!./src/sql_databases_peewee/sql_app/models.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` !!! tip @@ -188,7 +190,7 @@ Now let's check the file `sql_app/schemas.py`. Create all the same Pydantic models as in the SQLAlchemy tutorial: ```Python hl_lines="16 17 18 21 22 25 26 27 28 29 30 34 35 38 39 42 43 44 45 46 47 48" -{!./src/sql_databases_peewee/sql_app/schemas.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` !!! tip @@ -213,7 +215,7 @@ But recent versions of Pydantic allow providing a custom class that inherits fro We are going to create a custom `PeeweeGetterDict` class and use it in all the same Pydantic *models* / schemas that use `orm_mode`: ```Python hl_lines="3 8 9 10 11 12 13 31 49" -{!./src/sql_databases_peewee/sql_app/schemas.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` Here we are checking if the attribute that is being accessed (e.g. `.items` in `some_user.items`) is an instance of `peewee.ModelSelect`. @@ -234,7 +236,7 @@ Now let's see the file `sql_app/crud.py`. Create all the same CRUD utils as in the SQLAlchemy tutorial, all the code is very similar: ```Python hl_lines="1 4 5 8 9 12 13 16 17 18 19 20 23 24 27 28 29 30" -{!./src/sql_databases_peewee/sql_app/crud.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} ``` There are some differences with the code for the SQLAlchemy tutorial. @@ -258,7 +260,7 @@ And now in the file `sql_app/main.py` let's integrate and use all the other part In a very simplistic way create the database tables: ```Python hl_lines="9 10 11" -{!./src/sql_databases_peewee/sql_app/main.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### Create a dependency @@ -266,7 +268,7 @@ In a very simplistic way create the database tables: Create a dependency that will connect the database right at the beginning of a request and disconnect it at the end: ```Python hl_lines="23 24 25 26 27 28 29" -{!./src/sql_databases_peewee/sql_app/main.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` Here we have an empty `yield` because we are actually not using the database object directly. @@ -280,7 +282,7 @@ And then, in each *path operation function* that needs to access the database we But we are not using the value given by this dependency (it actually doesn't give any value, as it has an empty `yield`). So, we don't add it to the *path operation function* but to the *path operation decorator* in the `dependencies` parameter: ```Python hl_lines="32 40 47 59 65 72" -{!./src/sql_databases_peewee/sql_app/main.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### Context variable sub-dependency @@ -290,7 +292,7 @@ For all the `contextvars` parts to work, we need to make sure we have an indepen For that, we need to create another `async` dependency `reset_db_state()` that is used as a sub-dependency in `get_db()`. It will set the value for the context variable (with just a default `dict`) that will be used as the database state for the whole request. And then the dependency `get_db()` will store in it the database state (connection, transactions, etc). ```Python hl_lines="18 19 20" -{!./src/sql_databases_peewee/sql_app/main.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` For the **next request**, as we will reset that context variable again in the `async` dependency `reset_db_state()` and then create a new connection in the `get_db()` dependency, that new request will have its own database state (connection, transactions, etc). @@ -319,7 +321,7 @@ async def reset_db_state(): Now, finally, here's the standard **FastAPI** *path operations* code. ```Python hl_lines="32 33 34 35 36 37 40 41 42 43 46 47 48 49 50 51 52 53 56 57 58 59 60 61 62 65 66 67 68 71 72 73 74 75 76 77 78 79" -{!./src/sql_databases_peewee/sql_app/main.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### About `def` vs `async def` @@ -369,10 +371,16 @@ async def reset_db_state(): Then run your app with Uvicorn: -```bash -uvicorn sql_app.main:app --reload +
+ +```console +$ uvicorn sql_app.main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` +
+ Open your browser at http://127.0.0.1:8000/docs and create a couple of users. Then open 10 tabs at http://127.0.0.1:8000/docs#/default/read_slow_users_slowusers__get at the same time. @@ -430,31 +438,31 @@ Repeat the same process with the 10 tabs. This time all of them will wait and yo * `sql_app/database.py`: ```Python -{!./src/sql_databases_peewee/sql_app/database.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` * `sql_app/models.py`: ```Python -{!./src/sql_databases_peewee/sql_app/models.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` * `sql_app/schemas.py`: ```Python -{!./src/sql_databases_peewee/sql_app/schemas.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` * `sql_app/crud.py`: ```Python -{!./src/sql_databases_peewee/sql_app/crud.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} ``` * `sql_app/main.py`: ```Python -{!./src/sql_databases_peewee/sql_app/main.py!} +{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ## Technical Details diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md new file mode 100644 index 0000000000000..68d5790db8a03 --- /dev/null +++ b/docs/en/docs/advanced/sub-applications.md @@ -0,0 +1,73 @@ +# Sub Applications - Mounts + +If you need to have two independent FastAPI applications, with their own independent OpenAPI and their own docs UIs, you can have a main app and "mount" one (or more) sub-application(s). + +## Mounting a **FastAPI** application + +"Mounting" means adding a completely "independent" application in a specific path, that then takes care of handling all everything under that path, with the _path operations_ declared in that sub-application. + +### Top-level application + +First, create the main, top-level, **FastAPI** application, and its *path operations*: + +```Python hl_lines="3 6 7 8" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### Sub-application + +Then, create your sub-application, and its *path operations*. + +This sub-application is just another standard FastAPI application, but this is the one that will be "mounted": + +```Python hl_lines="11 14 15 16" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### Mount the sub-application + +In your top-level application, `app`, mount the sub-application, `subapi`. + +In this case, it will be mounted at the path `/subapi`: + +```Python hl_lines="11 19" +{!../../../docs_src/sub_applications/tutorial001.py!} +``` + +### Check the automatic API docs + +Now, run `uvicorn` with the main app, if your file is `main.py`, it would be: + +
+ +```console +$ uvicorn 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 for the main app, including only its own _path operations_: + + + +And then, open the docs for the sub-application, at http://127.0.0.1:8000/subapi/docs. + +You will see the automatic API docs for the sub-application, including only its own _path operations_, all under the correct sub-path prefix `/subapi`: + + + +If you try interacting with any of the two user interfaces, they will work correctly, because the browser will be able to talk to each specific app or sub-app. + +### Technical Details: `root_path` + +When you mount a sub-application as described above, FastAPI will take care of communicating the mount path for the sub-application using a mechanism from the ASGI specification called a `root_path`. + +That way, the sub-application will know to use that path prefix for the docs UI. + +And the sub-application could also have its own mounted sub-applications and everything would work correctly, because FastAPI handles all these `root_path`s automatically. + +You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md similarity index 85% rename from docs/advanced/templates.md rename to docs/en/docs/advanced/templates.md index 9b8f750b5923c..871f3163f0622 100644 --- a/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -1,3 +1,5 @@ +# Templates + You can use any template engine you want with **FastAPI**. A common election is Jinja2, the same one used by Flask and other tools. @@ -8,16 +10,28 @@ There are utilities to configure it easily that you can use directly in your **F Install `jinja2`: -```bash -pip install jinja2 +
+ +```console +$ pip install jinja2 + +---> 100% ``` +
+ If you need to also serve static files (as in this example), install `aiofiles`: -```bash -pip install aiofiles +
+ +```console +$ pip install aiofiles + +---> 100% ``` +
+ ## Using `Jinja2Templates` * Import `Jinja2Templates`. @@ -26,7 +40,7 @@ pip install aiofiles * Use the `templates` you created to render and return a `TemplateResponse`, passing the `request` as one of the key-value pairs in the Jinja2 "context". ```Python hl_lines="3 10 14 15" -{!./src/templates/tutorial001.py!} +{!../../../docs_src/templates/tutorial001.py!} ``` !!! note @@ -42,7 +56,7 @@ pip install aiofiles Then you can write a template at `templates/item.html` with: ```jinja hl_lines="7" -{!./src/templates/templates/item.html!} +{!../../../docs_src/templates/templates/item.html!} ``` It will show the `id` taken from the "context" `dict` you passed: @@ -56,13 +70,13 @@ It will show the `id` taken from the "context" `dict` you passed: And you can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted. ```jinja hl_lines="4" -{!./src/templates/templates/item.html!} +{!../../../docs_src/templates/templates/item.html!} ``` In this example, it would link to a CSS file at `static/styles.css` with: ```CSS hl_lines="4" -{!./src/templates/static/styles.css!} +{!../../../docs_src/templates/static/styles.css!} ``` And because you are using `StaticFiles`, that CSS file would be served automatically by your **FastAPI** application at the URL `/static/styles.css`. diff --git a/docs/en/docs/advanced/testing-database.md b/docs/en/docs/advanced/testing-database.md new file mode 100644 index 0000000000000..385d988005fae --- /dev/null +++ b/docs/en/docs/advanced/testing-database.md @@ -0,0 +1,95 @@ +# Testing a Database + +You can use the same dependency overrides from [Testing Dependencies with Overrides](testing-dependencies.md){.internal-link target=_blank} to alter a database for testing. + +You could want to set up a different database for testing, rollback the data after the tests, pre-fill it with some testing data, etc. + +The main idea is exactly the same you saw in that previous chapter. + +## Add tests for the SQL app + +Let's update the example from [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} to use a testing database. + +All the app code is the same, you can go back to that chapter check how it was. + +The only changes here are in the new testing file. + +Your normal dependency `get_db()` would return a database session. + +In the test, you could use a dependency override to return your *custom* database session instead of the one that would be used normally. + +In this example we'll create a temporary database only for the tests. + +## File structure + +We create a new file at `sql_app/tests/test_sql_app.py`. + +So the new file structure looks like: + +``` hl_lines="9 10 11" +. +└── sql_app + ├── __init__.py + ├── crud.py + ├── database.py + ├── main.py + ├── models.py + ├── schemas.py + └── tests + ├── __init__.py + └── test_sql_app.py +``` + +## Create the new database session + +First, we create a new database session with the new database. + +For the tests we'll use a file `test.db` instead of `sql_app.db`. + +But the rest of the session code is more or less the same, we just copy it. + +```Python hl_lines="8 9 10 11 12 13" +{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +``` + +!!! tip + You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`. + + For simplicity and to focus on the specific testing code, we are just copying it. + +## Create the database + +Because now we are going to use a new database in a new file, we need to make sure we create the database with: + +```Python +Base.metadata.create_all(bind=engine) +``` + +That is normally called in `main.py`, but the line in `main.py` uses the database file `sql_app.db`, and we need to make sure we create `test.db` for the tests. + +So we add that line here, with the new file. + +```Python hl_lines="16" +{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +``` + +## Dependency override + +Now we create the dependency override and add it to the overrides for our app. + +```Python hl_lines="19 20 21 22 23 24 27" +{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +``` + +!!! tip + The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead. + +## Test the app + +Then we can just test the app as normally. + +```Python hl_lines="32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47" +{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +``` + +And all the modifications we made in the database during the tests will be in the `test.db` database instead of the main `sql_app.db`. diff --git a/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md similarity index 81% rename from docs/advanced/testing-dependencies.md rename to docs/en/docs/advanced/testing-dependencies.md index 50d50618cf154..f2c283947ff83 100644 --- a/docs/advanced/testing-dependencies.md +++ b/docs/en/docs/advanced/testing-dependencies.md @@ -1,3 +1,5 @@ +# Testing Dependencies with Overrides + ## Overriding dependencies during testing There are some scenarios where you might want to override a dependency during testing. @@ -18,18 +20,6 @@ You probably want to test the external provider once, but not necessarily call i In this case, you can override the dependency that calls that provider, and use a custom dependency that returns a mock user, only for your tests. -### Use case: testing database - -Other example could be that you are using a specific database only for testing. - -Your normal dependency would return a database session. - -But then, after each test, you could want to rollback all the operations or remove data. - -Or you could want to alter the data before the tests run, etc. - -In this case, you could use a dependency override to return your *custom* database session instead of the one that would be used normally. - ### Use the `app.dependency_overrides` attribute For these cases, your **FastAPI** application has an attribute `app.dependency_overrides`, it is a simple `dict`. @@ -39,7 +29,7 @@ To override a dependency for testing, you put as a key the original dependency ( And then **FastAPI** will call that override instead of the original dependency. ```Python hl_lines="24 25 28" -{!./src/dependency_testing/tutorial001.py!} +{!../../../docs_src/dependency_testing/tutorial001.py!} ``` !!! tip diff --git a/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md similarity index 67% rename from docs/advanced/testing-events.md rename to docs/en/docs/advanced/testing-events.md index a52aabe9870f5..45d8d868654fb 100644 --- a/docs/advanced/testing-events.md +++ b/docs/en/docs/advanced/testing-events.md @@ -1,7 +1,7 @@ -## Testing Events, `startup` and `shutdown` +# Testing Events: startup - shutdown When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement: ```Python hl_lines="9 10 11 12 20 21 22 23 24" -{!./src/app_testing/tutorial003.py!} -``` \ No newline at end of file +{!../../../docs_src/app_testing/tutorial003.py!} +``` diff --git a/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md similarity index 72% rename from docs/advanced/testing-websockets.md rename to docs/en/docs/advanced/testing-websockets.md index 8e9ecf34f8e7e..a9d6821becfd4 100644 --- a/docs/advanced/testing-websockets.md +++ b/docs/en/docs/advanced/testing-websockets.md @@ -1,9 +1,9 @@ -## Testing WebSockets +# Testing WebSockets You can use the same `TestClient` to test WebSockets. For this, you use the `TestClient` in a `with` statement, connecting to the WebSocket: ```Python hl_lines="27 28 29 30 31" -{!./src/app_testing/tutorial002.py!} +{!../../../docs_src/app_testing/tutorial002.py!} ``` diff --git a/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md similarity index 96% rename from docs/advanced/using-request-directly.md rename to docs/en/docs/advanced/using-request-directly.md index 4d9e84d2c2a42..ac452c25ee343 100644 --- a/docs/advanced/using-request-directly.md +++ b/docs/en/docs/advanced/using-request-directly.md @@ -1,3 +1,5 @@ +# Using the Request Directly + Up to now, you have been declaring the parts of the request that you need with their types. Taking data from: @@ -28,7 +30,7 @@ Let's imagine you want to get the client's IP address/host inside of your *path For that you need to access the request directly. ```Python hl_lines="1 7 8" -{!./src/using_request_directly/tutorial001.py!} +{!../../../docs_src/using_request_directly/tutorial001.py!} ``` By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter. diff --git a/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md similarity index 90% rename from docs/advanced/websockets.md rename to docs/en/docs/advanced/websockets.md index ac6d93864ff3c..d473cef0705c5 100644 --- a/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -1,3 +1,4 @@ +# WebSockets You can use WebSockets with **FastAPI**. @@ -24,7 +25,7 @@ In production you would have one of the options above. But it's the simplest way to focus on the server-side of WebSockets and have a working example: ```Python hl_lines="2 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 41 42 43" -{!./src/websockets/tutorial001.py!} +{!../../../docs_src/websockets/tutorial001.py!} ``` ## Create a `websocket` @@ -32,7 +33,7 @@ But it's the simplest way to focus on the server-side of WebSockets and have a w In your **FastAPI** application, create a `websocket`: ```Python hl_lines="1 46 47" -{!./src/websockets/tutorial001.py!} +{!../../../docs_src/websockets/tutorial001.py!} ``` !!! note "Technical Details" @@ -45,7 +46,7 @@ In your **FastAPI** application, create a `websocket`: In your WebSocket route you can `await` for messages and send messages. ```Python hl_lines="48 49 50 51 52" -{!./src/websockets/tutorial001.py!} +{!../../../docs_src/websockets/tutorial001.py!} ``` You can receive and send binary, text, and JSON data. @@ -64,7 +65,7 @@ In WebSocket endpoints you can import from `fastapi` and use: They work the same way as for other FastAPI endpoints/*path operations*: ```Python hl_lines="53 54 55 56 57 58 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76" -{!./src/websockets/tutorial002.py!} +{!../../../docs_src/websockets/tutorial002.py!} ``` !!! info @@ -85,10 +86,16 @@ To learn more about the options, check Starlette's documentation for: If your file is named `main.py`, run your application 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) ``` +
+ Open your browser at http://127.0.0.1:8000. You will see a simple page like: diff --git a/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md similarity index 89% rename from docs/advanced/wsgi.md rename to docs/en/docs/advanced/wsgi.md index 7d2edfc55a6c5..0b917e7f7c1d9 100644 --- a/docs/advanced/wsgi.md +++ b/docs/en/docs/advanced/wsgi.md @@ -1,3 +1,5 @@ +# Including WSGI - Flask, Django, others + You can mount WSGI applications as you saw with [Sub Applications - Behind a Proxy, Mounts](./sub-applications-proxy.md){.internal-link target=_blank}. For that, you can use the `WSGIMiddleware` and use it to wrap your WSGI application, for example, Flask, Django, etc. @@ -10,8 +12,8 @@ Then wrap the WSGI (e.g. Flask) app with the middleware. And then mount that under a path. -```Python hl_lines="1 3 22" -{!./src/wsgi/tutorial001.py!} +```Python hl_lines="2 3 22" +{!../../../docs_src/wsgi/tutorial001.py!} ``` ## Check it diff --git a/docs/alternatives.md b/docs/en/docs/alternatives.md similarity index 99% rename from docs/alternatives.md rename to docs/en/docs/alternatives.md index 730c1079450f0..3d9e3a55af90f 100644 --- a/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -1,3 +1,5 @@ +# Alternatives, Inspiration and Comparisons + What inspired **FastAPI**, how it compares to other alternatives and what it learned from them. ## Intro diff --git a/docs/async.md b/docs/en/docs/async.md similarity index 62% rename from docs/async.md rename to docs/en/docs/async.md index 24c2f61d2ef9a..756909e989c7f 100644 --- a/docs/async.md +++ b/docs/en/docs/async.md @@ -1,3 +1,5 @@ +# Concurrency and async / await + Details about the `async def` syntax for *path operation functions* and some background about asynchronous code, concurrency, and parallelism. ## In a hurry? @@ -53,7 +55,7 @@ But by following the steps above, it will be able to do some performance optimiz Modern versions of Python have support for **"asynchronous code"** using something called **"coroutines"**, with **`async` and `await`** syntax. -Let's see that phrase by parts in the sections below, below: +Let's see that phrase by parts in the sections below: * **Asynchronous Code** * **`async` and `await`** @@ -61,13 +63,13 @@ Let's see that phrase by parts in the sections below, below: ## Asynchronous Code -Asynchronous code just means that the language has a way to tell the computer / program that at some point in the code, he will have to wait for *something else* to finish somewhere else. Let's say that *something else* is called "slow-file". +Asynchronous code just means that the language 💬 has a way to tell the computer / program 🤖 that at some point in the code, it 🤖 will have to wait for *something else* to finish somewhere else. Let's say that *something else* is called "slow-file" 📝. -So, during that time, the computer can go and do some other work, while "slow-file" finishes. +So, during that time, the computer can go and do some other work, while "slow-file" 📝 finishes. -Then the computer / program will come back every time it has a chance because it's waiting again, or whenever he finished all the work he had at that point. And it will see if any of the tasks he was waiting for has already finished doing whatever it had to do. +Then the computer / program 🤖 will come back every time it has a chance because it's waiting again, or whenever it 🤖 finished all the work it had at that point. And it 🤖 will see if any of the tasks it was waiting for have already finished, doing whatever it had to do. -And then it takes the first task to finish (let's say, our "slow-file") and continues whatever it had to do with it. +Next, it 🤖 takes the first task to finish (let's say, our "slow-file" 📝) and continues whatever it had to do with it. That "wait for something else" normally refers to I/O operations that are relatively "slow" (compared to the speed of the processor and the RAM memory), like waiting for: @@ -80,7 +82,7 @@ That "wait for something else" normally refers to I/O operations, so they call them "I/O bound". +As the execution time is consumed mostly by waiting for I/O operations, they call them "I/O bound" operations. It's called "asynchronous" because the computer / program doesn't have to be "synchronized" with the slow task, waiting for the exact moment that the task finishes, while doing nothing, to be able to take the task result and continue the work. @@ -92,7 +94,7 @@ For "synchronous" (contrary to "asynchronous") they commonly also use the term " This idea of **asynchronous** code described above is also sometimes called **"concurrency"**. It is different from **"parallelism"**. -**Concurrency** and **parallelism** both relate to "different things happening more or less at the same time". +**Concurrency** and **parallelism** both relate to "different things happening more or less at the same time". But the details between *concurrency* and *parallelism* are quite different. @@ -100,107 +102,109 @@ To see the difference, imagine the following story about burgers: ### Concurrent Burgers -You go with your crush to get fast food, you stand in line while the cashier takes the orders from the people in front of you. +You go with your crush 😍 to get fast food 🍔, you stand in line while the cashier 💁 takes the orders from the people in front of you. -Then it's your turn, you place your order of 2 very fancy burgers for your crush and you. +Then it's your turn, you place your order of 2 very fancy burgers 🍔 for your crush 😍 and you. -You pay. +You pay 💸. -The cashier says something to the guy in the kitchen so he knows he has to prepare your burgers (even though he is currently preparing the ones for the previous clients). +The cashier 💁 says something to the guy in the kitchen 👨‍🍳 so he knows he has to prepare your burgers 🍔 (even though he is currently preparing the ones for the previous clients). -The cashier gives you the number of your turn. +The cashier 💁 gives you the number of your turn. -While you are waiting, you go with your crush and pick a table, you sit and talk with your crush for a long time (as your burgers are very fancy and take some time to prepare). +While you are waiting, you go with your crush 😍 and pick a table, you sit and talk with your crush 😍 for a long time (as your burgers are very fancy and take some time to prepare ✨🍔✨). -As you are seating on the table with your crush, while you wait for the burgers, you can spend that time admiring how awesome, cute and smart your crush is. +As you are sitting on the table with your crush 😍, while you wait for the burgers 🍔, you can spend that time admiring how awesome, cute and smart your crush is ✨😍✨. -While waiting and talking to your crush, from time to time, you check the number displayed on the counter to see if it's your turn already. +While waiting and talking to your crush 😍, from time to time, you check the number displayed on the counter to see if it's your turn already. -Then at some point, it finally is your turn. You go to the counter, get your burgers and come back to the table. +Then at some point, it finally is your turn. You go to the counter, get your burgers 🍔 and come back to the table. -You and your crush eat the burgers and have a nice time. +You and your crush 😍 eat the burgers 🍔 and have a nice time ✨. --- -Imagine you are the computer / program in that story. +Imagine you are the computer / program 🤖 in that story. -While you are at the line, you are just idle, waiting for your turn, not doing anything very "productive". But the line is fast because the cashier is only taking the orders, so that's fine. +While you are at the line, you are just idle 😴, waiting for your turn, not doing anything very "productive". But the line is fast because the cashier 💁 is only taking the orders (not preparing them), so that's fine. -Then, when it's your turn, you do actual "productive" work, you process the menu, decide what you want, get your crush's choice, pay, check that you give the correct bill or card, check that you are charged correctly, check that the order has the correct items, etc. +Then, when it's your turn, you do actual "productive" work 🤓, you process the menu, decide what you want, get your crush's 😍 choice, pay 💸, check that you give the correct bill or card, check that you are charged correctly, check that the order has the correct items, etc. -But then, even though you still don't have your burgers, your work with the cashier is "on pause", because you have to wait for your burgers to be ready. +But then, even though you still don't have your burgers 🍔, your work with the cashier 💁 is "on pause" ⏸, because you have to wait 🕙 for your burgers to be ready. -But as you go away from the counter and seat on the table with a number for your turn, you can switch your attention to your crush, and "work" on that. Then you are again doing something very "productive", as is flirting with your crush. +But as you go away from the counter and sit on the table with a number for your turn, you can switch 🔀 your attention to your crush 😍, and "work" ⏯ 🤓 on that. Then you are again doing something very "productive" 🤓, as is flirting with your crush 😍. -Then the cashier says "I'm finished with doing the burgers" by putting your number on the counter display, but you don't jump like crazy immediately when the displayed number changes to your turn number. You know no one will steal your burgers because you have the number of your turn, and they have theirs. +Then the cashier 💁 says "I'm finished with doing the burgers" 🍔 by putting your number on the counter's display, but you don't jump like crazy immediately when the displayed number changes to your turn number. You know no one will steal your burgers 🍔 because you have the number of your turn, and they have theirs. -So you wait for your crush to finish the story (finish the current work / task being processed), smile gently and say that you are going for the burgers. +So you wait for your crush 😍 to finish the story (finish the current work ⏯ / task being processed 🤓), smile gently and say that you are going for the burgers ⏸. -Then you go to the counter, to the initial task that is now finished, pick the burgers, say thanks and take them to the table. That finishes that step / task of interaction with the counter. That in turn, creates a new task, of "eating burgers", but the previous one of "getting burgers" is finished. +Then you go to the counter 🔀, to the initial task that is now finished ⏯, pick the burgers 🍔, say thanks and take them to the table. That finishes that step / task of interaction with the counter ⏹. That in turn, creates a new task, of "eating burgers" 🔀 ⏯, but the previous one of "getting burgers" is finished ⏹. ### Parallel Burgers -You go with your crush to get parallel fast food. +Now let's imagine these aren't "Concurrent Burgers", but "Parallel Burgers". + +You go with your crush 😍 to get parallel fast food 🍔. -You stand in line while several (let's say 8) cashiers take the orders from the people in front of you. +You stand in line while several (let's say 8) cashiers that at the same time are cooks 👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳 take the orders from the people in front of you. -Everyone before you is waiting for their burgers to be ready before leaving the counter because each of the 8 cashiers goes himself and prepares the burger right away before getting the next order. +Everyone before you is waiting 🕙 for their burgers 🍔 to be ready before leaving the counter because each of the 8 cashiers goes himself and prepares the burger right away before getting the next order. -Then it's finally your turn, you place your order of 2 very fancy burgers for your crush and you. +Then it's finally your turn, you place your order of 2 very fancy burgers 🍔 for your crush 😍 and you. -You pay. +You pay 💸. -The cashier goes to the kitchen. +The cashier goes to the kitchen 👨‍🍳. -You wait, standing in front of the counter, so that no one else takes your burgers before you, as there are no numbers for turns. +You wait, standing in front of the counter 🕙, so that no one else takes your burgers 🍔 before you do, as there are no numbers for turns. -As you and your crush are busy not letting anyone get in front of you and take your burgers whenever they arrive, you cannot pay attention to your crush. +As you and your crush 😍 are busy not letting anyone get in front of you and take your burgers whenever they arrive 🕙, you cannot pay attention to your crush 😞. -This is "synchronous" work, you are "synchronized" with the cashier/cook. You have to wait and be there at the exact moment that the cashier/cook finishes the burgers and gives them to you, or otherwise, someone else might take them. +This is "synchronous" work, you are "synchronized" with the cashier/cook 👨‍🍳. You have to wait 🕙 and be there at the exact moment that the cashier/cook 👨‍🍳 finishes the burgers 🍔 and gives them to you, or otherwise, someone else might take them. -Then your cashier/cook finally comes back with your burgers, after a long time waiting there in front of the counter. +Then your cashier/cook 👨‍🍳 finally comes back with your burgers 🍔, after a long time waiting 🕙 there in front of the counter. -You take your burgers and go to the table with your crush. +You take your burgers 🍔 and go to the table with your crush 😍. -You just eat them, and you are done. +You just eat them, and you are done 🍔 ⏹. -There was not much talk or flirting as most of the time was spent waiting in front of the counter. +There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter 😞. --- -In this scenario of the parallel burgers, you are a computer / program with two processors (you and your crush), both waiting and dedicating their attention to be "waiting on the counter" for a long time. +In this scenario of the parallel burgers, you are a computer / program 🤖 with two processors (you and your crush 😍), both waiting 🕙 and dedicating their attention ⏯ to be "waiting on the counter" 🕙 for a long time. -The fast food store has 8 processors (cashiers/cooks). While the concurrent burgers store might have had only 2 (one cashier and one cook). +The fast food store has 8 processors (cashiers/cooks) 👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳. While the concurrent burgers store might have had only 2 (one cashier and one cook) 💁 👨‍🍳. -But still, the final experience is not the best. +But still, the final experience is not the best 😞. --- -This would be the parallel equivalent story for burgers. +This would be the parallel equivalent story for burgers 🍔. For a more "real life" example of this, imagine a bank. -Up to recently, most of the banks had multiple cashiers and a big line. +Up to recently, most of the banks had multiple cashiers 👨‍💼👨‍💼👨‍💼👨‍💼 and a big line 🕙🕙🕙🕙🕙🕙🕙🕙. -All of the cashiers doing all the work with one client after the other. +All of the cashiers doing all the work with one client after the other 👨‍💼⏯. -And you have to wait in the line for a long time or you lose your turn. +And you have to wait 🕙 in the line for a long time or you lose your turn. -You probably wouldn't want to take your crush with you to do errands at the bank. +You probably wouldn't want to take your crush 😍 with you to do errands at the bank 🏦. ### Burger Conclusion -In this scenario of "fast food burgers with your crush", as there is a lot of waiting, it makes a lot more sense to have a concurrent system. +In this scenario of "fast food burgers with your crush", as there is a lot of waiting 🕙, it makes a lot more sense to have a concurrent system ⏸🔀⏯. This is the case for most of the web applications. -Many, many users, but your server is waiting for their not-so-good connection to send their requests. +Many, many users, but your server is waiting 🕙 for their not-so-good connection to send their requests. -And then waiting again for the responses to come back. +And then waiting 🕙 again for the responses to come back. -This "waiting" is measured in microseconds, but still, summing it all, it's a lot of waiting in the end. +This "waiting" 🕙 is measured in microseconds, but still, summing it all, it's a lot of waiting in the end. -That's why it makes a lot of sense to use asynchronous code for web APIs. +That's why it makes a lot of sense to use asynchronous ⏸🔀⏯ code for web APIs. Most of the existing popular Python frameworks (including Flask and Django) were created before the new asynchronous features in Python existed. So, the ways they can be deployed support parallel execution and an older form of asynchronous execution that is not as powerful as the new capabilities. @@ -208,7 +212,7 @@ Even though the main specification for asynchronous web Python (ASGI) was develo That kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programing language. -And that's the same level of performance you get with **FastAPI**. +And that's the same level of performance you get with **FastAPI**. And as you can have parallelism and asynchronicity at the same time, you get higher performance than most of the tested NodeJS frameworks and on par with Go, which is a compiled language closer to C (all thanks to Starlette). @@ -226,15 +230,15 @@ So, to balance that out, imagine the following short story: --- -There's no waiting anywhere, just a lot of work to be done, on multiple places of the house. +There's no waiting 🕙 anywhere, just a lot of work to be done, on multiple places of the house. -You could have turns as in the burgers example, first the living room, then the kitchen, but as you are not waiting for anything, just cleaning and cleaning, the turns wouldn't affect anything. +You could have turns as in the burgers example, first the living room, then the kitchen, but as you are not waiting 🕙 for anything, just cleaning and cleaning, the turns wouldn't affect anything. It would take the same amount of time to finish with or without turns (concurrency) and you would have done the same amount of work. -But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner. +But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners 👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner. -In this scenario, each one of the cleaners (including you) would be a processor, doing their part of the job. +In this scenario, each one of the cleaners (including you) would be a processor, doing their part of the job. And as most of the execution time is taken by actual work (instead of waiting), and the work in a computer is done by a CPU, they call these problems "CPU bound". @@ -244,8 +248,8 @@ Common examples of CPU bound operations are things that require complex math pro For example: -* **Audio** or **image processing** -* **Computer vision**: an image is composed of millions of pixels, each pixel has 3 values / colors, processing that normally requires computing something on those pixels, all at the same time) +* **Audio** or **image processing**. +* **Computer vision**: an image is composed of millions of pixels, each pixel has 3 values / colors, processing that normally requires computing something on those pixels, all at the same time. * **Machine Learning**: it normally requires lots of "matrix" and "vector" multiplications. Think of a huge spreadsheet with numbers and multiplying all of them together at the same time. * **Deep Learning**: this is a sub-field of Machine Learning, so, the same applies. It's just that there is not a single spreadsheet of numbers to multiply, but a huge set of them, and in many cases, you use a special processor to build and / or use those models. @@ -261,7 +265,7 @@ To see how to achieve this parallelism in production see the section about [Depl ## `async` and `await` -Modern versions of python have a very intuitive way to define asynchronous code. This makes it look just like normal "sequential" code and do the "awaiting" for you at the right moments. +Modern versions of Python have a very intuitive way to define asynchronous code. This makes it look just like normal "sequential" code and do the "awaiting" for you at the right moments. When there is an operation that will require waiting before giving the results and has support for these new Python features, you can code it like: @@ -269,7 +273,7 @@ When there is an operation that will require waiting before giving the results a burgers = await get_burgers(2) ``` -The key here is the `await`. It tells Python that it has to wait for `get_burgers(2)` to finish doing its thing before storing the results in `burgers`. With that, Python will know that it can go and do something else in the meanwhile (like receiving another request). +The key here is the `await`. It tells Python that it has to wait ⏸ for `get_burgers(2)` to finish doing its thing 🕙 before storing the results in `burgers`. With that, Python will know that it can go and do something else 🔀 ⏯ in the meanwhile (like receiving another request). For `await` to work, it has to be inside a function that supports this asynchronicity. To do that, you just declare it with `async def`: @@ -288,7 +292,7 @@ def get_sequential_burgers(number: int): return burgers ``` -With `async def`, Python knows that, inside that function, it has to be aware of `await` expressions, and that it can "pause" the execution of that function and go do something else before coming back. +With `async def`, Python knows that, inside that function, it has to be aware of `await` expressions, and that it can "pause" ⏸ the execution of that function and go do something else 🔀 before coming back. When you want to call an `async def` function, you have to "await" it. So, this won't work: @@ -332,11 +336,11 @@ But before that, handling asynchronous code was quite more complex and difficult In previous versions of Python, you could have used threads or Gevent. But the code is way more complex to understand, debug, and think about. -In previous versions of NodeJS / Browser JavaScript, you would have used "callbacks". Which lead to callback hell. +In previous versions of NodeJS / Browser JavaScript, you would have used "callbacks". Which leads to callback hell. ## Coroutines -**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function that it can start and that it will end at some point, but that it might be paused internally too, whenever there is an `await` inside of it. +**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. But all this functionality of using asynchronous code with `async` and `await` is many times summarized as using "coroutines". It is comparable to the main key feature of Go, the "Goroutines". @@ -346,7 +350,7 @@ Let's see the same phrase from above: > Modern versions of Python have support for **"asynchronous code"** using something called **"coroutines"**, with **`async` and `await`** syntax. -That should make more sense now. +That should make more sense now. ✨ All that is what powers FastAPI (through Starlette) and what makes it have such an impressive performance. @@ -354,16 +358,16 @@ All that is what powers FastAPI (through Starlette) and what makes it have such !!! warning You can probably skip this. - + These are very technical details of how **FastAPI** works underneath. - + If you have quite some technical knowledge (co-routines, threads, blocking, etc) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead. ### Path operation functions When you declare a *path operation function* with normal `def` instead of `async def`, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server). -If you are coming from another async framework that does not work in the way described above and you are used to define trivial compute-only *path operation functions* with plain `def` for a tiny performance gain (about 100 nanoseconds), please note that in **FastAPI** the effect would be quite opposite. In these cases, it's better to use `async def` unless your *path operation functions* use code that performs blocking IO. +If you are coming from another async framework that does not work in the way described above and you are used to define trivial compute-only *path operation functions* with plain `def` for a tiny performance gain (about 100 nanoseconds), please note that in **FastAPI** the effect would be quite opposite. In these cases, it's better to use `async def` unless your *path operation functions* use code that performs blocking I/O. Still, in both situations, chances are that **FastAPI** will [still be faster](/#performance){.internal-link target=_blank} than (or at least comparable to) your previous framework. @@ -373,7 +377,7 @@ The same applies for dependencies. If a dependency is a standard `def` function ### Sub-dependencies -You can have multiple dependencies and sub-dependencies requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread instead of being "awaited". +You can have multiple dependencies and sub-dependencies requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited". ### Other utility functions @@ -381,7 +385,7 @@ Any other utility function that you call directly can be created with normal `de This is in contrast to the functions that FastAPI calls for you: *path operation functions* and dependencies. -If your utility function is a normal function with `def`, it will be called directly (as you write it in your code), not in a threadpool, if the function is created with `async def` then you should await for that function when you call it in your code. +If your utility function is a normal function with `def`, it will be called directly (as you write it in your code), not in a threadpool, if the function is created with `async def` then you should `await` for that function when you call it in your code. --- diff --git a/docs/benchmarks.md b/docs/en/docs/benchmarks.md similarity index 99% rename from docs/benchmarks.md rename to docs/en/docs/benchmarks.md index 95efcab531766..5223df81d6c97 100644 --- a/docs/benchmarks.md +++ b/docs/en/docs/benchmarks.md @@ -1,3 +1,5 @@ +# Benchmarks + Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*) But when checking benchmarks and comparisons you should have the following in mind. diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md new file mode 100644 index 0000000000000..416bc32f84838 --- /dev/null +++ b/docs/en/docs/contributing.md @@ -0,0 +1,511 @@ +# Development - Contributing + +First, you might want to see the basic ways to [help FastAPI and get help](help-fastapi.md){.internal-link target=_blank}. + +## Developing + +If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment. + +### Virtual environment with `venv` + +You can create a virtual environment in a directory using Python's `venv` module: + +
+ +```console +$ python -m venv env +``` + +
+ +That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment. + +### Activate the environment + +Activate the new environment with: + +=== "Linux, macOS" + +
+ + ```console + $ source ./env/bin/activate + ``` + +
+ +=== "Windows PowerShell" + +
+ + ```console + $ .\env\Scripts\Activate.ps1 + ``` + +
+ +=== "Windows Bash" + + Or if you use Bash for Windows (e.g. Git Bash): + +
+ + ```console + $ source ./env/Scripts/activate + ``` + +
+ +To check it worked, use: + +=== "Linux, macOS, Windows Bash" + +
+ + ```console + $ which pip + + some/directory/fastapi/env/bin/pip + ``` + +
+ +=== "Windows PowerShell" + +
+ + ```console + $ Get-Command pip + + some/directory/fastapi/env/bin/pip + ``` + +
+ +If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 + + + +!!! tip + Every time you install a new package with `pip` under that environment, activate the environment again. + + This makes sure that if you use a terminal program installed by that package (like `flit`), you use the one from your local environment and not any other that could be installed globally. + +### Flit + +**FastAPI** uses Flit to build, package and publish the project. + +After activating the environment as described above, install `flit`: + +
+ +```console +$ pip install flit + +---> 100% +``` + +
+ +Now re-activate the environment to make sure you are using the `flit` you just installed (and not a global one). + +And now use `flit` to install the development dependencies: + +=== "Linux, macOS" + +
+ + ```console + $ flit install --deps develop --symlink + + ---> 100% + ``` + +
+ +=== "Windows" + + If you are on Windows, use `--pth-file` instead of `--symlink`: + +
+ + ```console + $ flit install --deps develop --pth-file + + ---> 100% + ``` + +
+ +It will install all the dependencies and your local FastAPI in your local environment. + +#### Using your local FastAPI + +If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code. + +And if you update that local FastAPI source code, as it is installed with `--symlink` (or `--pth-file` on Windows), when you run that Python file again, it will use the fresh version of FastAPI you just edited. + +That way, you don't have to "install" your local version to be able to test every change. + +### Format + +There is a script that you can run that will format and clean all your code: + +
+ +```console +$ bash scripts/format.sh +``` + +
+ +It will also auto-sort all your imports. + +For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above using `--symlink` (or `--pth-file` on Windows). + +### Format imports + +There is another script that formats all the imports and makes sure you don't have unused imports: + +
+ +```console +$ bash scripts/format-imports.sh +``` + +
+ +As it runs one command after the other and modifies and reverts many files, it takes a bit longer to run, so it might be easier to use `scripts/format.sh` frequently and `scripts/format-imports.sh` only before committing. + +## Docs + +First, make sure you set up your environment as described above, that will install all the requirements. + +The documentation uses MkDocs. + +And there are extra tools/scripts in place to handle translations in `./scripts/docs.py`. + +!!! tip + You don't need to see the code in `./scripts/docs.py`, you just use it in the command line. + +All the documentation is in Markdown format in the directory `./docs/en/`. + +Many of the tutorials have blocks of code. + +In most of the cases, these blocks of code are actual complete applications that can be run as is. + +In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs_src/` directory. + +And those Python files are included/injected in the documentation when generating the site. + +### Docs for tests + +Most of the tests actually run against the example source files in the documentation. + +This helps making sure that: + +* The documentation is up to date. +* The documentation examples can be run as is. +* Most of the features are covered by the documentation, ensured by test coverage. + +During local development, there is a script that builds the site and checks for any changes, live-reloading: + +
+ +```console +$ python ./scripts/docs.py live + +[INFO] Serving on http://127.0.0.1:8008 +[INFO] Start watching changes +[INFO] Start detecting changes +``` + +
+ +It will serve the documentation on `http://127.0.0.1:8008`. + +That way, you can edit the documentation/source files and see the changes live. + +#### Typer CLI (optional) + +The instructions here show you how to use the script at `./scripts/docs.py` with the `python` program directly. + +But you can also use Typer CLI, and you will get autocompletion in your terminal for the commands after installing completion. + +If you install Typer CLI, you can install completion with: + +
+ +```console +$ typer --install-completion + +zsh completion installed in /home/user/.bashrc. +Completion will take effect once you restart the terminal. +``` + +
+ +### Apps and docs at the same time + +If you run the examples with, e.g.: + +
+ +```console +$ uvicorn tutorial001:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +as Uvicorn by default will use the port `8000`, the documentation on port `8008` won't clash. + +### Translations + +Help with translations is VERY MUCH appreciated! And it can't be done without the help from the community. 🌎 🚀 + +Here are the steps to help with translations. + +#### Tips and guidelines + +* Check the currently existing pull requests for your language and add reviews requesting changes or approving them. + +!!! tip + You can add comments with change suggestions to existing pull requests. + + Check the docs about adding a pull request review to approve it or request changes. + +* Check in the issues to see if there's one coordinating translations for your language. + +* Add a single pull request per page translated. That will make it much easier for others to review it. + +For the languages I don't speak, I'll wait for several others to review the translation before merging. + +* You can also check if there are translations for your language and add a review to them, that will help me know that the translation is correct and I can merge it. + +* Use the same Python examples and only translate the text in the docs. You don't have to change anything for this to work. + +* Use the same images, file names, and links. You don't have to change anything for it to work. + +* To check the 2-letter code for the language you want to translate you can use the table List of ISO 639-1 codes. + +#### Existing language + +Let's say you want to translate a page for a language that already has translations for some pages, like Spanish. + +In the case of Spanish, the 2-letter code is `es`. So, the directory for Spanish translations is located at `docs/es/`. + +!!! tip + The main ("official") language is English, located at `docs/en/`. + +Now run the live server for the docs in Spanish: + +
+ +```console +// Use the command "live" and pass the language code as a CLI argument +$ python ./scripts/docs.py live es + +[INFO] Serving on http://127.0.0.1:8008 +[INFO] Start watching changes +[INFO] Start detecting changes +``` + +
+ +Now you can go to http://127.0.0.1:8008 and see your changes live. + +If you look at the FastAPI docs website, you will see that every language has all the pages. But some pages are not translated and have a notification about the missing translation. + +But when you run it locally like this, you will only see the pages that are already translated. + +Now let's say that you want to add a translation for the section [Features](features.md){.internal-link target=_blank}. + +* Copy the file at: + +``` +docs/en/docs/features.md +``` + +* Paste it in exactly the same location but for the language you want to translate, e.g.: + +``` +docs/es/docs/features.md +``` + +!!! tip + Notice that the only change in the path and file name is the language code, from `en` to `es`. + +* Now open the MkDocs config file for English at: + +``` +docs/en/docs/mkdocs.yml +``` + +* Find the place where that `docs/features.md` is located in the config file. Somewhere like: + +```YAML hl_lines="8" +site_name: FastAPI +# More stuff +nav: +- FastAPI: index.md +- Languages: + - en: / + - es: /es/ +- features.md +``` + +* Open the MkDocs config file for the language you are editing, e.g.: + +``` +docs/es/docs/mkdocs.yml +``` + +* Add it there at the exact same location it was for English, e.g.: + +```YAML hl_lines="8" +site_name: FastAPI +# More stuff +nav: +- FastAPI: index.md +- Languages: + - en: / + - es: /es/ +- features.md +``` + +Make sure that if there are other entries, the new entry with your translation is exactly in the same order as in the English version. + +If you go to your browser you will see that now the docs show your new section. 🎉 + +Now you can translate it all and see how it looks as you save the file. + +#### New Language + +Let's say that you want to add translations for a language that is not yet translated, not even some pages. + +Let's say you want to add translations for Creole, and it's not yet there in the docs. + +Checking the link from above, the code for "Creole" is `ht`. + +The next step is to run the script to generate a new translation directory: + +
+ +```console +// Use the command new-lang, pass the language code as a CLI argument +$ python ./scripts/docs.py new-lang ht + +Successfully initialized: docs/ht +Updating ht +Updating en +``` + +
+ +Now you can check in your code editor the newly created directory `docs/ht/`. + +!!! tip + Create a first pull request with just this, to set up the configuration for the new language, before adding translations. + + That way others can help with other pages while you work on the first one. 🚀 + +Start by translating the main page, `docs/ht/index.md`. + +Then you can continue with the previous instructions, for an "Existing Language". + +##### New Language not supported + +If when running the live server script you get an error about the language not being supported, something like: + +``` + raise TemplateNotFound(template) +jinja2.exceptions.TemplateNotFound: partials/language/xx.html +``` + +That means that the theme doesn't support that language (in this case, with a fake 2-letter code of `xx`). + +But don't worry, you can set the theme language to English and then translate the content of the docs. + +If you need to do that, edit the `mkdocs.yml` for your new language, it will have something like: + +```YAML hl_lines="5" +site_name: FastAPI +# More stuff +theme: + # More stuff + language: xx +``` + +Change that language from `xx` (from your language code) to `en`. + +Then you can start the live server again. + +#### Preview the result + +When you use the script at `./scripts/docs.py` with the `live` command it only shows the files and translations available for the current language. + +But once you are done, you can test it all as it would look online. + +To do that, first build all the docs: + +
+ +```console +// Use the command "build-all", this will take a bit +$ python ./scripts/docs.py build-all + +Updating es +Updating en +Building docs for: en +Building docs for: es +Successfully built docs for: es +Copying en index.md to README.md +``` + +
+ +That generates all the docs at `./docs_build/` for each language. This includes adding any files with missing translations, with a note saying that "this file doesn't have a translation yet". But you don't have to do anything with that directory. + +Then it builds all those independent MkDocs sites for each language, combines them, and generates the final output at `./site/`. + +Then you can serve that with the command `serve`: + +
+ +```console +// Use the command "serve" after running "build-all" +$ python ./scripts/docs.py serve + +Warning: this is a very simple server. For development, use mkdocs serve instead. +This is here only to preview a site with translations already built. +Make sure you run the build-all command first. +Serving at: http://127.0.0.1:8008 +``` + +
+ +## Tests + +There is a script that you can run locally to test all the code and generate coverage reports in HTML: + +
+ +```console +$ bash scripts/test-cov-html.sh +``` + +
+ +This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. + +### Tests in your editor + +If you want to use the integrated tests in your editor add `./docs_src` to your `PYTHONPATH` variable. + +For example, in VS Code you can create a file `.env` with: + +```env +PYTHONPATH=./docs_src +``` diff --git a/docs/css/custom.css b/docs/en/docs/css/custom.css similarity index 72% rename from docs/css/custom.css rename to docs/en/docs/css/custom.css index 94bdbed43e807..b7de5e34ec533 100644 --- a/docs/css/custom.css +++ b/docs/en/docs/css/custom.css @@ -11,3 +11,8 @@ a.internal-link::after { */ content: "\00A0↪"; } + +/* Give space to lower icons so Gitter chat doesn't get on top of them */ +.md-footer-meta { + padding-bottom: 2em; +} diff --git a/docs/en/docs/css/termynal.css b/docs/en/docs/css/termynal.css new file mode 100644 index 0000000000000..0484e65d4d8eb --- /dev/null +++ b/docs/en/docs/css/termynal.css @@ -0,0 +1,108 @@ +/** + * termynal.js + * + * @author Ines Montani + * @version 0.0.1 + * @license MIT + */ + +:root { + --color-bg: #252a33; + --color-text: #eee; + --color-text-subtle: #a2a2a2; +} + +[data-termynal] { + width: 750px; + max-width: 100%; + background: var(--color-bg); + color: var(--color-text); + font-size: 18px; + /* font-family: 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier, monospace; */ + font-family: 'Roboto Mono', 'Fira Mono', Consolas, Menlo, Monaco, 'Courier New', Courier, monospace; + border-radius: 4px; + padding: 75px 45px 35px; + position: relative; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +[data-termynal]:before { + content: ''; + position: absolute; + top: 15px; + left: 15px; + display: inline-block; + width: 15px; + height: 15px; + border-radius: 50%; + /* A little hack to display the window buttons in one pseudo element. */ + background: #d9515d; + -webkit-box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930; + box-shadow: 25px 0 0 #f4c025, 50px 0 0 #3ec930; +} + +[data-termynal]:after { + content: 'bash'; + position: absolute; + color: var(--color-text-subtle); + top: 5px; + left: 0; + width: 100%; + text-align: center; +} + +a[data-terminal-control] { + text-align: right; + display: block; + color: #aebbff; +} + +[data-ty] { + display: block; + line-height: 2; +} + +[data-ty]:before { + /* Set up defaults and ensure empty lines are displayed. */ + content: ''; + display: inline-block; + vertical-align: middle; +} + +[data-ty="input"]:before, +[data-ty-prompt]:before { + margin-right: 0.75em; + color: var(--color-text-subtle); +} + +[data-ty="input"]:before { + content: '$'; +} + +[data-ty][data-ty-prompt]:before { + content: attr(data-ty-prompt); +} + +[data-ty-cursor]:after { + content: attr(data-ty-cursor); + font-family: monospace; + margin-left: 0.5em; + -webkit-animation: blink 1s infinite; + animation: blink 1s infinite; +} + + +/* Cursor animation */ + +@-webkit-keyframes blink { + 50% { + opacity: 0; + } +} + +@keyframes blink { + 50% { + opacity: 0; + } +} diff --git a/docs/deployment.md b/docs/en/docs/deployment.md similarity index 92% rename from docs/deployment.md rename to docs/en/docs/deployment.md index 4973bc21569fe..94ab1b90b9b07 100644 --- a/docs/deployment.md +++ b/docs/en/docs/deployment.md @@ -1,3 +1,5 @@ +# Deployment + Deploying a **FastAPI** application is relatively easy. There are several ways to do it depending on your specific use case and the tools that you use. @@ -188,18 +190,28 @@ def read_item(item_id: int, q: str = None): * Go to the project directory (in where your `Dockerfile` is, containing your `app` directory). * Build your FastAPI image: -```bash -docker build -t myimage . +
+ +```console +$ docker build -t myimage . + +---> 100% ``` +
+ ### Start the Docker container * Run a container based on your image: -```bash -docker run -d --name mycontainer -p 80:80 myimage +
+ +```console +$ docker run -d --name mycontainer -p 80:80 myimage ``` +
+ Now you have an optimized FastAPI server in a Docker container. Auto-tuned for your current server (and number of CPU cores). ### Check it @@ -317,31 +329,61 @@ You can deploy **FastAPI** directly without Docker too. You just need to install an ASGI compatible server like: -* Uvicorn, a lightning-fast ASGI server, built on uvloop and httptools. +=== "Uvicorn" -```bash -pip install uvicorn -``` + * Uvicorn, a lightning-fast ASGI server, built on uvloop and httptools. -* Hypercorn, an ASGI server also compatible with HTTP/2. +
-```bash -pip install hypercorn -``` + ```console + $ pip install uvicorn + + ---> 100% + ``` + +
+ +=== "Hypercorn" + + * Hypercorn, an ASGI server also compatible with HTTP/2. + +
-...or any other ASGI server. + ```console + $ pip install hypercorn + + ---> 100% + ``` + +
+ + ...or any other ASGI server. And run your application the same way you have done in the tutorials, but without the `--reload` option, e.g.: -```bash -uvicorn main:app --host 0.0.0.0 --port 80 -``` +=== "Uvicorn" -or with Hypercorn: +
-```bash -hypercorn main:app --bind 0.0.0.0:80 -``` + ```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) + ``` + +
You might want to set up some tooling to make sure it is restarted automatically if it stops. diff --git a/docs/external-links.md b/docs/en/docs/external-links.md similarity index 80% rename from docs/external-links.md rename to docs/en/docs/external-links.md index c222e1247fcbc..34ba30e0a82df 100644 --- a/docs/external-links.md +++ b/docs/en/docs/external-links.md @@ -1,3 +1,5 @@ +# External Links and Articles + **FastAPI** has a great community constantly growing. There are many posts, articles, tools, and projects, related to **FastAPI**. @@ -57,6 +59,25 @@ Here's an incomplete list of some of them. * Create and Deploy FastAPI app to Heroku without using Docker by Navule Pavan Kumar Rao. +* Apache Kafka producer and consumer with FastAPI and aiokafka by Benjamin Ramser. + +* Real-time Notifications with Python and Postgres by Guillermo Cruz. + +* Microservice in Python using FastAPI by Paurakh Sharma Humagain. + +* Build simple API service with Python FastAPI — Part 1 by cuongld2. + +* FastAPI + Zeit.co = 🚀 + by Paul Sec. + +* Build a web API from scratch with FastAPI - the workshop by Sebastián Ramírez (tiangolo). + +* Build a Secure Twilio Webhook with Python and FastAPI by Twilio. + +* Using FastAPI with Django by Stavros Korokithakis. + +* Introducing Dispatch by Netflix. + ### Japanese * FastAPI|DB接続してCRUDするPython製APIサーバーを構築 by @mtitg. @@ -106,11 +127,16 @@ Here's an incomplete list of some of them. ## Podcasts * FastAPI on PythonBytes by Python Bytes FM. +* Build The Next Generation Of Python Web Applications With FastAPI - Episode 259 - interview to Sebastían Ramírez (tiangolo) by Podcast.`__init__`. ## Talks * PyCon UK 2019: FastAPI from the ground up by Chris Withers. +* PyConBY 2020: Serve ML models easily with FastAPI by Sebastián Ramírez (tiangolo). + +* [VIRTUAL] Py.Amsterdam's flying Software Circus: Intro to FastAPI by Sebastián Ramírez (tiangolo). + ## Projects Latest GitHub projects with the topic `fastapi`: diff --git a/docs/features.md b/docs/en/docs/features.md similarity index 95% rename from docs/features.md rename to docs/en/docs/features.md index 69c62cbced1f6..0e6daad1c7a0f 100644 --- a/docs/features.md +++ b/docs/en/docs/features.md @@ -1,3 +1,4 @@ +# Features ## FastAPI features @@ -16,11 +17,11 @@ Interactive API documentation and exploration web user interfaces. As the framew * Swagger UI, with interactive exploration, call and test your API directly from the browser. -![Swagger UI interaction](img/index/index-03-swagger-02.png) +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) * Alternative API documentation with ReDoc. -![ReDoc](img/index/index-06-redoc-02.png) +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) ### Just Modern Python @@ -70,7 +71,7 @@ my_second_user: User = User(**second_user_data) ### Editor support -All the framework was designed to be easy and intuitive to use, all the decisions where tested on multiple editors even before starting development, to ensure the best development experience. +All the framework was designed to be easy and intuitive to use, all the decisions were tested on multiple editors even before starting development, to ensure the best development experience. In the last Python developer survey it was clear that the most used feature is "autocompletion". @@ -82,11 +83,11 @@ Here's how your editor might help you: * in Visual Studio Code: -![editor support](img/vscode-completion.png) +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) * in PyCharm: -![editor support](img/pycharm-completion.png) +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) You will get completion in code you might even consider impossible before. As for example, the `price` key inside a JSON body (that could have been nested) that comes from a request. diff --git a/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md similarity index 58% rename from docs/help-fastapi.md rename to docs/en/docs/help-fastapi.md index 1370a5770eb9f..aed3ed6f6ec18 100644 --- a/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -1,3 +1,5 @@ +# Help FastAPI - Get Help + Do you like **FastAPI**? Would you like to help FastAPI, other users, and the author? @@ -10,28 +12,18 @@ And there are several ways to get help too. ## Star **FastAPI** in GitHub -You can "star" FastAPI in GitHub (clicking the star button at the top right): https://github.com/tiangolo/fastapi. +You can "star" FastAPI in GitHub (clicking the star button at the top right): https://github.com/tiangolo/fastapi. ⭐️ By adding a star, other users will be able to find it more easily and see that it has been already useful for others. ## Watch the GitHub repository for releases -You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/tiangolo/fastapi. +You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/tiangolo/fastapi. 👀 There you can select "Releases only". Doing it, you will receive notifications (in your email) whenever there's a new release (a new version) of **FastAPI** with bug fixes and new features. -## Join the chat - - - Join the chat at https://gitter.im/tiangolo/fastapi - - -Join the chat on Gitter: https://gitter.im/tiangolo/fastapi. - -There you can ask quick questions, help others, share ideas, etc. - ## Connect with the author You can connect with me (Sebastián Ramírez / `tiangolo`), the author. @@ -43,40 +35,32 @@ You can: * Follow me to see when I create a new Open Source project. * Follow me on **Twitter**. * Tell me how you use FastAPI (I love to hear that). - * Ask questions. + * Hear when I make announcements or release new tools. * Connect with me on **Linkedin**. - * Talk to me. - * Endorse me or recommend me :) -* Read what I write (or follow me) on **Medium**. - * Read other ideas, articles and tools I have created. - * Follow me to see when I publish something new. + * Hear when I make announcements or release new tools (although I use Twitter more often 🤷‍♂). +* Read what I write (or follow me) on **Dev.to** or **Medium**. + * Read other ideas, articles, and about tools I have created. + * Follow me to read when I publish something new. ## Tweet about **FastAPI** -Tweet about **FastAPI** and let me and others know why you like it. - -## Let me know how are you using **FastAPI** +Tweet about **FastAPI** and let me and others know why you like it. 🎉 I love to hear about how **FastAPI** is being used, what have you liked in it, in which project/company are you using it, etc. -You can let me know: - -* On **Twitter**. -* On **Linkedin**. -* On **Medium**. - ## Vote for FastAPI -* Vote to include **FastAPI** in `awesome-python`. * Vote for **FastAPI** in Slant. +* Vote for **FastAPI** in AlternativeTo. +* Vote for **FastAPI** on awesome-rest. ## Help others with issues in GitHub -You can see existing issues and try and help others. +You can see existing issues and try and help others, most of the times they are questions that you might already know the answer for. 🤓 ## Watch the GitHub repository -You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/tiangolo/fastapi. +You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/tiangolo/fastapi. 👀 If you select "Watching" instead of "Releases only", you will receive notifications when someone creates a new issue. @@ -86,9 +70,10 @@ Then you can try and help them solving those issues. You can create a new issue in the GitHub repository, for example to: -* Report a bug/issue. +* Ask a question or ask about a problem. * Suggest a new feature. -* Ask a question. + +**Note**: if you create an issue then I'm going to ask you to also help others. 😉 ## Create a Pull Request @@ -99,6 +84,39 @@ You can + Join the chat at https://gitter.im/tiangolo/fastapi + + +Join the chat on Gitter: https://gitter.im/tiangolo/fastapi. + +There you can have quick conversations with others, help others, share ideas, etc. + +But have in mind that as it allows more "free conversation", it's easy to ask questions that are too general and more difficult to answer, so, you might not receive answers. + +In GitHub issues the template will guide to to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the Gitter chat. 😅 + +Conversations in Gitter are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation. + +On the other side, there's more than 1000 people in the chat, so there's a high chance you'll find someone to talk to there, almost all the time. 😄 + +## Sponsor the author + +You can also financially support the author (me) through GitHub sponsors. + +There you could buy me a coffee ☕️ to say thanks 😄. + +## Sponsor the tools that power FastAPI + +As you have seen in the documentation, FastAPI stands on the shoulders of giants, Starlette and Pydantic. + +You can also sponsor: + +* Samuel Colvin (Pydantic) +* Encode (Starlette, Uvicorn) + --- -Thanks! +Thanks! 🚀 diff --git a/docs/history-design-future.md b/docs/en/docs/history-design-future.md similarity index 99% rename from docs/history-design-future.md rename to docs/en/docs/history-design-future.md index 08067e3c201bc..9db1027c26c2a 100644 --- a/docs/history-design-future.md +++ b/docs/en/docs/history-design-future.md @@ -1,3 +1,5 @@ +# History, Design and Future + Some time ago, a **FastAPI** user asked: > What’s the history of this project? It seems to have come from nowhere to awesome in a few weeks [...] diff --git a/docs/img/favicon.png b/docs/en/docs/img/favicon.png similarity index 100% rename from docs/img/favicon.png rename to docs/en/docs/img/favicon.png diff --git a/docs/img/github-social-preview.png b/docs/en/docs/img/github-social-preview.png similarity index 100% rename from docs/img/github-social-preview.png rename to docs/en/docs/img/github-social-preview.png diff --git a/docs/img/github-social-preview.svg b/docs/en/docs/img/github-social-preview.svg similarity index 100% rename from docs/img/github-social-preview.svg rename to docs/en/docs/img/github-social-preview.svg diff --git a/docs/img/icon-transparent-bg.png b/docs/en/docs/img/icon-transparent-bg.png similarity index 100% rename from docs/img/icon-transparent-bg.png rename to docs/en/docs/img/icon-transparent-bg.png diff --git a/docs/img/icon-white-bg.png b/docs/en/docs/img/icon-white-bg.png similarity index 100% rename from docs/img/icon-white-bg.png rename to docs/en/docs/img/icon-white-bg.png diff --git a/docs/img/icon-white.svg b/docs/en/docs/img/icon-white.svg similarity index 100% rename from docs/img/icon-white.svg rename to docs/en/docs/img/icon-white.svg diff --git a/docs/img/index/index-01-swagger-ui-simple.png b/docs/en/docs/img/index/index-01-swagger-ui-simple.png similarity index 100% rename from docs/img/index/index-01-swagger-ui-simple.png rename to docs/en/docs/img/index/index-01-swagger-ui-simple.png diff --git a/docs/img/index/index-02-redoc-simple.png b/docs/en/docs/img/index/index-02-redoc-simple.png similarity index 100% rename from docs/img/index/index-02-redoc-simple.png rename to docs/en/docs/img/index/index-02-redoc-simple.png diff --git a/docs/img/index/index-03-swagger-02.png b/docs/en/docs/img/index/index-03-swagger-02.png similarity index 100% rename from docs/img/index/index-03-swagger-02.png rename to docs/en/docs/img/index/index-03-swagger-02.png diff --git a/docs/img/index/index-04-swagger-03.png b/docs/en/docs/img/index/index-04-swagger-03.png similarity index 100% rename from docs/img/index/index-04-swagger-03.png rename to docs/en/docs/img/index/index-04-swagger-03.png diff --git a/docs/img/index/index-05-swagger-04.png b/docs/en/docs/img/index/index-05-swagger-04.png similarity index 100% rename from docs/img/index/index-05-swagger-04.png rename to docs/en/docs/img/index/index-05-swagger-04.png diff --git a/docs/img/index/index-06-redoc-02.png b/docs/en/docs/img/index/index-06-redoc-02.png similarity index 100% rename from docs/img/index/index-06-redoc-02.png rename to docs/en/docs/img/index/index-06-redoc-02.png diff --git a/docs/img/logo-margin/logo-teal-vector.svg b/docs/en/docs/img/logo-margin/logo-teal-vector.svg similarity index 100% rename from docs/img/logo-margin/logo-teal-vector.svg rename to docs/en/docs/img/logo-margin/logo-teal-vector.svg diff --git a/docs/img/logo-margin/logo-teal.png b/docs/en/docs/img/logo-margin/logo-teal.png similarity index 100% rename from docs/img/logo-margin/logo-teal.png rename to docs/en/docs/img/logo-margin/logo-teal.png diff --git a/docs/img/logo-margin/logo-teal.svg b/docs/en/docs/img/logo-margin/logo-teal.svg similarity index 100% rename from docs/img/logo-margin/logo-teal.svg rename to docs/en/docs/img/logo-margin/logo-teal.svg diff --git a/docs/img/logo-margin/logo-white-bg.png b/docs/en/docs/img/logo-margin/logo-white-bg.png similarity index 100% rename from docs/img/logo-margin/logo-white-bg.png rename to docs/en/docs/img/logo-margin/logo-white-bg.png diff --git a/docs/img/logo-teal-vector.svg b/docs/en/docs/img/logo-teal-vector.svg similarity index 100% rename from docs/img/logo-teal-vector.svg rename to docs/en/docs/img/logo-teal-vector.svg diff --git a/docs/img/logo-teal.svg b/docs/en/docs/img/logo-teal.svg similarity index 100% rename from docs/img/logo-teal.svg rename to docs/en/docs/img/logo-teal.svg diff --git a/docs/img/pycharm-completion.png b/docs/en/docs/img/pycharm-completion.png similarity index 100% rename from docs/img/pycharm-completion.png rename to docs/en/docs/img/pycharm-completion.png diff --git a/docs/img/python-types/image01.png b/docs/en/docs/img/python-types/image01.png similarity index 100% rename from docs/img/python-types/image01.png rename to docs/en/docs/img/python-types/image01.png diff --git a/docs/img/python-types/image02.png b/docs/en/docs/img/python-types/image02.png similarity index 100% rename from docs/img/python-types/image02.png rename to docs/en/docs/img/python-types/image02.png diff --git a/docs/img/python-types/image03.png b/docs/en/docs/img/python-types/image03.png similarity index 100% rename from docs/img/python-types/image03.png rename to docs/en/docs/img/python-types/image03.png diff --git a/docs/img/python-types/image04.png b/docs/en/docs/img/python-types/image04.png similarity index 100% rename from docs/img/python-types/image04.png rename to docs/en/docs/img/python-types/image04.png diff --git a/docs/img/python-types/image05.png b/docs/en/docs/img/python-types/image05.png similarity index 100% rename from docs/img/python-types/image05.png rename to docs/en/docs/img/python-types/image05.png diff --git a/docs/img/python-types/image06.png b/docs/en/docs/img/python-types/image06.png similarity index 100% rename from docs/img/python-types/image06.png rename to docs/en/docs/img/python-types/image06.png diff --git a/docs/img/tutorial/additional-responses/image01.png b/docs/en/docs/img/tutorial/additional-responses/image01.png similarity index 100% rename from docs/img/tutorial/additional-responses/image01.png rename to docs/en/docs/img/tutorial/additional-responses/image01.png diff --git a/docs/img/tutorial/async-sql-databases/image01.png b/docs/en/docs/img/tutorial/async-sql-databases/image01.png similarity index 100% rename from docs/img/tutorial/async-sql-databases/image01.png rename to docs/en/docs/img/tutorial/async-sql-databases/image01.png diff --git a/docs/en/docs/img/tutorial/behind-a-proxy/image01.png b/docs/en/docs/img/tutorial/behind-a-proxy/image01.png new file mode 100644 index 0000000000000..4ceae4421988a Binary files /dev/null and b/docs/en/docs/img/tutorial/behind-a-proxy/image01.png differ diff --git a/docs/en/docs/img/tutorial/behind-a-proxy/image02.png b/docs/en/docs/img/tutorial/behind-a-proxy/image02.png new file mode 100644 index 0000000000000..8012031401c83 Binary files /dev/null and b/docs/en/docs/img/tutorial/behind-a-proxy/image02.png differ diff --git a/docs/img/tutorial/bigger-applications/image01.png b/docs/en/docs/img/tutorial/bigger-applications/image01.png similarity index 100% rename from docs/img/tutorial/bigger-applications/image01.png rename to docs/en/docs/img/tutorial/bigger-applications/image01.png diff --git a/docs/img/tutorial/body-fields/image01.png b/docs/en/docs/img/tutorial/body-fields/image01.png similarity index 100% rename from docs/img/tutorial/body-fields/image01.png rename to docs/en/docs/img/tutorial/body-fields/image01.png diff --git a/docs/img/tutorial/body-nested-models/image01.png b/docs/en/docs/img/tutorial/body-nested-models/image01.png similarity index 100% rename from docs/img/tutorial/body-nested-models/image01.png rename to docs/en/docs/img/tutorial/body-nested-models/image01.png diff --git a/docs/img/tutorial/body/image01.png b/docs/en/docs/img/tutorial/body/image01.png similarity index 100% rename from docs/img/tutorial/body/image01.png rename to docs/en/docs/img/tutorial/body/image01.png diff --git a/docs/img/tutorial/body/image02.png b/docs/en/docs/img/tutorial/body/image02.png similarity index 100% rename from docs/img/tutorial/body/image02.png rename to docs/en/docs/img/tutorial/body/image02.png diff --git a/docs/img/tutorial/body/image03.png b/docs/en/docs/img/tutorial/body/image03.png similarity index 100% rename from docs/img/tutorial/body/image03.png rename to docs/en/docs/img/tutorial/body/image03.png diff --git a/docs/img/tutorial/body/image04.png b/docs/en/docs/img/tutorial/body/image04.png similarity index 100% rename from docs/img/tutorial/body/image04.png rename to docs/en/docs/img/tutorial/body/image04.png diff --git a/docs/img/tutorial/body/image05.png b/docs/en/docs/img/tutorial/body/image05.png similarity index 100% rename from docs/img/tutorial/body/image05.png rename to docs/en/docs/img/tutorial/body/image05.png diff --git a/docs/img/tutorial/custom-response/image01.png b/docs/en/docs/img/tutorial/custom-response/image01.png similarity index 100% rename from docs/img/tutorial/custom-response/image01.png rename to docs/en/docs/img/tutorial/custom-response/image01.png diff --git a/docs/img/tutorial/debugging/image01.png b/docs/en/docs/img/tutorial/debugging/image01.png similarity index 100% rename from docs/img/tutorial/debugging/image01.png rename to docs/en/docs/img/tutorial/debugging/image01.png diff --git a/docs/en/docs/img/tutorial/debugging/image02.png b/docs/en/docs/img/tutorial/debugging/image02.png new file mode 100644 index 0000000000000..8394f50e2d12d Binary files /dev/null and b/docs/en/docs/img/tutorial/debugging/image02.png differ diff --git a/docs/img/tutorial/dependencies/image01.png b/docs/en/docs/img/tutorial/dependencies/image01.png similarity index 100% rename from docs/img/tutorial/dependencies/image01.png rename to docs/en/docs/img/tutorial/dependencies/image01.png diff --git a/docs/img/tutorial/dependencies/image02.png b/docs/en/docs/img/tutorial/dependencies/image02.png similarity index 100% rename from docs/img/tutorial/dependencies/image02.png rename to docs/en/docs/img/tutorial/dependencies/image02.png diff --git a/docs/img/tutorial/extending-openapi/image01.png b/docs/en/docs/img/tutorial/extending-openapi/image01.png similarity index 100% rename from docs/img/tutorial/extending-openapi/image01.png rename to docs/en/docs/img/tutorial/extending-openapi/image01.png diff --git a/docs/img/tutorial/graphql/image01.png b/docs/en/docs/img/tutorial/graphql/image01.png similarity index 100% rename from docs/img/tutorial/graphql/image01.png rename to docs/en/docs/img/tutorial/graphql/image01.png diff --git a/docs/img/tutorial/application-configuration/image01.png b/docs/en/docs/img/tutorial/metadata/image01.png similarity index 100% rename from docs/img/tutorial/application-configuration/image01.png rename to docs/en/docs/img/tutorial/metadata/image01.png diff --git a/docs/img/tutorial/openapi-callbacks/image01.png b/docs/en/docs/img/tutorial/openapi-callbacks/image01.png similarity index 100% rename from docs/img/tutorial/openapi-callbacks/image01.png rename to docs/en/docs/img/tutorial/openapi-callbacks/image01.png diff --git a/docs/img/tutorial/path-operation-configuration/image01.png b/docs/en/docs/img/tutorial/path-operation-configuration/image01.png similarity index 100% rename from docs/img/tutorial/path-operation-configuration/image01.png rename to docs/en/docs/img/tutorial/path-operation-configuration/image01.png diff --git a/docs/img/tutorial/path-operation-configuration/image02.png b/docs/en/docs/img/tutorial/path-operation-configuration/image02.png similarity index 100% rename from docs/img/tutorial/path-operation-configuration/image02.png rename to docs/en/docs/img/tutorial/path-operation-configuration/image02.png diff --git a/docs/img/tutorial/path-operation-configuration/image03.png b/docs/en/docs/img/tutorial/path-operation-configuration/image03.png similarity index 100% rename from docs/img/tutorial/path-operation-configuration/image03.png rename to docs/en/docs/img/tutorial/path-operation-configuration/image03.png diff --git a/docs/img/tutorial/path-operation-configuration/image04.png b/docs/en/docs/img/tutorial/path-operation-configuration/image04.png similarity index 100% rename from docs/img/tutorial/path-operation-configuration/image04.png rename to docs/en/docs/img/tutorial/path-operation-configuration/image04.png diff --git a/docs/img/tutorial/path-operation-configuration/image05.png b/docs/en/docs/img/tutorial/path-operation-configuration/image05.png similarity index 100% rename from docs/img/tutorial/path-operation-configuration/image05.png rename to docs/en/docs/img/tutorial/path-operation-configuration/image05.png diff --git a/docs/img/tutorial/path-params/image01.png b/docs/en/docs/img/tutorial/path-params/image01.png similarity index 100% rename from docs/img/tutorial/path-params/image01.png rename to docs/en/docs/img/tutorial/path-params/image01.png diff --git a/docs/img/tutorial/path-params/image02.png b/docs/en/docs/img/tutorial/path-params/image02.png similarity index 100% rename from docs/img/tutorial/path-params/image02.png rename to docs/en/docs/img/tutorial/path-params/image02.png diff --git a/docs/img/tutorial/path-params/image03.png b/docs/en/docs/img/tutorial/path-params/image03.png similarity index 100% rename from docs/img/tutorial/path-params/image03.png rename to docs/en/docs/img/tutorial/path-params/image03.png diff --git a/docs/img/tutorial/query-params-str-validations/image01.png b/docs/en/docs/img/tutorial/query-params-str-validations/image01.png similarity index 100% rename from docs/img/tutorial/query-params-str-validations/image01.png rename to docs/en/docs/img/tutorial/query-params-str-validations/image01.png diff --git a/docs/img/tutorial/query-params-str-validations/image02.png b/docs/en/docs/img/tutorial/query-params-str-validations/image02.png similarity index 100% rename from docs/img/tutorial/query-params-str-validations/image02.png rename to docs/en/docs/img/tutorial/query-params-str-validations/image02.png diff --git a/docs/img/tutorial/response-model/image01.png b/docs/en/docs/img/tutorial/response-model/image01.png similarity index 100% rename from docs/img/tutorial/response-model/image01.png rename to docs/en/docs/img/tutorial/response-model/image01.png diff --git a/docs/img/tutorial/response-model/image02.png b/docs/en/docs/img/tutorial/response-model/image02.png similarity index 100% rename from docs/img/tutorial/response-model/image02.png rename to docs/en/docs/img/tutorial/response-model/image02.png diff --git a/docs/img/tutorial/response-status-code/image01.png b/docs/en/docs/img/tutorial/response-status-code/image01.png similarity index 100% rename from docs/img/tutorial/response-status-code/image01.png rename to docs/en/docs/img/tutorial/response-status-code/image01.png diff --git a/docs/img/tutorial/response-status-code/image02.png b/docs/en/docs/img/tutorial/response-status-code/image02.png similarity index 100% rename from docs/img/tutorial/response-status-code/image02.png rename to docs/en/docs/img/tutorial/response-status-code/image02.png diff --git a/docs/img/tutorial/security/image01.png b/docs/en/docs/img/tutorial/security/image01.png similarity index 100% rename from docs/img/tutorial/security/image01.png rename to docs/en/docs/img/tutorial/security/image01.png diff --git a/docs/img/tutorial/security/image02.png b/docs/en/docs/img/tutorial/security/image02.png similarity index 100% rename from docs/img/tutorial/security/image02.png rename to docs/en/docs/img/tutorial/security/image02.png diff --git a/docs/img/tutorial/security/image03.png b/docs/en/docs/img/tutorial/security/image03.png similarity index 100% rename from docs/img/tutorial/security/image03.png rename to docs/en/docs/img/tutorial/security/image03.png diff --git a/docs/img/tutorial/security/image04.png b/docs/en/docs/img/tutorial/security/image04.png similarity index 100% rename from docs/img/tutorial/security/image04.png rename to docs/en/docs/img/tutorial/security/image04.png diff --git a/docs/img/tutorial/security/image05.png b/docs/en/docs/img/tutorial/security/image05.png similarity index 100% rename from docs/img/tutorial/security/image05.png rename to docs/en/docs/img/tutorial/security/image05.png diff --git a/docs/img/tutorial/security/image06.png b/docs/en/docs/img/tutorial/security/image06.png similarity index 100% rename from docs/img/tutorial/security/image06.png rename to docs/en/docs/img/tutorial/security/image06.png diff --git a/docs/img/tutorial/security/image07.png b/docs/en/docs/img/tutorial/security/image07.png similarity index 100% rename from docs/img/tutorial/security/image07.png rename to docs/en/docs/img/tutorial/security/image07.png diff --git a/docs/img/tutorial/security/image08.png b/docs/en/docs/img/tutorial/security/image08.png similarity index 100% rename from docs/img/tutorial/security/image08.png rename to docs/en/docs/img/tutorial/security/image08.png diff --git a/docs/img/tutorial/security/image09.png b/docs/en/docs/img/tutorial/security/image09.png similarity index 100% rename from docs/img/tutorial/security/image09.png rename to docs/en/docs/img/tutorial/security/image09.png diff --git a/docs/img/tutorial/security/image10.png b/docs/en/docs/img/tutorial/security/image10.png similarity index 100% rename from docs/img/tutorial/security/image10.png rename to docs/en/docs/img/tutorial/security/image10.png diff --git a/docs/img/tutorial/security/image11.png b/docs/en/docs/img/tutorial/security/image11.png similarity index 100% rename from docs/img/tutorial/security/image11.png rename to docs/en/docs/img/tutorial/security/image11.png diff --git a/docs/img/tutorial/security/image12.png b/docs/en/docs/img/tutorial/security/image12.png similarity index 100% rename from docs/img/tutorial/security/image12.png rename to docs/en/docs/img/tutorial/security/image12.png diff --git a/docs/img/tutorial/sql-databases/image01.png b/docs/en/docs/img/tutorial/sql-databases/image01.png similarity index 100% rename from docs/img/tutorial/sql-databases/image01.png rename to docs/en/docs/img/tutorial/sql-databases/image01.png diff --git a/docs/img/tutorial/sql-databases/image02.png b/docs/en/docs/img/tutorial/sql-databases/image02.png similarity index 100% rename from docs/img/tutorial/sql-databases/image02.png rename to docs/en/docs/img/tutorial/sql-databases/image02.png diff --git a/docs/img/tutorial/sub-applications/image01.png b/docs/en/docs/img/tutorial/sub-applications/image01.png similarity index 100% rename from docs/img/tutorial/sub-applications/image01.png rename to docs/en/docs/img/tutorial/sub-applications/image01.png diff --git a/docs/img/tutorial/sub-applications/image02.png b/docs/en/docs/img/tutorial/sub-applications/image02.png similarity index 100% rename from docs/img/tutorial/sub-applications/image02.png rename to docs/en/docs/img/tutorial/sub-applications/image02.png diff --git a/docs/img/tutorial/websockets/image01.png b/docs/en/docs/img/tutorial/websockets/image01.png similarity index 100% rename from docs/img/tutorial/websockets/image01.png rename to docs/en/docs/img/tutorial/websockets/image01.png diff --git a/docs/img/tutorial/websockets/image02.png b/docs/en/docs/img/tutorial/websockets/image02.png similarity index 100% rename from docs/img/tutorial/websockets/image02.png rename to docs/en/docs/img/tutorial/websockets/image02.png diff --git a/docs/img/tutorial/websockets/image03.png b/docs/en/docs/img/tutorial/websockets/image03.png similarity index 100% rename from docs/img/tutorial/websockets/image03.png rename to docs/en/docs/img/tutorial/websockets/image03.png diff --git a/docs/img/tutorial/websockets/image04.png b/docs/en/docs/img/tutorial/websockets/image04.png similarity index 100% rename from docs/img/tutorial/websockets/image04.png rename to docs/en/docs/img/tutorial/websockets/image04.png diff --git a/docs/img/vscode-completion.png b/docs/en/docs/img/vscode-completion.png similarity index 100% rename from docs/img/vscode-completion.png rename to docs/en/docs/img/vscode-completion.png diff --git a/docs/index.md b/docs/en/docs/index.md similarity index 88% rename from docs/index.md rename to docs/en/docs/index.md index 8801c1af57b63..b74421fa9d5aa 100644 --- a/docs/index.md +++ b/docs/en/docs/index.md @@ -9,7 +9,7 @@ Build Status - Coverage + Coverage Package version @@ -33,7 +33,7 @@ The key features are: * **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). -* **Fast to code**: Increase the speed to develop features by about 200% to 300% *. +* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * * **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * * **Intuitive**: Great editor support. Completion everywhere. Less time debugging. * **Easy**: Designed to be easy to use and learn. Less time reading docs. @@ -45,37 +45,51 @@ The key features are: ## Opinions -"*[...] 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.*" +"_[...] 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)
--- -"*I’m over the moon excited about **FastAPI**. It’s so fun!*" +"_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!_"
Brian Okken - Python Bytes podcast host (ref)
--- -"*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.*" +"_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._"
Timothy Crosley - Hug creator (ref)
--- -"*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 [...]*" +"_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 [...]*" +"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
--- -"*We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]*" +## **Typer**, the FastAPI of CLIs -
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ ---- +If you are building a CLI app to be used in the terminal instead of a web API, check out **Typer**. + +**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀 ## Requirements @@ -88,16 +102,28 @@ FastAPI stands on the shoulders of giants: ## Installation -```bash -pip install fastapi +
+ +```console +$ pip install fastapi + +---> 100% ``` +
+ You will also need an ASGI server, for production such as Uvicorn or Hypercorn. -```bash -pip install uvicorn +
+ +```console +$ pip install uvicorn + +---> 100% ``` +
+ ## Example ### Create it @@ -151,10 +177,20 @@ If you don't know, check the _"In a hurry?"_ section about + +```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. ``` + +
About the command uvicorn main:app --reload... diff --git a/docs/en/docs/js/chat.js b/docs/en/docs/js/chat.js new file mode 100644 index 0000000000000..debdef4dad5d0 --- /dev/null +++ b/docs/en/docs/js/chat.js @@ -0,0 +1,3 @@ +((window.gitter = {}).chat = {}).options = { + room: 'tiangolo/fastapi' +}; diff --git a/docs/en/docs/js/custom.js b/docs/en/docs/js/custom.js new file mode 100644 index 0000000000000..72140df8ba8b8 --- /dev/null +++ b/docs/en/docs/js/custom.js @@ -0,0 +1,149 @@ +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 +} + +function setupTermynal() { + document.querySelectorAll(".use-termynal").forEach(node => { + node.style.display = "block"; + new Termynal(node, { + lineDelay: 500 + }); + }); + const progressLiteralStart = "---> 100%"; + const promptLiteralStart = "$ "; + const customPromptLiteralStart = "# "; + const termynalActivateClass = "termy"; + let termynals = []; + + function createTermynals() { + document + .querySelectorAll(`.${termynalActivateClass} .highlight`) + .forEach(node => { + const text = node.textContent; + const lines = text.split("\n"); + const useLines = []; + let buffer = []; + function saveBuffer() { + if (buffer.length) { + let isBlankSpace = true; + buffer.forEach(line => { + if (line) { + isBlankSpace = false; + } + }); + dataValue = {}; + if (isBlankSpace) { + dataValue["delay"] = 0; + } + if (buffer[buffer.length - 1] === "") { + // A last single
won't have effect + // so put an additional one + buffer.push(""); + } + const bufferValue = buffer.join("
"); + dataValue["value"] = bufferValue; + useLines.push(dataValue); + buffer = []; + } + } + for (let line of lines) { + if (line === progressLiteralStart) { + saveBuffer(); + useLines.push({ + type: "progress" + }); + } else if (line.startsWith(promptLiteralStart)) { + saveBuffer(); + const value = line.replace(promptLiteralStart, "").trimEnd(); + useLines.push({ + type: "input", + value: value + }); + } else if (line.startsWith("// ")) { + saveBuffer(); + const value = "💬 " + line.replace("// ", "").trimEnd(); + useLines.push({ + value: value, + class: "termynal-comment", + delay: 0 + }); + } else if (line.startsWith(customPromptLiteralStart)) { + saveBuffer(); + const promptStart = line.indexOf(promptLiteralStart); + if (promptStart === -1) { + console.error("Custom prompt found but no end delimiter", line) + } + const prompt = line.slice(0, promptStart).replace(customPromptLiteralStart, "") + let value = line.slice(promptStart + promptLiteralStart.length); + useLines.push({ + type: "input", + value: value, + prompt: prompt + }); + } else { + buffer.push(line); + } + } + saveBuffer(); + const div = document.createElement("div"); + node.replaceWith(div); + const termynal = new Termynal(div, { + lineData: useLines, + noInit: true, + lineDelay: 500 + }); + termynals.push(termynal); + }); + } + + function loadVisibleTermynals() { + termynals = termynals.filter(termynal => { + if (termynal.container.getBoundingClientRect().top - innerHeight <= 0) { + termynal.init(); + return false; + } + return true; + }); + } + window.addEventListener("scroll", loadVisibleTermynals); + createTermynals(); + loadVisibleTermynals(); +} + +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) + }) + } + + setupTermynal(); +} + +main() diff --git a/docs/en/docs/js/termynal.js b/docs/en/docs/js/termynal.js new file mode 100644 index 0000000000000..8b0e9339e8772 --- /dev/null +++ b/docs/en/docs/js/termynal.js @@ -0,0 +1,264 @@ +/** + * termynal.js + * A lightweight, modern and extensible animated terminal window, using + * async/await. + * + * @author Ines Montani + * @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. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Documentación alternativa de la API con ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### 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: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* en PyCharm: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +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 +

    +

    + FastAPI framework, alto desempeño, fácil de aprender, rápido de programar, listo para producción +

    +

    + + Build Status + + + Coverage + + + Package version + + + Join the chat at https://gitter.im/tiangolo/fastapi + +

    + +--- + +**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!_" + +
    Brian Okken - Python Bytes podcast host (ref)
    + +--- + +"_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._" + +
    Timothy Crosley - Hug creator (ref)
    + +--- + +"_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 [...]_" + +
    Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
    + +--- + +## **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): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### 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): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## 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: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Haz clíck en el botón de "Try it out" que te permite llenar los parámetros e interactuar directamente con la API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* 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: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### 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: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### 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: + +![soporte de editor](https://fastapi.tiangolo.com/img/vscode-completion.png) + +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. + +![Interação Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Documentação alternativa da API com ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### 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: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* no PyCharm: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +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 @@ +

      + FastAPI +

      +

      + Framework FastAPI, alta performance, fácil de aprender, fácil de codar, pronto para produção +

      +

      + + Build Status + + + Coverage + + + Package version + + + Join the chat at https://gitter.im/tiangolo/fastapi + +

      + +--- + +**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!*" + +
      Brian Okken - Python Bytes podcaster (ref)
      + +--- + +"*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.*" + +
      Timothy Crosley - criador doHug (ref)
      + +--- + +"*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 [...]*" + +
      Ines Montani - Matthew Honnibal - fundadores da Explosion AI - criadores da spaCy (ref) - (ref)
      + +--- + +"*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): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### 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): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## 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: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Clique no botão "Try it out", ele permiirá que você preencha os parâmetros e interaja diretamente com a API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* 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: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### 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: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### 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: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +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 提供): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### 可选的 API 文档 + +你也可以访问 http://192.168.99.100/redoc 或者 http://127.0.0.1/redoc (或者类似的,使用Docker主机)。 + +你将看到一个可选的自动化文档(由 ReDoc 提供) + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## 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 。 + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* 另外的 API 文档:ReDoc + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### 更主流的 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 中: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* PyCharm 中: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +你将能进行代码补全,这是在之前你可能曾认为不可能的事。例如,在来自请求 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 +

      +

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

      +

      + + Build Status + + + Coverage + + + Package version + + + Join the chat at https://gitter.im/tiangolo/fastapi + +

      + +--- + +**文档**: 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** 产品。*" + +
      Kabir Khan - 微软 (ref)
      + +--- + +"***FastAPI** 让我兴奋的欣喜若狂。它太棒了!*" + +
      Brian Okken - Python Bytes 播客主持人 (ref)
      + +--- + +"*老实说,你的作品看起来非常可靠和优美。在很多方面,这就是我想让 **Hug** 成为的样子 - 看到有人实现了它真的很鼓舞人心。*" + +
      Timothy Crosley - Hug 作者 (ref)
      + +--- + +"*如果你正打算学习一个**现代框架**用来构建 REST API,来看下 **FastAPI** [...] 它快速、易用且易于学习 [...]*" + +"*我们已经将 **API** 服务切换到了 **FastAPI** [...] 我认为你会喜欢它的 [...]*" + +
      Ines Montani - Matthew Honnibal - Explosion AI 创始人 - spaCy 作者 (ref) - (ref)
      + +--- + +"*我们采用了 **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生成): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### 备选 API 文档 + +访问 http://127.0.0.1:8000/redoc。 + +你会看到另一个自动生成的文档(由 ReDoc)生成: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## 升级示例 + +修改 `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 文档将会自动更新,并加入新的请求体: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* 点击 "Try it out" 按钮,之后你可以填写参数并直接调用 API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* 然后点击 "Execute" 按钮,用户界面将会和 API 进行通信,发送参数,获取结果并在屏幕上展示: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### 升级备选文档 + +访问 http://127.0.0.1:8000/redoc。 + +* 备选文档同样会体现新加入的请求参数和请求体: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### 回顾 + +总的来说,你就像声明函数的参数类型一样只声明了**一次**请求参数、请求体等的类型。 + +你使用了标准的现代 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 ... +``` + +......注意观察编辑器是如何自动补全属性并且还知道它们的类型: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +教程 - 用户指南 中有包含更多特性的更完整示例。 + +**剧透警告**: 教程 - 用户指南中的内容有: + +* 对来自不同地方的参数进行声明,如:**请求头**、**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"Item ID: foo" in response.content response = client.get("/static/styles.css") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert b"color: green;" in response.content shutil.rmtree("./templates") shutil.rmtree("./static") diff --git a/tests/test_tutorial/test_testing/test_main.py b/tests/test_tutorial/test_testing/test_main.py index 36e8069a5263f..6ef800f6ed44e 100644 --- a/tests/test_tutorial/test_testing/test_main.py +++ b/tests/test_tutorial/test_testing/test_main.py @@ -22,7 +22,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_testing/test_tutorial001.py b/tests/test_tutorial/test_testing/test_tutorial001.py index adc6928c63b4e..66863b94512f5 100644 --- a/tests/test_tutorial/test_testing/test_tutorial001.py +++ b/tests/test_tutorial/test_testing/test_tutorial001.py @@ -22,7 +22,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_testing_dependencies/test_tutorial001.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py index 093c6499a8c0e..dccace562e2d0 100644 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py +++ b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py @@ -21,7 +21,7 @@ def test_override_in_items_with_params_run(): def test_override_in_users(): response = client.get("/users/") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.json() == { "message": "Hello Users!", "params": {"q": None, "skip": 5, "limit": 10}, @@ -30,7 +30,7 @@ def test_override_in_users(): def test_override_in_users_with_q(): response = client.get("/users/?q=foo") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.json() == { "message": "Hello Users!", "params": {"q": "foo", "skip": 5, "limit": 10}, @@ -39,7 +39,7 @@ def test_override_in_users_with_q(): def test_override_in_users_with_params(): response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.json() == { "message": "Hello Users!", "params": {"q": "foo", "skip": 5, "limit": 10}, @@ -49,7 +49,7 @@ def test_override_in_users_with_params(): def test_normal_app(): app.dependency_overrides = None response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 100, "limit": 200}, diff --git a/tests/test_tutorial/test_websockets/test_tutorial001.py b/tests/test_tutorial/test_websockets/test_tutorial001.py index b30ecf477bead..6c715b19495a2 100644 --- a/tests/test_tutorial/test_websockets/test_tutorial001.py +++ b/tests/test_tutorial/test_websockets/test_tutorial001.py @@ -8,7 +8,7 @@ def test_main(): response = client.get("/") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert b"" in response.content diff --git a/tests/test_tutorial/test_websockets/test_tutorial002.py b/tests/test_tutorial/test_websockets/test_tutorial002.py index 9e3e45edb4193..640691cd3e169 100644 --- a/tests/test_tutorial/test_websockets/test_tutorial002.py +++ b/tests/test_tutorial/test_websockets/test_tutorial002.py @@ -8,7 +8,7 @@ def test_main(): response = client.get("/") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert b"" in response.content diff --git a/tests/test_tutorial/test_wsgi/test_tutorial001.py b/tests/test_tutorial/test_wsgi/test_tutorial001.py index e5390fced45b7..8eee4d465ae30 100644 --- a/tests/test_tutorial/test_wsgi/test_tutorial001.py +++ b/tests/test_tutorial/test_wsgi/test_tutorial001.py @@ -7,11 +7,11 @@ def test_flask(): response = client.get("/v1/") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.text == "Hello, World from Flask!" def test_app(): response = client.get("/v2") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.json() == {"message": "Hello World"} diff --git a/tests/test_union_body.py b/tests/test_union_body.py index e043041708119..d1dfd5efbad2c 100644 --- a/tests/test_union_body.py +++ b/tests/test_union_body.py @@ -108,17 +108,17 @@ def save_union_body(item: Union[OtherItem, Item]): def test_item_openapi_schema(): response = client.get("/openapi.json") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.json() == item_openapi_schema def test_post_other_item(): response = client.post("/items/", json={"price": 100}) - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.json() == {"item": {"price": 100}} def test_post_item(): response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.json() == {"item": {"name": "Foo"}} diff --git a/tests/test_union_inherited_body.py b/tests/test_union_inherited_body.py index b901f28e72fb6..a1a3f0ed5b5b7 100644 --- a/tests/test_union_inherited_body.py +++ b/tests/test_union_inherited_body.py @@ -121,19 +121,19 @@ def save_union_different_body(item: Union[ExtendedItem, Item]): @skip_py36 def test_inherited_item_openapi_schema(): response = client.get("/openapi.json") - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.json() == inherited_item_openapi_schema @skip_py36 def test_post_extended_item(): 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}} @skip_py36 def test_post_item(): response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200 + assert response.status_code == 200, response.text assert response.json() == {"item": {"name": "Foo"}} diff --git a/tests/test_validate_response_recursive.py b/tests/test_validate_response_recursive.py new file mode 100644 index 0000000000000..3a4b10e0ca9f4 --- /dev/null +++ b/tests/test_validate_response_recursive.py @@ -0,0 +1,80 @@ +from typing import List + +from fastapi import FastAPI +from fastapi.testclient import TestClient +from pydantic import BaseModel + +app = FastAPI() + + +class RecursiveItem(BaseModel): + sub_items: List["RecursiveItem"] = [] + name: str + + +RecursiveItem.update_forward_refs() + + +class RecursiveSubitemInSubmodel(BaseModel): + sub_items2: List["RecursiveItemViaSubmodel"] = [] + name: str + + +class RecursiveItemViaSubmodel(BaseModel): + sub_items1: List[RecursiveSubitemInSubmodel] = [] + name: str + + +RecursiveSubitemInSubmodel.update_forward_refs() + + +@app.get("/items/recursive", response_model=RecursiveItem) +def get_recursive(): + return {"name": "item", "sub_items": [{"name": "subitem", "sub_items": []}]} + + +@app.get("/items/recursive-submodel", response_model=RecursiveItemViaSubmodel) +def get_recursive_submodel(): + return { + "name": "item", + "sub_items1": [ + { + "name": "subitem", + "sub_items2": [ + { + "name": "subsubitem", + "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], + } + ], + } + ], + } + + +client = TestClient(app) + + +def test_recursive(): + response = client.get("/items/recursive") + assert response.status_code == 200, response.text + assert response.json() == { + "sub_items": [{"name": "subitem", "sub_items": []}], + "name": "item", + } + + response = client.get("/items/recursive-submodel") + assert response.status_code == 200, response.text + assert response.json() == { + "name": "item", + "sub_items1": [ + { + "name": "subitem", + "sub_items2": [ + { + "name": "subsubitem", + "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], + } + ], + } + ], + } diff --git a/tests/test_ws_router.py b/tests/test_ws_router.py index fd19e650a9ace..dd0456127222a 100644 --- a/tests/test_ws_router.py +++ b/tests/test_ws_router.py @@ -1,4 +1,4 @@ -from fastapi import APIRouter, FastAPI, WebSocket +from fastapi import APIRouter, Depends, FastAPI, WebSocket from fastapi.testclient import TestClient router = APIRouter() @@ -34,6 +34,19 @@ async def routerindex(websocket: WebSocket): await websocket.close() +async def ws_dependency(): + return "Socket Dependency" + + +@router.websocket("/router-ws-depends/") +async def router_ws_decorator_depends( + websocket: WebSocket, data=Depends(ws_dependency) +): + await websocket.accept() + await websocket.send_text(data) + await websocket.close() + + app.include_router(router) app.include_router(prefix_router, prefix="/prefix") @@ -64,3 +77,16 @@ def test_router2(): with client.websocket_connect("/router2") as websocket: data = websocket.receive_text() assert data == "Hello, router!" + + +def test_router_ws_depends(): + client = TestClient(app) + with client.websocket_connect("/router-ws-depends/") as websocket: + assert websocket.receive_text() == "Socket Dependency" + + +def test_router_ws_depends_with_override(): + client = TestClient(app) + app.dependency_overrides[ws_dependency] = lambda: "Override" + with client.websocket_connect("/router-ws-depends/") as websocket: + assert websocket.receive_text() == "Override"