```console
-$ pip install fastapi[all]
+$ pip install "fastapi[all]"
---> 100%
```
@@ -62,7 +62,7 @@ $ pip install fastapi[all]
También debes instalar `uvicorn` para que funcione como tu servidor:
```
- pip install uvicorn[standard]
+ pip install "uvicorn[standard]"
```
Y lo mismo para cada una de las dependencias opcionales que quieras utilizar.
diff --git a/docs/es/mkdocs.yml b/docs/es/mkdocs.yml
index b544f9b387ad8..d1d6215b693a2 100644
--- a/docs/es/mkdocs.yml
+++ b/docs/es/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -83,6 +85,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -115,6 +119,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -133,6 +139,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md
index fd52f994c83a9..0f7cd569aec1e 100644
--- a/docs/fa/docs/index.md
+++ b/docs/fa/docs/index.md
@@ -1,16 +1,12 @@
-
-{!../../../docs/missing-translation.md!}
-
-
- FastAPI framework, high performance, easy to learn, fast to code, ready for production
+ فریمورک FastAPI، کارایی بالا، یادگیری آسان، کدنویسی سریع، آماده برای استفاده در محیط پروداکشن
-
-
+
+
@@ -25,103 +21,99 @@
---
-**Documentation**: https://fastapi.tiangolo.com
+**مستندات**: https://fastapi.tiangolo.com
-**Source Code**: https://github.com/tiangolo/fastapi
+**کد منبع**: https://github.com/tiangolo/fastapi
---
+FastAPI یک وب فریمورک مدرن و سریع (با کارایی بالا) برای ایجاد APIهای متنوع (وب، وبسوکت و غبره) با زبان پایتون نسخه +۳.۶ است. این فریمورک با رعایت کامل راهنمای نوع داده (Type Hint) ایجاد شده است.
-FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
+ویژگیهای کلیدی این فریمورک عبارتند از:
-The key features are:
+* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#performance).
-* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
+* **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه فابلیتهای جدید. *
+* **باگ کمتر**: کاهش ۴۰ درصدی خطاهای انسانی (برنامهنویسی). *
+* **غریزی**: پشتیبانی فوقالعاده در محیطهای توسعه یکپارچه (IDE). تکمیل در همه بخشهای کد. کاهش زمان رفع باگ.
+* **آسان**: طراحی شده برای یادگیری و استفاده آسان. کاهش زمان مورد نیاز برای مراجعه به مستندات.
+* **کوچک**: کاهش تکرار در کد. چندین قابلیت برای هر پارامتر (منظور پارامترهای ورودی تابع هندلر میباشد، به بخش خلاصه در همین صفحه مراجعه شود). باگ کمتر.
+* **استوار**: ایجاد کدی آماده برای استفاده در محیط پروداکشن و تولید خودکار مستندات تعاملی
+* **مبتنی بر استانداردها**: مبتنی بر (و منطبق با) استانداردهای متن باز مربوط به API: OpenAPI (سوگر سابق) و JSON Schema.
-* **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.
-* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
-* **Robust**: Get production-ready code. With automatic interactive documentation.
-* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.
+* تخمینها بر اساس تستهای انجام شده در یک تیم توسعه داخلی که مشغول ایجاد برنامههای کاربردی واقعی بودند صورت گرفته است.
-* estimation based on tests on an internal development team, building production applications.
-
-## Sponsors
+## اسپانسرهای طلایی
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
-
-{% endfor -%}
-{%- for sponsor in sponsors.silver -%}
-
+
{% endfor %}
{% endif %}
-Other sponsors
+دیگر اسپانسرها
-## Opinions
+## نظر دیگران در مورد FastAPI
-"_[...] 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)
---
-"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
+
"We adopted the FastAPI library to spawn a RESTserver 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**]_"
+
"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!_"
+
"I’m over the moon excited about FastAPI. It’s so fun!"
---
-"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
+
"Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted Hug to be - it's really inspiring to see someone build that."
---
-"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
+
"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 [...]"
---
-## **Typer**, the FastAPI of CLIs
+## **Typer**, فریمورکی معادل FastAPI برای کار با
واسط خط فرمان
-If you are building a
CLI app to be used in the terminal instead of a web API, check out
**Typer**.
+اگر در حال ساختن برنامهای برای استفاده در
CLI (به جای استفاده در وب) هستید، میتوانید از
**Typer**. استفاده کنید.
-**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
+**Typer** دوقلوی کوچکتر FastAPI است و قرار است معادلی برای FastAPI در برنامههای CLI باشد.️ 🚀
-## Requirements
+## نیازمندیها
-Python 3.6+
+پایتون +۳.۶
-FastAPI stands on the shoulders of giants:
+FastAPI مبتنی بر ابزارهای قدرتمند زیر است:
-*
Starlette for the web parts.
-*
Pydantic for the data parts.
+* فریمورک
Starlette برای بخش وب.
+* کتابخانه
Pydantic برای بخش داده.
-## Installation
+## نصب
@@ -133,7 +125,7 @@ $ pip install fastapi
-You will also need an ASGI server, for production such as
Uvicorn or
Hypercorn.
+نصب یک سرور پروداکشن نظیر
Uvicorn یا
Hypercorn نیز جزء نیازمندیهاست.
@@ -145,14 +137,13 @@ $ pip install "uvicorn[standard]"
-## Example
-
-### Create it
+## مثال
-* Create a file `main.py` with:
+### ایجاد کنید
+* فایلی به نام `main.py` با محتوای زیر ایجاد کنید :
```Python
-from typing import Union
+from typing import Optional
from fastapi import FastAPI
@@ -170,12 +161,12 @@ def read_item(item_id: int, q: Union[str, None] = None):
```
-Or use async def
...
+همچنین میتوانید از async def
... نیز استفاده کنید
-If your code uses `async` / `await`, use `async def`:
+اگر در کدتان از `async` / `await` استفاده میکنید, از `async def` برای تعریف تابع خود استفاده کنید:
```Python hl_lines="9 14"
-from typing import Union
+from typing import Optional
from fastapi import FastAPI
@@ -188,19 +179,20 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Union[str, None] = None):
+async def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
```
-**Note**:
+**توجه**:
+
+اگر با `async / await` آشنا نیستید، به بخش _"عجله دارید?"_ در صفحه درباره `async` و `await` در مستندات مراجعه کنید.
-If you don't know, check the _"In a hurry?"_ section about `async` and `await` in the docs.
-### Run it
+### اجرا کنید
-Run the server with:
+با استفاده از دستور زیر سرور را اجرا کنید:
@@ -217,57 +209,57 @@ INFO: Application startup complete.
-About the command uvicorn main:app --reload
...
+درباره دستور uvicorn main:app --reload
...
-The command `uvicorn main:app` refers to:
+دستور `uvicorn main:app` شامل موارد زیر است:
-* `main`: the file `main.py` (the Python "module").
-* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
-* `--reload`: make the server restart after code changes. Only do this for development.
+* `main`: فایل `main.py` (ماژول پایتون ایجاد شده).
+* `app`: شیء ایجاد شده در فایل `main.py` در خط `app = FastAPI()`.
+* `--reload`: ریستارت کردن سرور با تغییر کد. تنها در هنگام توسعه از این گزینه استفاده شود..
-### Check it
+### بررسی کنید
-Open your browser at
http://127.0.0.1:8000/items/5?q=somequery.
+آدرس
http://127.0.0.1:8000/items/5?q=somequery را در مرورگر خود باز کنید.
-You will see the JSON response as:
+پاسخ JSON زیر را مشاهده خواهید کرد:
```JSON
{"item_id": 5, "q": "somequery"}
```
-You already created an API that:
+تا اینجا شما APIای ساختید که:
-* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
-* Both _paths_ take `GET`
operations (also known as HTTP _methods_).
-* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
-* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.
+* درخواستهای HTTP به _مسیرهای_ `/` و `/items/{item_id}` را دریافت میکند.
+* هردو _مسیر_
عملیات (یا HTTP _متد_) `GET` را پشتیبانی میکنند.
+* _مسیر_ `/items/{item_id}` شامل
_پارامتر مسیر_ `item_id` از نوع `int` است.
+* _مسیر_ `/items/{item_id}` شامل
_پارامتر پرسمان_ اختیاری `q` از نوع `str` است.
-### Interactive API docs
+### مستندات API تعاملی
-Now go to
http://127.0.0.1:8000/docs.
+حال به آدرس
http://127.0.0.1:8000/docs بروید.
-You will see the automatic interactive API documentation (provided by
Swagger UI):
+مستندات API تعاملی (ایجاد شده به کمک
Swagger UI) را مشاهده خواهید کرد:
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
-### Alternative API docs
+### مستندات API جایگزین
-And now, go to
http://127.0.0.1:8000/redoc.
+حال به آدرس
http://127.0.0.1:8000/redoc بروید.
-You will see the alternative automatic documentation (provided by
ReDoc):
+مستندات خودکار دیگری را مشاهده خواهید کرد که به کمک
ReDoc ایجاد میشود:
![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
-## Example upgrade
+## تغییر مثال
-Now modify the file `main.py` to receive a body from a `PUT` request.
+حال فایل `main.py` را مطابق زیر ویرایش کنید تا بتوانید
بدنه یک درخواست `PUT` را دریافت کنید.
-Declare the body using standard Python types, thanks to Pydantic.
+به کمک Pydantic بدنه درخواست را با
انواع استاندارد پایتون تعریف کنید.
```Python hl_lines="4 9-12 25-27"
-from typing import Union
+from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
@@ -296,173 +288,175 @@ def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
```
-The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
+سرور به صورت خودکار ریاستارت میشود (زیرا پیشتر از گزینه `--reload` در دستور `uvicorn` استفاده کردیم).
-### Interactive API docs upgrade
+### تغییر مستندات API تعاملی
-Now go to
http://127.0.0.1:8000/docs.
+مجددا به آدرس
http://127.0.0.1:8000/docs بروید.
-* The interactive API documentation will be automatically updated, including the new body:
+* مستندات API تعاملی به صورت خودکار بهروز شده است و شامل بدنه تعریف شده در مرحله قبل است:
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
-* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
+* روی دکمه "Try it out" کلیک کنید, اکنون میتوانید پارامترهای مورد نیاز هر API را مشخص کرده و به صورت مستقیم با آنها تعامل کنید:
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)
-* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
+* سپس روی دکمه "Execute" کلیک کنید, خواهید دید که واسط کاریری با APIهای تعریف شده ارتباط برقرار کرده، پارامترهای مورد نیاز را به آنها ارسال میکند، سپس نتایج را دریافت کرده و در صفحه نشان میدهد:
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)
-### Alternative API docs upgrade
+### تغییر مستندات API جایگزین
-And now, go to
http://127.0.0.1:8000/redoc.
+حال به آدرس
http://127.0.0.1:8000/redoc بروید.
-* The alternative documentation will also reflect the new query parameter and body:
+* خواهید دید که مستندات جایگزین نیز بهروزرسانی شده و شامل پارامتر پرسمان و بدنه تعریف شده میباشد:
![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)
-### Recap
+### خلاصه
-In summary, you declare **once** the types of parameters, body, etc. as function parameters.
+به طور خلاصه شما **یک بار** انواع پارامترها، بدنه و غیره را به عنوان پارامترهای ورودی تابع خود تعریف میکنید.
-You do that with standard modern Python types.
+ این کار را با استفاده از انواع استاندارد و مدرن موجود در پایتون انجام میدهید.
-You don't have to learn a new syntax, the methods or classes of a specific library, etc.
+نیازی به یادگیری
نحو جدید یا متدها و کلاسهای یک کتابخانه بخصوص و غیره نیست.
-Just standard **Python 3.6+**.
+تنها **پایتون +۳.۶**.
-For example, for an `int`:
+به عنوان مثال برای یک پارامتر از نوع `int`:
```Python
item_id: int
```
-or for a more complex `Item` model:
+یا برای یک مدل پیچیدهتر مثل `Item`:
```Python
item: Item
```
-...and with that single declaration you get:
+...و با همین اعلان تمامی قابلیتهای زیر در دسترس قرار میگیرد:
-* Editor support, including:
- * Completion.
- * Type checks.
-* Validation of data:
- * Automatic and clear errors when the data is invalid.
- * Validation even for deeply nested JSON objects.
-*
Conversion of input data: coming from the network to Python data and types. Reading from:
+* پشتیبانی ویرایشگر متنی شامل:
+ * تکمیل کد.
+ * بررسی انواع داده.
+* اعتبارسنجی داده:
+ * خطاهای خودکار و مشخص در هنگام نامعتبر بودن داده
+ * اعتبارسنجی، حتی برای اشیاء JSON تو در تو.
+*
تبدیل داده ورودی: که از شبکه رسیده به انواع و داده پایتونی. این داده شامل:
* JSON.
- * Path parameters.
- * Query parameters.
- * Cookies.
- * Headers.
- * Forms.
- * Files.
-*
Conversion of output data: converting from Python data and types to network data (as JSON):
- * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
- * `datetime` objects.
- * `UUID` objects.
- * Database models.
- * ...and many more.
-* Automatic interactive API documentation, including 2 alternative user interfaces:
+ *
پارامترهای مسیر.
+ *
پارامترهای پرسمان.
+ *
کوکیها.
+ *
سرآیندها (هدرها).
+ *
فرمها.
+ *
فایلها.
+*
تبدیل داده خروجی: تبدیل از انواع و داده پایتون به داده شبکه (مانند JSON):
+ * تبدیل انواع داده پایتونی (`str`, `int`, `float`, `bool`, `list` و غیره).
+ * اشیاء `datetime`.
+ * اشیاء `UUID`.
+ * qمدلهای پایگاهداده.
+ * و موارد بیشمار دیگر.
+* دو مدل مستند API تعاملی خودکار :
* Swagger UI.
* ReDoc.
---
-Coming back to the previous code example, **FastAPI** will:
-
-* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
-* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
- * If it is not, the client will see a useful, clear error.
-* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests.
- * As the `q` parameter is declared with `= None`, it is optional.
- * Without the `None` it would be required (as is the body in the case with `PUT`).
-* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
- * Check that it has a required attribute `name` that should be a `str`.
- * Check that it has a required attribute `price` that has to be a `float`.
- * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
- * All this would also work for deeply nested JSON objects.
-* Convert from and to JSON automatically.
-* Document everything with OpenAPI, that can be used by:
- * Interactive documentation systems.
- * Automatic client code generation systems, for many languages.
-* Provide 2 interactive documentation web interfaces directly.
+به مثال قبلی باز میگردیم، در این مثال **FastAPI** موارد زیر را انجام میدهد:
+
+* اعتبارسنجی اینکه پارامتر `item_id` در مسیر درخواستهای `GET` و `PUT` موجود است .
+* اعتبارسنجی اینکه پارامتر `item_id` در درخواستهای `GET` و `PUT` از نوع `int` است.
+ * اگر غیر از این موارد باشد، سرویسگیرنده خطای مفید و مشخصی دریافت خواهد کرد.
+* بررسی وجود پارامتر پرسمان اختیاری `q` (مانند `http://127.0.0.1:8000/items/foo?q=somequery`) در درخواستهای `GET`.
+ * از آنجا که پارامتر `q` با `= None` مقداردهی شده است, این پارامتر اختیاری است.
+ * اگر از مقدار اولیه `None` استفاده نکنیم، این پارامتر الزامی خواهد بود (همانند بدنه درخواست در درخواست `PUT`).
+* برای درخواستهای `PUT` به آدرس `/items/{item_id}`, بدنه درخواست باید از نوع JSON تعریف شده باشد:
+ * بررسی اینکه بدنه شامل فیلدی با نام `name` و از نوع `str` است.
+ * بررسی اینکه بدنه شامل فیلدی با نام `price` و از نوع `float` است.
+ * بررسی اینکه بدنه شامل فیلدی اختیاری با نام `is_offer` است, که در صورت وجود باید از نوع `bool` باشد.
+ * تمامی این موارد برای اشیاء JSON در هر عمقی قابل بررسی میباشد.
+* تبدیل از/به JSON به صورت خودکار.
+* مستندسازی همه چیز با استفاده از OpenAPI, که میتوان از آن برای موارد زیر استفاده کرد:
+ * سیستم مستندات تعاملی.
+ * تولید خودکار کد سرویسگیرنده در زبانهای برنامهنویسی بیشمار.
+* فراهم سازی ۲ مستند تعاملی مبتنی بر وب به صورت پیشفرض .
---
-We just scratched the surface, but you already get the idea of how it all works.
+موارد ذکر شده تنها پارهای از ویژگیهای بیشمار FastAPI است اما ایدهای کلی از طرز کار آن در اختیار قرار میدهد.
-Try changing the line with:
+خط زیر را به این صورت تغییر دهید:
```Python
return {"item_name": item.name, "item_id": item_id}
```
-...from:
+از:
```Python
... "item_name": item.name ...
```
-...to:
+به:
```Python
... "item_price": item.price ...
```
-...and see how your editor will auto-complete the attributes and know their types:
+در حین تایپ کردن توجه کنید که چگونه ویرایشگر، ویژگیهای کلاس `Item` را تشخیص داده و به تکمیل خودکار آنها کمک میکند:
![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
-For a more complete example including more features, see the
Tutorial - User Guide.
+برای مشاهده مثالهای کاملتر که شامل قابلیتهای بیشتری از FastAPI باشد به بخش
آموزش - راهنمای کاربر مراجعه کنید.
-**Spoiler alert**: the tutorial - user guide includes:
+**هشدار اسپویل**: بخش آموزش - راهنمای کاربر شامل موارد زیر است:
-* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
-* How to set **validation constraints** as `maximum_length` or `regex`.
-* A very powerful and easy to use **
Dependency Injection** system.
-* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
-* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
-* **GraphQL** integration with
Strawberry and other libraries.
-* Many extra features (thanks to Starlette) as:
- * **WebSockets**
- * extremely easy tests based on `requests` and `pytest`
+* اعلان **پارامترهای** موجود در بخشهای دیگر درخواست، شامل: **سرآیند (هدر)ها**, **کوکیها**, **فیلدهای فرم** و **فایلها**.
+* چگونگی تنظیم **
محدودیتهای اعتبارسنجی** به عنوان مثال `maximum_length` یا `regex`.
+* سیستم **
Dependency Injection** قوی و کاربردی.
+* امنیت و تایید هویت, شامل پشتیبانی از **OAuth2** مبتنی بر **JWT tokens** و **HTTP Basic**.
+* تکنیک پیشرفته برای تعریف **مدلهای چند سطحی JSON** (بر اساس Pydantic).
+* قابلیتهای اضافی دیگر (بر اساس Starlette) شامل:
+ * **
وبسوکت**
+ * **GraphQL**
+ * تستهای خودکار آسان مبتنی بر `requests` و `pytest`
* **CORS**
* **Cookie Sessions**
- * ...and more.
+ * و موارد بیشمار دیگر.
-## Performance
+## کارایی
-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). (*)
+معیار (بنچمارک)های مستقل TechEmpower حاکی از آن است که برنامههای **FastAPI** که تحت Uvicorn اجرا میشود،
یکی از سریعترین فریمورکهای مبتنی بر پایتون, است که کمی ضعیفتر از Starlette و Uvicorn عمل میکند (فریمورک و سروری که FastAPI بر اساس آنها ایجاد شده است) (*)
-To understand more about it, see the section
Benchmarks.
+برای درک بهتری از این موضوع به بخش
بنچمارکها مراجعه کنید.
-## Optional Dependencies
+## نیازمندیهای اختیاری
-Used by Pydantic:
+استفاده شده توسط Pydantic:
-*
ujson
- for faster JSON
"parsing".
-*
email_validator
- for email validation.
+*
ujson
- برای
"تجزیه (parse)" سریعتر JSON .
+*
email_validator
- برای اعتبارسنجی آدرسهای ایمیل.
-Used by Starlette:
+استفاده شده توسط Starlette:
-*
requests
- Required if you want to use the `TestClient`.
-*
jinja2
- Required if you want to use the default template configuration.
-*
python-multipart
- Required if you want to support form
"parsing", with `request.form()`.
-*
itsdangerous
- Required for `SessionMiddleware` support.
-*
pyyaml
- Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-*
ujson
- Required if you want to use `UJSONResponse`.
+*
requests
- در صورتی که میخواهید از `TestClient` استفاده کنید.
+*
aiofiles
- در صورتی که میخواهید از `FileResponse` و `StaticFiles` استفاده کنید.
+*
jinja2
- در صورتی که بخواهید از پیکربندی پیشفرض برای قالبها استفاده کنید.
+*
python-multipart
- در صورتی که بخواهید با استفاده از `request.form()` از قابلیت
"تجزیه (parse)" فرم استفاده کنید.
+*
itsdangerous
- در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید.
+*
pyyaml
- برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمیکنید.).
+*
graphene
- در صورتی که از `GraphQLApp` پشتیبانی میکنید.
+*
ujson
- در صورتی که بخواهید از `UJSONResponse` استفاده کنید.
-Used by FastAPI / Starlette:
+استفاده شده توسط FastAPI / Starlette:
-*
uvicorn
- for the server that loads and serves your application.
-*
orjson
- Required if you want to use `ORJSONResponse`.
+*
uvicorn
- برای سرور اجرا کننده برنامه وب.
+*
orjson
- در صورتی که بخواهید از `ORJSONResponse` استفاده کنید.
-You can install all of these with `pip install "fastapi[all]"`.
+میتوان همه این موارد را با استفاده از دستور `pip install fastapi[all]`. به صورت یکجا نصب کرد.
-## License
+## لایسنس
-This project is licensed under the terms of the MIT license.
+این پروژه مشمول قوانین و مقررات لایسنس MIT است.
diff --git a/docs/fa/mkdocs.yml b/docs/fa/mkdocs.yml
index 3966a60261e02..7c2fe5eab8719 100644
--- a/docs/fa/mkdocs.yml
+++ b/docs/fa/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -73,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -105,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -123,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md
index 71c28b7039068..db88c4663ce3f 100644
--- a/docs/fr/docs/async.md
+++ b/docs/fr/docs/async.md
@@ -205,10 +205,6 @@ Cette "attente" 🕙 se mesure en microsecondes, mais tout de même, en cumulé
C'est pourquoi il est logique d'utiliser du code asynchrone ⏸🔀⏯ pour des APIs web.
-La plupart des frameworks Python existants (y compris Flask et Django) ont été créés avant que les nouvelles fonctionnalités asynchrones de Python n'existent. Donc, les façons dont ils peuvent être déployés supportent l'exécution parallèle et une ancienne forme d'exécution asynchrone qui n'est pas aussi puissante que les nouvelles fonctionnalités de Python.
-
-Et cela, bien que les spécifications principales du web asynchrone en Python (ou ASGI) ont été développées chez Django, pour ajouter le support des WebSockets.
-
Ce type d'asynchronicité est ce qui a rendu NodeJS populaire (bien que NodeJS ne soit pas parallèle) et c'est la force du Go en tant que langage de programmation.
Et c'est le même niveau de performance que celui obtenu avec **FastAPI**.
diff --git a/docs/fr/docs/deployment/index.md b/docs/fr/docs/deployment/index.md
new file mode 100644
index 0000000000000..e855adfa3c1ed
--- /dev/null
+++ b/docs/fr/docs/deployment/index.md
@@ -0,0 +1,28 @@
+# Déploiement - Intro
+
+Le déploiement d'une application **FastAPI** est relativement simple.
+
+## Que signifie le déploiement
+
+**Déployer** une application signifie effectuer les étapes nécessaires pour la rendre **disponible pour les
+utilisateurs**.
+
+Pour une **API Web**, cela implique normalement de la placer sur une **machine distante**, avec un **programme serveur**
+qui offre de bonnes performances, une bonne stabilité, _etc._, afin que vos **utilisateurs** puissent **accéder** à
+l'application efficacement et sans interruption ni problème.
+
+Ceci contraste avec les étapes de **développement**, où vous êtes constamment en train de modifier le code, de le casser
+et de le réparer, d'arrêter et de redémarrer le serveur de développement, _etc._
+
+## Stratégies de déploiement
+
+Il existe plusieurs façons de procéder, en fonction de votre cas d'utilisation spécifique et des outils que vous
+utilisez.
+
+Vous pouvez **déployer un serveur** vous-même en utilisant une combinaison d'outils, vous pouvez utiliser un **service
+cloud** qui fait une partie du travail pour vous, ou encore d'autres options possibles.
+
+Je vais vous montrer certains des principaux concepts que vous devriez probablement avoir à l'esprit lors du déploiement
+d'une application **FastAPI** (bien que la plupart de ces concepts s'appliquent à tout autre type d'application web).
+
+Vous verrez plus de détails à avoir en tête et certaines des techniques pour le faire dans les sections suivantes. ✨
diff --git a/docs/fr/docs/history-design-future.md b/docs/fr/docs/history-design-future.md
new file mode 100644
index 0000000000000..b77664be6c2c0
--- /dev/null
+++ b/docs/fr/docs/history-design-future.md
@@ -0,0 +1,79 @@
+# Histoire, conception et avenir
+
+Il y a quelque temps,
un utilisateur de **FastAPI** a demandé :
+
+> Quelle est l'histoire de ce projet ? Il semble être sorti de nulle part et est devenu génial en quelques semaines [...].
+
+Voici un petit bout de cette histoire.
+
+## Alternatives
+
+Je crée des API avec des exigences complexes depuis plusieurs années (Machine Learning, systèmes distribués, jobs asynchrones, bases de données NoSQL, etc), en dirigeant plusieurs équipes de développeurs.
+
+Dans ce cadre, j'ai dû étudier, tester et utiliser de nombreuses alternatives.
+
+L'histoire de **FastAPI** est en grande partie l'histoire de ses prédécesseurs.
+
+Comme dit dans la section [Alternatives](alternatives.md){.internal-link target=\_blank} :
+
+
+
+**FastAPI** n'existerait pas sans le travail antérieur d'autres personnes.
+
+Il y a eu de nombreux outils créés auparavant qui ont contribué à inspirer sa création.
+
+J'ai évité la création d'un nouveau framework pendant plusieurs années. J'ai d'abord essayé de résoudre toutes les fonctionnalités couvertes par **FastAPI** en utilisant de nombreux frameworks, plug-ins et outils différents.
+
+Mais à un moment donné, il n'y avait pas d'autre option que de créer quelque chose qui offre toutes ces fonctionnalités, en prenant les meilleures idées des outils précédents, et en les combinant de la meilleure façon possible, en utilisant des fonctionnalités du langage qui n'étaient même pas disponibles auparavant (annotations de type pour Python 3.6+).
+
+
+
+## Recherche
+
+En utilisant toutes les alternatives précédentes, j'ai eu la chance d'apprendre de toutes, de prendre des idées, et de les combiner de la meilleure façon que j'ai pu trouver pour moi-même et les équipes de développeurs avec lesquelles j'ai travaillé.
+
+Par exemple, il était clair que l'idéal était de se baser sur les annotations de type Python standard.
+
+De plus, la meilleure approche était d'utiliser des normes déjà existantes.
+
+Ainsi, avant même de commencer à coder **FastAPI**, j'ai passé plusieurs mois à étudier les spécifications d'OpenAPI, JSON Schema, OAuth2, etc. Comprendre leurs relations, leurs similarités et leurs différences.
+
+## Conception
+
+Ensuite, j'ai passé du temps à concevoir l'"API" de développeur que je voulais avoir en tant qu'utilisateur (en tant que développeur utilisant FastAPI).
+
+J'ai testé plusieurs idées dans les éditeurs Python les plus populaires : PyCharm, VS Code, les éditeurs basés sur Jedi.
+
+D'après la dernière
Enquête Développeurs Python, cela couvre environ 80% des utilisateurs.
+
+Cela signifie que **FastAPI** a été spécifiquement testé avec les éditeurs utilisés par 80% des développeurs Python. Et comme la plupart des autres éditeurs ont tendance à fonctionner de façon similaire, tous ses avantages devraient fonctionner pour pratiquement tous les éditeurs.
+
+Ainsi, j'ai pu trouver les meilleurs moyens de réduire autant que possible la duplication du code, d'avoir la complétion partout, les contrôles de type et d'erreur, etc.
+
+Le tout de manière à offrir la meilleure expérience de développement à tous les développeurs.
+
+## Exigences
+
+Après avoir testé plusieurs alternatives, j'ai décidé que j'allais utiliser
**Pydantic** pour ses avantages.
+
+J'y ai ensuite contribué, pour le rendre entièrement compatible avec JSON Schema, pour supporter différentes manières de définir les déclarations de contraintes, et pour améliorer le support des éditeurs (vérifications de type, autocomplétion) sur la base des tests effectués dans plusieurs éditeurs.
+
+Pendant le développement, j'ai également contribué à
**Starlette**, l'autre exigence clé.
+
+## Développement
+
+Au moment où j'ai commencé à créer **FastAPI** lui-même, la plupart des pièces étaient déjà en place, la conception était définie, les exigences et les outils étaient prêts, et la connaissance des normes et des spécifications était claire et fraîche.
+
+## Futur
+
+À ce stade, il est déjà clair que **FastAPI** et ses idées sont utiles pour de nombreuses personnes.
+
+Elle a été préférée aux solutions précédentes parce qu'elle convient mieux à de nombreux cas d'utilisation.
+
+De nombreux développeurs et équipes dépendent déjà de **FastAPI** pour leurs projets (y compris moi et mon équipe).
+
+Mais il y a encore de nombreuses améliorations et fonctionnalités à venir.
+
+**FastAPI** a un grand avenir devant lui.
+
+Et [votre aide](help-fastapi.md){.internal-link target=\_blank} est grandement appréciée.
diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md
index f713ee96b386f..1307c063bbc8e 100644
--- a/docs/fr/docs/index.md
+++ b/docs/fr/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/fr/mkdocs.yml b/docs/fr/mkdocs.yml
index bf0d2b21cc49c..6bed7be73853e 100644
--- a/docs/fr/mkdocs.yml
+++ b/docs/fr/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -67,9 +69,11 @@ nav:
- tutorial/background-tasks.md
- async.md
- Déploiement:
+ - deployment/index.md
- deployment/docker.md
- project-generation.md
- alternatives.md
+- history-design-future.md
- external-links.md
markdown_extensions:
- toc:
@@ -88,6 +92,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -120,6 +126,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -138,6 +146,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md
new file mode 100644
index 0000000000000..fa63d8cb7cf8f
--- /dev/null
+++ b/docs/he/docs/index.md
@@ -0,0 +1,464 @@
+
+
+
+
+ תשתית FastAPI, ביצועים גבוהים, קלה ללמידה, מהירה לתכנות, מוכנה לסביבת ייצור
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+---
+
+**תיעוד**: https://fastapi.tiangolo.com
+
+**קוד**:
https://github.com/tiangolo/fastapi
+
+---
+
+FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים גבוהים) לבניית ממשקי תכנות יישומים (API) עם פייתון 3.6+ בהתבסס על רמזי טיפוסים סטנדרטיים.
+
+תכונות המפתח הן:
+
+- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#performance).
+
+- **מהירה לתכנות**: הגבירו את מהירות פיתוח התכונות החדשות בכ - %200 עד %300. \*
+- **פחות שגיאות**: מנעו כ - %40 משגיאות אנוש (מפתחים). \*
+- **אינטואיטיבית**: תמיכת עורך מעולה.
השלמה בכל מקום. פחות זמן ניפוי שגיאות.
+- **קלה**: מתוכננת להיות קלה לשימוש וללמידה. פחות זמן קריאת תיעוד.
+- **קצרה**: מזערו שכפול קוד. מספר תכונות מכל הכרזת פרמטר. פחות שגיאות.
+- **חסונה**: קבלו קוד מוכן לסביבת ייצור. עם תיעוד אינטרקטיבי אוטומטי.
+- **מבוססת סטנדרטים**: מבוססת על (ותואמת לחלוטין ל -) הסטדנרטים הפתוחים לממשקי תכנות יישומים:
OpenAPI (ידועים לשעבר כ - Swagger) ו -
JSON Schema.
+
+
\* הערכה מבוססת על בדיקות של צוות פיתוח פנימי שבונה אפליקציות בסביבת ייצור.
+
+## נותני חסות
+
+
+
+{% if sponsors %}
+{% for sponsor in sponsors.gold -%}
+
+{% endfor -%}
+{%- for sponsor in sponsors.silver -%}
+
+{% endfor %}
+{% endif %}
+
+
+
+
נותני חסות אחרים
+
+## דעות
+
+"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
+
+
Kabir Khan -
Microsoft (ref)
+
+---
+
+"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
+
+
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala -
Uber (ref)
+
+---
+
+"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
+
+
Kevin Glisson, Marc Vilanova, Forest Monsen -
Netflix (ref)
+
+---
+
+"_I’m over the moon excited about **FastAPI**. It’s so fun!_"
+
+
+
+---
+
+"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
+
+
+
+---
+
+"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
+
+"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
+
+
+
+---
+
+## **Typer**, ה - FastAPI של ממשקי שורת פקודה (CLI).
+
+
+
+אם אתם בונים אפליקציית
CLI לשימוש במסוף במקום ממשק רשת, העיפו מבט על
**Typer**.
+
+**Typer** היא אחותה הקטנה של FastAPI. ומטרתה היא להיות ה - **FastAPI של ממשקי שורת פקודה**. ⌨️ 🚀
+
+## תלויות
+
+פייתון 3.6+
+
+FastAPI עומדת על כתפי ענקיות:
+
+-
Starlette לחלקי הרשת.
+-
Pydantic לחלקי המידע.
+
+## התקנה
+
+
+
+```console
+$ pip install fastapi
+
+---> 100%
+```
+
+
+
+תצטרכו גם שרת ASGI כגון
Uvicorn או
Hypercorn.
+
+
+
+```console
+$ pip install "uvicorn[standard]"
+
+---> 100%
+```
+
+
+
+## דוגמא
+
+### צרו אותה
+
+- צרו קובץ בשם `main.py` עם:
+
+```Python
+from typing import Union
+
+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: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+```
+
+
+או השתמשו ב - async def
...
+
+אם הקוד שלכם משתמש ב - `async` / `await`, השתמשו ב - `async def`:
+
+```Python hl_lines="9 14"
+from typing import Union
+
+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: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+```
+
+**שימו לב**:
+
+אם אינכם יודעים, בדקו את פרק "ממהרים?" על `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` (מודול פייתון).
+- `app`: האובייקט שנוצר בתוך `main.py` עם השורה app = FastAPI()
.
+- --reload
: גרמו לשרת להתאתחל לאחר שינויים בקוד. עשו זאת רק בסביבת פיתוח.
+
+
+
+### בדקו אותה
+
+פתחו את הדפדפן שלכם בכתובת
http://127.0.0.1:8000/items/5?q=somequery.
+
+אתם תראו תגובת JSON:
+
+```JSON
+{"item_id": 5, "q": "somequery"}
+```
+
+כבר יצרתם API ש:
+
+- מקבל בקשות HTTP בנתיבים `/` ו -
/items/{item_id}
.
+- שני ה _נתיבים_ מקבלים _בקשות_ `GET` (ידועות גם כ*מתודות* HTTP).
+- ה _נתיב_
/items/{item_id}
כולל \*פרמטר נתיב\_ `item_id` שאמור להיות `int`.
+- ה _נתיב_
/items/{item_id}
\*פרמטר שאילתא\_ אופציונלי `q`.
+
+### תיעוד API אינטרקטיבי
+
+כעת פנו לכתובת
http://127.0.0.1:8000/docs.
+
+אתם תראו את התיעוד האוטומטי (מסופק על ידי
Swagger UI):
+
+![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
+
+### תיעוד אלטרנטיבי
+
+כעת פנו לכתובת
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 hl_lines="4 9-12 25-27"
+from typing import Union
+
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+ is_offer: Union[bool, None] = None
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: Union[str, None] = 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}
+```
+
+השרת אמול להתאתחל אוטומטית (מאחר והוספתם
--reload
לפקודת `uvicorn` שלמעלה).
+
+### שדרוג התיעוד האינטרקטיבי
+
+כעת פנו לכתובת
http://127.0.0.1:8000/docs.
+
+- התיעוד האוטומטי יתעדכן, כולל הגוף החדש:
+
+![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)
+
+### סיכום
+
+לסיכום, אתם מכריזים ** פעם אחת** על טיפוסי הפרמטרים, גוף וכו' כפרמטרים לפונקציה.
+
+אתם עושים את זה עם טיפוסי פייתון מודרניים.
+
+אתם לא צריכים ללמוד תחביר חדש, מתודות או מחלקות של ספרייה ספיציפית, וכו'
+
+רק **פייתון 3.6+** סטנדרטי.
+
+לדוגמא, ל - `int`:
+
+```Python
+item_id: int
+```
+
+או למודל `Item` מורכב יותר:
+
+```Python
+item: Item
+```
+
+...ועם הכרזת הטיפוס האחת הזו אתם מקבלים:
+
+- תמיכת עורך, כולל:
+ - השלמות.
+ - בדיקת טיפוסים.
+- אימות מידע:
+ - שגיאות ברורות ואטומטיות כאשר מוכנס מידע לא חוקי .
+ - אימות אפילו לאובייקטי JSON מקוננים.
+-
המרה של מידע קלט: המרה של מידע שמגיע מהרשת למידע וטיפוסים של פייתון. קורא מ:
+ - JSON.
+ - פרמטרי נתיב.
+ - פרמטרי שאילתא.
+ - עוגיות.
+ - כותרות.
+ - טפסים.
+ - קבצים.
+-
המרה של מידע פלט: המרה של מידע וטיפוסים מפייתון למידע רשת (כ - JSON):
+ - המירו טיפוסי פייתון (`str`, `int`, `float`, `bool`, `list`, etc).
+ - עצמי `datetime`.
+ - עצמי `UUID`.
+ - מודלי בסיסי נתונים.
+ - ...ורבים אחרים.
+- תיעוד API אוטומטי ואינטרקטיבית כולל שתי אלטרנטיבות לממשק המשתמש:
+ - Swagger UI.
+ - ReDoc.
+
+---
+
+בחזרה לדוגמאת הקוד הקודמת, **FastAPI** ידאג:
+
+- לאמת שיש `item_id` בנתיב בבקשות `GET` ו - `PUT`.
+- לאמת שה - `item_id` הוא מטיפוס `int` בבקשות `GET` ו - `PUT`.
+ - אם הוא לא, הלקוח יראה שגיאה ברורה ושימושית.
+- לבדוק האם קיים פרמטר שאילתא בשם `q` (קרי `http://127.0.0.1:8000/items/foo?q=somequery`) לבקשות `GET`.
+ - מאחר והפרמטר `q` מוגדר עם
= None
, הוא אופציונלי.
+ - לולא ה - `None` הוא היה חובה (כמו הגוף במקרה של `PUT`).
+- לבקשות `PUT` לנתיב
/items/{item_id}
, לקרוא את גוף הבקשה כ - JSON:
+ - לאמת שהוא כולל את מאפיין החובה `name` שאמור להיות מטיפוס `str`.
+ - לאמת שהוא כולל את מאפיין החובה `price` שחייב להיות מטיפוס `float`.
+ - לבדוק האם הוא כולל את מאפיין הרשות `is_offer` שאמור להיות מטיפוס `bool`, אם הוא נמצא.
+ - כל זה יעבוד גם לאובייקט JSON מקונן.
+- להמיר מ - JSON ול- JSON אוטומטית.
+- לתעד הכל באמצעות OpenAPI, תיעוד שבו יוכלו להשתמש:
+ - מערכות תיעוד אינטרקטיביות.
+ - מערכות ייצור קוד אוטומטיות, להרבה שפות.
+- לספק ישירות שתי מערכות תיעוד רשתיות.
+
+---
+
+רק גרדנו את קצה הקרחון, אבל כבר יש לכם רעיון של איך הכל עובד.
+
+נסו לשנות את השורה:
+
+```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)
+
+לדוגמא יותר שלמה שכוללת עוד תכונות, ראו את ה
מדריך - למשתמש.
+
+**התראת ספוילרים**: המדריך - למשתמש כולל:
+
+- הכרזה על **פרמטרים** ממקורות אחרים ושונים כגון: **כותרות**, **עוגיות**, **טפסים** ו - **קבצים**.
+- איך לקבוע **מגבלות אימות** בעזרת `maximum_length` או `regex`.
+- דרך חזקה וקלה להשתמש ב**
הזרקת תלויות**.
+- אבטחה והתאמתות, כולל תמיכה ב - **OAuth2** עם **JWT** והתאמתות **HTTP Basic**.
+- טכניקות מתקדמות (אבל קלות באותה מידה) להכרזת אובייקטי JSON מקוננים (תודות ל - Pydantic).
+- אינטרקציה עם **GraphQL** דרך
Strawberry וספריות אחרות.
+- תכונות נוספות רבות (תודות ל - Starlette) כגון:
+ - **WebSockets**
+ - בדיקות קלות במיוחד מבוססות על `requests` ו - `pytest`
+ - **CORS**
+ - **Cookie Sessions**
+ - ...ועוד.
+
+## ביצועים
+
+בדיקות עצמאיות של TechEmpower הראו שאפליקציות **FastAPI** שרצות תחת Uvicorn הן
מתשתיות הפייתון המהירות ביותר, רק מתחת ל - Starlette ו - Uvicorn עצמן (ש - FastAPI מבוססת עליהן). (\*)
+
+כדי להבין עוד על הנושא, ראו את הפרק
Benchmarks.
+
+## תלויות אופציונליות
+
+בשימוש Pydantic:
+
+-
ujson
-
"פרסור" JSON.
+-
email_validator
- לאימות כתובות אימייל.
+
+בשימוש Starlette:
+
+-
requests
- דרוש אם ברצונכם להשתמש ב - `TestClient`.
+-
jinja2
- דרוש אם ברצונכם להשתמש בברירת המחדל של תצורת הטמפלייטים.
+-
python-multipart
- דרוש אם ברצונכם לתמוך ב
"פרסור" טפסים, באצמעות
request.form()
.
+-
itsdangerous
- דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`.
+-
pyyaml
- דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI).
+-
ujson
- דרוש אם ברצונכם להשתמש ב - `UJSONResponse`.
+
+בשימוש FastAPI / Starlette:
+
+-
uvicorn
- לשרת שטוען ומגיש את האפליקציה שלכם.
+-
orjson
- דרוש אם ברצונכם להשתמש ב - `ORJSONResponse`.
+
+תוכלו להתקין את כל אלו באמצעות
pip install "fastapi[all]"
.
+
+## רשיון
+
+הפרויקט הזה הוא תחת התנאים של רשיון MIT.
diff --git a/docs/he/mkdocs.yml b/docs/he/mkdocs.yml
new file mode 100644
index 0000000000000..3279099b5abd1
--- /dev/null
+++ b/docs/he/mkdocs.yml
@@ -0,0 +1,145 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/he/
+theme:
+ name: material
+ custom_dir: overrides
+ palette:
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb
+ name: Switch to light mode
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb-outline
+ name: Switch to dark mode
+ features:
+ - search.suggest
+ - search.highlight
+ - content.tabs.link
+ icon:
+ repo: fontawesome/brands/github-alt
+ logo: https://fastapi.tiangolo.com/img/icon-white.svg
+ favicon: https://fastapi.tiangolo.com/img/favicon.png
+ language: he
+repo_name: tiangolo/fastapi
+repo_url: https://github.com/tiangolo/fastapi
+edit_uri: ''
+plugins:
+- search
+- markdownextradata:
+ data: data
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - az: /az/
+ - de: /de/
+ - es: /es/
+ - fa: /fa/
+ - fr: /fr/
+ - he: /he/
+ - id: /id/
+ - it: /it/
+ - ja: /ja/
+ - ko: /ko/
+ - nl: /nl/
+ - pl: /pl/
+ - pt: /pt/
+ - ru: /ru/
+ - sq: /sq/
+ - sv: /sv/
+ - tr: /tr/
+ - uk: /uk/
+ - zh: /zh/
+markdown_extensions:
+- toc:
+ permalink: true
+- markdown.extensions.codehilite:
+ guess_lang: false
+- mdx_include:
+ base_path: docs
+- admonition
+- codehilite
+- extra
+- pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_code_format ''
+- pymdownx.tabbed:
+ alternate_style: true
+- attr_list
+- md_in_html
+extra:
+ analytics:
+ provider: google
+ property: UA-133183413-1
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/tiangolo/fastapi
+ - icon: fontawesome/brands/discord
+ link: https://discord.gg/VQjSZaeJmf
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/fastapi
+ - 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
+ alternate:
+ - link: /
+ name: en - English
+ - link: /az/
+ name: az
+ - link: /de/
+ name: de
+ - link: /es/
+ name: es - español
+ - link: /fa/
+ name: fa
+ - link: /fr/
+ name: fr - français
+ - link: /he/
+ name: he
+ - link: /id/
+ name: id
+ - link: /it/
+ name: it - italiano
+ - link: /ja/
+ name: ja - 日本語
+ - link: /ko/
+ name: ko - 한국어
+ - link: /nl/
+ name: nl
+ - link: /pl/
+ name: pl
+ - link: /pt/
+ name: pt - português
+ - link: /ru/
+ name: ru - русский язык
+ - link: /sq/
+ name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
+ - link: /tr/
+ name: tr - Türkçe
+ - link: /uk/
+ name: uk - українська мова
+ - link: /zh/
+ name: zh - 汉语
+extra_css:
+- https://fastapi.tiangolo.com/css/termynal.css
+- https://fastapi.tiangolo.com/css/custom.css
+extra_javascript:
+- https://fastapi.tiangolo.com/js/termynal.js
+- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/he/overrides/.gitignore b/docs/he/overrides/.gitignore
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md
index 0bb7b55e3b065..041e0b754f1c1 100644
--- a/docs/id/docs/index.md
+++ b/docs/id/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md
new file mode 100644
index 0000000000000..8fec3c087e6ad
--- /dev/null
+++ b/docs/id/docs/tutorial/index.md
@@ -0,0 +1,80 @@
+# Tutorial - Pedoman Pengguna - Pengenalan
+
+Tutorial ini menunjukan cara menggunakan ***FastAPI*** dengan semua fitur-fiturnya, tahap demi tahap.
+
+Setiap bagian dibangun secara bertahap dari bagian sebelumnya, tetapi terstruktur untuk memisahkan banyak topik, sehingga kamu bisa secara langsung menuju ke topik spesifik untuk menyelesaikan kebutuhan API tertentu.
+
+Ini juga dibangun untuk digunakan sebagai referensi yang akan datang.
+
+Sehingga kamu dapat kembali lagi dan mencari apa yang kamu butuhkan dengan tepat.
+
+## Jalankan kode
+
+Semua blok-blok kode dapat dicopy dan digunakan langsung (Mereka semua sebenarnya adalah file python yang sudah teruji).
+
+Untuk menjalankan setiap contoh, copy kode ke file `main.py`, dan jalankan `uvicorn` dengan:
+
+
+
+```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.
+```
+
+
+
+**SANGAT disarankan** agar kamu menulis atau meng-copy kode, meng-editnya dan menjalankannya secara lokal.
+
+Dengan menggunakannya di dalam editor, benar-benar memperlihatkan manfaat dari FastAPI, melihat bagaimana sedikitnya kode yang harus kamu tulis, semua pengecekan tipe, pelengkapan otomatis, dll.
+
+---
+
+## Install FastAPI
+
+Langkah pertama adalah dengan meng-install FastAPI.
+
+Untuk tutorial, kamu mungkin hendak meng-instalnya dengan semua pilihan fitur dan dependensinya:
+
+
+
+```console
+$ pip install "fastapi[all]"
+
+---> 100%
+```
+
+
+
+...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu.
+
+!!! catatan
+ Kamu juga dapat meng-instalnya bagian demi bagian.
+
+ Hal ini mungkin yang akan kamu lakukan ketika kamu hendak men-deploy aplikasimu ke tahap produksi:
+
+ ```
+ pip install fastapi
+ ```
+
+ Juga install `uvicorn` untk menjalankan server"
+
+ ```
+ pip install "uvicorn[standard]"
+ ```
+
+ Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan.
+
+## Pedoman Pengguna Lanjutan
+
+Tersedia juga **Pedoman Pengguna Lanjutan** yang dapat kamu baca nanti setelah **Tutorial - Pedoman Pengguna** ini.
+
+**Pedoman Pengguna Lanjutan**, dibangun atas hal ini, menggunakan konsep yang sama, dan mengajarkan kepadamu beberapa fitur tambahan.
+
+Tetapi kamu harus membaca terlebih dahulu **Tutorial - Pedoman Pengguna** (apa yang sedang kamu baca sekarang).
+
+Hal ini didesain sehingga kamu dapat membangun aplikasi lengkap dengan hanya **Tutorial - Pedoman Pengguna**, dan kemudian mengembangkannya ke banyak cara yang berbeda, tergantung dari kebutuhanmu, menggunakan beberapa ide-ide tambahan dari **Pedoman Pengguna Lanjutan**.
diff --git a/docs/id/mkdocs.yml b/docs/id/mkdocs.yml
index 769547d11adf4..abb31252f6ff8 100644
--- a/docs/id/mkdocs.yml
+++ b/docs/id/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -73,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -105,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -123,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md
index 6acf925528935..5cbe78a717bb7 100644
--- a/docs/it/docs/index.md
+++ b/docs/it/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/it/mkdocs.yml b/docs/it/mkdocs.yml
index ebec9a6429d90..532b5bc52caa0 100644
--- a/docs/it/mkdocs.yml
+++ b/docs/it/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -73,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -105,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -123,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md
new file mode 100644
index 0000000000000..676f60359f78e
--- /dev/null
+++ b/docs/ja/docs/advanced/index.md
@@ -0,0 +1,24 @@
+# ユーザーガイド 応用編
+
+## さらなる機能
+
+[チュートリアル - ユーザーガイド](../tutorial/){.internal-link target=_blank}により、**FastAPI**の主要な機能は十分に理解できたことでしょう。
+
+以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。
+
+!!! tip "豆知識"
+ 以降のセクションは、 **必ずしも"応用編"ではありません**。
+
+ ユースケースによっては、その中から解決策を見つけられるかもしれません。
+
+## 先にチュートリアルを読む
+
+[チュートリアル - ユーザーガイド](../tutorial/){.internal-link target=_blank}の知識があれば、**FastAPI**の主要な機能を利用することができます。
+
+以降のセクションは、すでにチュートリアルを読んで、その主要なアイデアを理解できていることを前提としています。
+
+## テスト駆動開発のコース
+
+このセクションの内容を補完するために脱初心者用コースを受けたい場合は、**TestDriven.io**による、Test-Driven Development with FastAPI and Dockerを確認するのがよいかもしれません。
+
+現在、このコースで得られた利益の10%が**FastAPI**の開発のために寄付されています。🎉 😄
diff --git a/docs/ja/docs/advanced/nosql-databases.md b/docs/ja/docs/advanced/nosql-databases.md
new file mode 100644
index 0000000000000..fbd76e96b14e9
--- /dev/null
+++ b/docs/ja/docs/advanced/nosql-databases.md
@@ -0,0 +1,156 @@
+# NoSQL (分散 / ビッグデータ) Databases
+
+**FastAPI** はあらゆる
NoSQLと統合することもできます。
+
+ここでは
ドキュメントベースのNoSQLデータベースである**
Couchbase**を使用した例を見てみましょう。
+
+他にもこれらのNoSQLデータベースを利用することが出来ます:
+
+* **MongoDB**
+* **Cassandra**
+* **CouchDB**
+* **ArangoDB**
+* **ElasticSearch** など。
+
+!!! tip "豆知識"
+ **FastAPI**と**Couchbase**を使った公式プロジェクト・ジェネレータがあります。すべて**Docker**ベースで、フロントエンドやその他のツールも含まれています:
https://github.com/tiangolo/full-stack-fastapi-couchbase
+
+## Couchbase コンポーネントの Import
+
+まずはImportしましょう。今はその他のソースコードに注意を払う必要はありません。
+
+```Python hl_lines="3-5"
+{!../../../docs_src/nosql_databases/tutorial001.py!}
+```
+
+## "document type" として利用する定数の定義
+
+documentで利用する固定の`type`フィールドを用意しておきます。
+
+これはCouchbaseで必須ではありませんが、後々の助けになるベストプラクティスです。
+
+```Python hl_lines="9"
+{!../../../docs_src/nosql_databases/tutorial001.py!}
+```
+
+## `Bucket` を取得する関数の追加
+
+**Couchbase**では、bucketはdocumentのセットで、様々な種類のものがあります。
+
+Bucketは通常、同一のアプリケーション内で互いに関係を持っています。
+
+リレーショナルデータベースの世界でいう"database"(データベースサーバではなく特定のdatabase)と類似しています。
+
+**MongoDB** で例えると"collection"と似た概念です。
+
+次のコードでは主に `Bucket` を利用してCouchbaseを操作します。
+
+この関数では以下の処理を行います:
+
+* **Couchbase** クラスタ(1台の場合もあるでしょう)に接続
+ * タイムアウトのデフォルト値を設定
+* クラスタで認証を取得
+* `Bucket` インスタンスを取得
+ * タイムアウトのデフォルト値を設定
+* 作成した`Bucket`インスタンスを返却
+
+```Python hl_lines="12-21"
+{!../../../docs_src/nosql_databases/tutorial001.py!}
+```
+
+## Pydantic モデルの作成
+
+**Couchbase**のdocumentは実際には単にJSONオブジェクトなのでPydanticを利用してモデルに出来ます。
+
+### `User` モデル
+
+まずは`User`モデルを作成してみましょう:
+
+```Python hl_lines="24-28"
+{!../../../docs_src/nosql_databases/tutorial001.py!}
+```
+
+このモデルは*path operation*に使用するので`hashed_password`は含めません。
+
+### `UserInDB` モデル
+
+それでは`UserInDB`モデルを作成しましょう。
+
+こちらは実際にデータベースに保存されるデータを保持します。
+
+`User`モデルの持つ全ての属性に加えていくつかの属性を追加するのでPydanticの`BaseModel`を継承せずに`User`のサブクラスとして定義します:
+
+```Python hl_lines="31-33"
+{!../../../docs_src/nosql_databases/tutorial001.py!}
+```
+
+!!! note "備考"
+ データベースに保存される`hashed_password`と`type`フィールドを`UserInDB`モデルに保持させていることに注意してください。
+
+ しかしこれらは(*path operation*で返却する)一般的な`User`モデルには含まれません
+
+## user の取得
+
+それでは次の関数を作成しましょう:
+
+* username を取得する
+* username を利用してdocumentのIDを生成する
+* 作成したIDでdocumentを取得する
+* documentの内容を`UserInDB`モデルに設定する
+
+*path operation関数*とは別に、`username`(またはその他のパラメータ)からuserを取得することだけに特化した関数を作成することで、より簡単に複数の部分で再利用したり
ユニットテストを追加することができます。
+
+```Python hl_lines="36-42"
+{!../../../docs_src/nosql_databases/tutorial001.py!}
+```
+
+### f-strings
+
+`f"userprofile::{username}"` という記載に馴染みがありませんか?これは Python の"
f-string"と呼ばれるものです。
+
+f-stringの`{}`の中に入れられた変数は、文字列の中に展開/注入されます。
+
+### `dict` アンパック
+
+`UserInDB(**result.value)`という記載に馴染みがありませんか?
これは`dict`の"アンパック"と呼ばれるものです。
+
+これは`result.value`の`dict`からそのキーと値をそれぞれ取りキーワード引数として`UserInDB`に渡します。
+
+例えば`dict`が下記のようになっていた場合:
+
+```Python
+{
+ "username": "johndoe",
+ "hashed_password": "some_hash",
+}
+```
+
+`UserInDB`には次のように渡されます:
+
+```Python
+UserInDB(username="johndoe", hashed_password="some_hash")
+```
+
+## **FastAPI** コードの実装
+
+### `FastAPI` app の作成
+
+```Python hl_lines="46"
+{!../../../docs_src/nosql_databases/tutorial001.py!}
+```
+
+### *path operation関数*の作成
+
+私たちのコードはCouchbaseを呼び出しており、
実験的なPython await
を使用していないので、私たちは`async def`ではなく通常の`def`で関数を宣言する必要があります。
+
+また、Couchbaseは単一の`Bucket`オブジェクトを複数の
スレッドで使用しないことを推奨していますので、単に直接Bucketを取得して関数に渡すことが出来ます。
+
+```Python hl_lines="49-53"
+{!../../../docs_src/nosql_databases/tutorial001.py!}
+```
+
+## まとめ
+
+他のサードパーティ製のNoSQLデータベースを利用する場合でも、そのデータベースの標準ライブラリを利用するだけで利用できます。
+
+他の外部ツール、システム、APIについても同じことが言えます。
diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md
index dd4b568bdcd65..67010a66f489d 100644
--- a/docs/ja/docs/deployment/manually.md
+++ b/docs/ja/docs/deployment/manually.md
@@ -11,7 +11,7 @@
```console
- $ pip install uvicorn[standard]
+ $ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md
index 5fca78a833ec3..51977037c2208 100644
--- a/docs/ja/docs/index.md
+++ b/docs/ja/docs/index.md
@@ -131,7 +131,7 @@ $ pip install fastapi
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md
index 29fc86f94bcd8..a2dd59c9b03cb 100644
--- a/docs/ja/docs/tutorial/index.md
+++ b/docs/ja/docs/tutorial/index.md
@@ -43,7 +43,7 @@ $ uvicorn main:app --reload
```console
-$ pip install fastapi[all]
+$ pip install "fastapi[all]"
---> 100%
```
@@ -64,7 +64,7 @@ $ pip install fastapi[all]
また、サーバーとして動作するように`uvicorn` をインストールします:
```
- pip install uvicorn[standard]
+ pip install "uvicorn[standard]"
```
そして、使用したい依存関係をそれぞれ同様にインストールします。
diff --git a/docs/ja/mkdocs.yml b/docs/ja/mkdocs.yml
index 055404feaf9aa..b3f18bbdd305f 100644
--- a/docs/ja/mkdocs.yml
+++ b/docs/ja/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -78,10 +80,12 @@ nav:
- tutorial/testing.md
- tutorial/debugging.md
- 高度なユーザーガイド:
+ - advanced/index.md
- advanced/path-operation-advanced-configuration.md
- advanced/additional-status-codes.md
- advanced/response-directly.md
- advanced/custom-response.md
+ - advanced/nosql-databases.md
- advanced/conditional-openapi.md
- async.md
- デプロイ:
@@ -114,6 +118,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -146,6 +152,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -164,6 +172,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md
index ec44229947b7c..5a258f47b2504 100644
--- a/docs/ko/docs/index.md
+++ b/docs/ko/docs/index.md
@@ -131,7 +131,7 @@ $ pip install fastapi
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md
index 622aad1aa6ac8..d6db525e8dbd6 100644
--- a/docs/ko/docs/tutorial/index.md
+++ b/docs/ko/docs/tutorial/index.md
@@ -43,7 +43,7 @@ $ uvicorn main:app --reload
```console
-$ pip install fastapi[all]
+$ pip install "fastapi[all]"
---> 100%
```
diff --git a/docs/ko/mkdocs.yml b/docs/ko/mkdocs.yml
index 60cf7d30ae754..50931e134cf06 100644
--- a/docs/ko/mkdocs.yml
+++ b/docs/ko/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -66,6 +68,7 @@ nav:
- tutorial/response-status-code.md
- tutorial/request-files.md
- tutorial/request-forms-and-files.md
+ - tutorial/encoder.md
markdown_extensions:
- toc:
permalink: true
@@ -83,6 +86,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -115,6 +120,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -133,6 +140,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/nl/mkdocs.yml b/docs/nl/mkdocs.yml
index 9cd1e04010fde..6d46939f93988 100644
--- a/docs/nl/mkdocs.yml
+++ b/docs/nl/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -73,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -105,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -123,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md
index bbe1b1ad15e0d..9cc99ba7200a0 100644
--- a/docs/pl/docs/index.md
+++ b/docs/pl/docs/index.md
@@ -130,7 +130,7 @@ Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np.
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md
new file mode 100644
index 0000000000000..9406d703d59cb
--- /dev/null
+++ b/docs/pl/docs/tutorial/first-steps.md
@@ -0,0 +1,334 @@
+# Pierwsze kroki
+
+Najprostszy plik FastAPI może wyglądać tak:
+
+```Python
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Skopiuj to do pliku `main.py`.
+
+Uruchom serwer:
+
+
+
+```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
+ Polecenie `uvicorn main:app` odnosi się do:
+
+ * `main`: plik `main.py` ("moduł" Python).
+ * `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`.
+ * `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania.
+
+Na wyjściu znajduje się linia z czymś w rodzaju:
+
+```hl_lines="4"
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+Ta linia pokazuje adres URL, pod którym Twoja aplikacja jest obsługiwana, na Twoim lokalnym komputerze.
+
+### Sprawdź to
+
+Otwórz w swojej przeglądarce http://127.0.0.1:8000.
+
+Zobaczysz odpowiedź w formacie JSON:
+
+```JSON
+{"message": "Hello World"}
+```
+
+### Interaktywna dokumentacja API
+
+Przejdź teraz do
http://127.0.0.1:8000/docs.
+
+Zobaczysz automatyczną i interaktywną dokumentację API (dostarczoną przez
Swagger UI):
+
+![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
+
+### Alternatywna dokumentacja API
+
+Teraz przejdź do
http://127.0.0.1:8000/redoc.
+
+Zobaczysz alternatywną automatycznie wygenerowaną dokumentację API (dostarczoną przez
ReDoc):
+
+![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
+
+### OpenAPI
+
+**FastAPI** generuje "schemat" z całym Twoim API przy użyciu standardu **OpenAPI** służącego do definiowania API.
+
+#### Schema
+
+"Schema" jest definicją lub opisem czegoś. Nie jest to kod, który go implementuje, ale po prostu abstrakcyjny opis.
+
+#### API "Schema"
+
+W typ przypadku,
OpenAPI to specyfikacja, która dyktuje sposób definiowania schematu interfejsu API.
+
+Definicja schematu zawiera ścieżki API, możliwe parametry, które są przyjmowane przez endpointy, itp.
+
+#### "Schemat" danych
+
+Termin "schemat" może również odnosić się do wyglądu niektórych danych, takich jak zawartość JSON.
+
+W takim przypadku będzie to oznaczać atrybuty JSON, ich typy danych itp.
+
+#### OpenAPI i JSON Schema
+
+OpenAPI definiuje API Schema dla Twojego API, który zawiera definicje (lub "schematy") danych wysyłanych i odbieranych przez Twój interfejs API przy użyciu **JSON Schema**, standardu dla schematów danych w formacie JSON.
+
+#### Sprawdź `openapi.json`
+
+Jeśli jesteś ciekawy, jak wygląda surowy schemat OpenAPI, FastAPI automatycznie generuje JSON Schema z opisami wszystkich Twoich API.
+
+Możesz to zobaczyć bezpośrednio pod adresem:
http://127.0.0.1:8000/openapi.json.
+
+Zobaczysz JSON zaczynający się od czegoś takiego:
+
+```JSON
+{
+ "openapi": "3.0.2",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+
+
+
+...
+```
+
+#### Do czego służy OpenAPI
+
+Schemat OpenAPI jest tym, co zasila dwa dołączone interaktywne systemy dokumentacji.
+
+Istnieją dziesiątki alternatyw, wszystkie oparte na OpenAPI. Możesz łatwo dodać dowolną z nich do swojej aplikacji zbudowanej za pomocą **FastAPI**.
+
+Możesz go również użyć do automatycznego generowania kodu dla klientów, którzy komunikują się z Twoim API. Na przykład aplikacje frontendowe, mobilne lub IoT.
+
+## Przypomnijmy, krok po kroku
+
+### Krok 1: zaimportuj `FastAPI`
+
+```Python hl_lines="1"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+`FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API.
+
+!!! note "Szczegóły techniczne"
+ `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`.
+
+ Oznacza to, że możesz korzystać ze wszystkich funkcjonalności
Starlette również w `FastAPI`.
+
+
+### Krok 2: utwórz instancję `FastAPI`
+
+```Python hl_lines="3"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Zmienna `app` będzie tutaj "instancją" klasy `FastAPI`.
+
+Będzie to główny punkt interakcji przy tworzeniu całego interfejsu API.
+
+Ta zmienna `app` jest tą samą zmienną, do której odnosi się `uvicorn` w poleceniu:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+
+
+Jeśli stworzysz swoją aplikację, np.:
+
+```Python hl_lines="3"
+{!../../../docs_src/first_steps/tutorial002.py!}
+```
+
+I umieścisz to w pliku `main.py`, to będziesz mógł tak wywołać `uvicorn`:
+
+
+
+```console
+$ uvicorn main:my_awesome_api --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+
+
+### Krok 3: wykonaj *operację na ścieżce*
+
+#### Ścieżka
+
+"Ścieżka" tutaj odnosi się do ostatniej części adresu URL, zaczynając od pierwszego `/`.
+
+Więc, w adresie URL takim jak:
+
+```
+https://example.com/items/foo
+```
+
+...ścieżką będzie:
+
+```
+/items/foo
+```
+
+!!! info
+ "Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'.
+
+Podczas budowania API, "ścieżka" jest głównym sposobem na oddzielenie "odpowiedzialności" i „zasobów”.
+
+#### Operacje
+
+"Operacje" tutaj odnoszą się do jednej z "metod" HTTP.
+
+Jedna z:
+
+* `POST`
+* `GET`
+* `PUT`
+* `DELETE`
+
+...i te bardziej egzotyczne:
+
+* `OPTIONS`
+* `HEAD`
+* `PATCH`
+* `TRACE`
+
+W protokole HTTP można komunikować się z każdą ścieżką za pomocą jednej (lub więcej) "metod".
+
+---
+
+Podczas tworzenia API zwykle używasz tych metod HTTP do wykonania określonej akcji.
+
+Zazwyczaj używasz:
+
+* `POST`: do tworzenia danych.
+* `GET`: do odczytywania danych.
+* `PUT`: do aktualizacji danych.
+* `DELETE`: do usuwania danych.
+
+Tak więc w OpenAPI każda z metod HTTP nazywana jest "operacją".
+
+Będziemy je również nazywali "**operacjami**".
+
+#### Zdefiniuj *dekorator operacji na ścieżce*
+
+```Python hl_lines="6"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+`@app.get("/")` mówi **FastAPI** że funkcja poniżej odpowiada za obsługę żądań, które trafiają do:
+
+* ścieżki `/`
+* używając
operacji get
+
+!!! info "`@decorator` Info"
+ Składnia `@something` jest w Pythonie nazywana "dekoratorem".
+
+ Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
+
+ "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
+
+ W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
+
+ Jest to "**dekorator operacji na ścieżce**".
+
+Możesz również użyć innej operacji:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+Oraz tych bardziej egzotycznych:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+!!! tip
+ Możesz dowolnie używać każdej operacji (metody HTTP).
+
+ **FastAPI** nie narzuca żadnego konkretnego znaczenia.
+
+ Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
+
+ Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
+
+### Krok 4: zdefiniuj **funkcję obsługującą ścieżkę**
+
+To jest nasza "**funkcja obsługująca ścieżkę**":
+
+* **ścieżka**: to `/`.
+* **operacja**: to `get`.
+* **funkcja**: to funkcja poniżej "dekoratora" (poniżej `@app.get("/")`).
+
+```Python hl_lines="7"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Jest to funkcja Python.
+
+Zostanie ona wywołana przez **FastAPI** za każdym razem, gdy otrzyma żądanie do adresu URL "`/`" przy użyciu operacji `GET`.
+
+W tym przypadku jest to funkcja "asynchroniczna".
+
+---
+
+Możesz również zdefiniować to jako normalną funkcję zamiast `async def`:
+
+```Python hl_lines="7"
+{!../../../docs_src/first_steps/tutorial003.py!}
+```
+
+!!! note
+ Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](/async/#in-a-hurry){.internal-link target=_blank}.
+
+### Krok 5: zwróć zawartość
+
+```Python hl_lines="8"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Możesz zwrócić `dict`, `list`, pojedynczą wartość jako `str`, `int`, itp.
+
+Możesz również zwrócić modele Pydantic (więcej o tym później).
+
+Istnieje wiele innych obiektów i modeli, które zostaną automatycznie skonwertowane do formatu JSON (w tym ORM itp.). Spróbuj użyć swoich ulubionych, jest bardzo prawdopodobne, że są już obsługiwane.
+
+## Podsumowanie
+
+* Zaimportuj `FastAPI`.
+* Stwórz instancję `app`.
+* Dodaj **dekorator operacji na ścieżce** (taki jak `@app.get("/")`).
+* Napisz **funkcję obsługującą ścieżkę** (taką jak `def root(): ...` powyżej).
+* Uruchom serwer deweloperski (`uvicorn main:app --reload`).
diff --git a/docs/pl/mkdocs.yml b/docs/pl/mkdocs.yml
index 0c3d100e7791f..1cd1294208f8f 100644
--- a/docs/pl/mkdocs.yml
+++ b/docs/pl/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,11 +54,13 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
- Samouczek:
- tutorial/index.md
+ - tutorial/first-steps.md
markdown_extensions:
- toc:
permalink: true
@@ -75,6 +78,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -107,6 +112,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -125,6 +132,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/pt/docs/deployment.md b/docs/pt/docs/deployment.md
index cd820cbd3c97b..2272467fdea0c 100644
--- a/docs/pt/docs/deployment.md
+++ b/docs/pt/docs/deployment.md
@@ -336,7 +336,7 @@ Você apenas precisa instalar um servidor ASGI compatível como:
```console
- $ pip install uvicorn[standard]
+ $ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md
index b1d0c89f2a813..51af486b97307 100644
--- a/docs/pt/docs/index.md
+++ b/docs/pt/docs/index.md
@@ -124,7 +124,7 @@ Você também precisará de um servidor ASGI para produção, tal como
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..97a2e3eac9531
--- /dev/null
+++ b/docs/pt/docs/tutorial/handling-errors.md
@@ -0,0 +1,251 @@
+# Manipulação de erros
+
+Há diversas situações em que você precisa notificar um erro a um cliente que está utilizando a sua API.
+
+Esse cliente pode ser um browser com um frontend, o código de outra pessoa, um dispositivo IoT, etc.
+
+Pode ser que você precise comunicar ao cliente que:
+
+* O cliente não tem direitos para realizar aquela operação.
+* O cliente não tem acesso aquele recurso.
+* O item que o cliente está tentando acessar não existe.
+* etc.
+
+
+Nesses casos, você normalmente retornaria um **HTTP status code** próximo ao status code na faixa do status code **400** (do 400 ao 499).
+
+Isso é bastante similar ao caso do HTTP status code 200 (do 200 ao 299). Esses "200" status codes significam que, de algum modo, houve sucesso na requisição.
+
+Os status codes na faixa dos 400 significam que houve um erro por parte do cliente.
+
+Você se lembra de todos aqueles erros (e piadas) a respeito do "**404 Not Found**"?
+
+## Use o `HTTPException`
+
+Para retornar ao cliente *responses* HTTP com erros, use o `HTTPException`.
+
+### Import `HTTPException`
+
+```Python hl_lines="1"
+{!../../../docs_src/handling_errors/tutorial001.py!}
+```
+
+### Lance o `HTTPException` no seu código.
+
+`HTTPException`, ao fundo, nada mais é do que a conjunção entre uma exceção comum do Python e informações adicionais relevantes para APIs.
+
+E porque é uma exceção do Python, você não **retorna** (return) o `HTTPException`, você lança o (raise) no seu código.
+
+Isso também significa que, se você está escrevendo uma função de utilidade, a qual você está chamando dentro da sua função de operações de caminhos, e você lança o `HTTPException` dentro da função de utilidade, o resto do seu código não será executado dentro da função de operações de caminhos. Ao contrário, o `HTTPException` irá finalizar a requisição no mesmo instante e enviará o erro HTTP oriundo do `HTTPException` para o cliente.
+
+O benefício de lançar uma exceção em vez de retornar um valor ficará mais evidente na seção sobre Dependências e Segurança.
+
+Neste exemplo, quando o cliente pede, na requisição, por um item cujo ID não existe, a exceção com o status code `404` é lançada:
+
+```Python hl_lines="11"
+{!../../../docs_src/handling_errors/tutorial001.py!}
+```
+
+### A response resultante
+
+
+Se o cliente faz uma requisição para `http://example.com/items/foo` (um `item_id` `"foo"`), esse cliente receberá um HTTP status code 200, e uma resposta JSON:
+
+
+```
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Mas se o cliente faz uma requisição para `http://example.com/items/bar` (ou seja, um não existente `item_id "bar"`), esse cliente receberá um HTTP status code 404 (o erro "não encontrado" — *not found error*), e uma resposta JSON:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+!!! tip "Dica"
+ Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`.
+
+ Você pode passar um `dict` ou um `list`, etc.
+ Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON.
+
+
+## Adicione headers customizados
+
+Há certas situações em que é bastante útil poder adicionar headers customizados no HTTP error. Exemplo disso seria adicionar headers customizados para tipos de segurança.
+
+Você provavelmente não precisará utilizar esses headers diretamente no seu código.
+
+Mas caso você precise, para um cenário mais complexo, você pode adicionar headers customizados:
+
+```Python hl_lines="14"
+{!../../../docs_src/handling_errors/tutorial002.py!}
+```
+
+## Instalando manipuladores de exceções customizados
+
+Você pode adicionar manipuladores de exceção customizados com a mesma seção de utilidade de exceções presentes no Starlette
+
+Digamos que você tenha uma exceção customizada `UnicornException` que você (ou uma biblioteca que você use) precise lançar (`raise`).
+
+Nesse cenário, se você precisa manipular essa exceção de modo global com o FastAPI, você pode adicionar um manipulador de exceção customizada com `@app.exception_handler()`.
+
+```Python hl_lines="5-7 13-18 24"
+{!../../../docs_src/handling_errors/tutorial003.py!}
+```
+
+Nesse cenário, se você fizer uma requisição para `/unicorns/yolo`, a *operação de caminho* vai lançar (`raise`) o `UnicornException`.
+
+Essa exceção será manipulada, contudo, pelo `unicorn_exception_handler`.
+
+Dessa forma você receberá um erro "limpo", com o HTTP status code `418` e um JSON com o conteúdo:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+!!! note "Detalhes Técnicos"
+ Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+
+ **FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`.
+
+## Sobrescreva o manipulador padrão de exceções
+
+**FastAPI** tem alguns manipuladores padrão de exceções.
+
+Esses manipuladores são os responsáveis por retornar o JSON padrão de respostas quando você lança (`raise`) o `HTTPException` e quando a requisição tem dados invalidos.
+
+Você pode sobrescrever esses manipuladores de exceção com os seus próprios manipuladores.
+
+## Sobrescreva exceções de validação da requisição
+
+Quando a requisição contém dados inválidos, **FastAPI** internamente lança para o `RequestValidationError`.
+
+Para sobrescrevê-lo, importe o `RequestValidationError` e use-o com o `@app.exception_handler(RequestValidationError)` para decorar o manipulador de exceções.
+
+```Python hl_lines="2 14-16"
+{!../../../docs_src/handling_errors/tutorial004.py!}
+```
+
+Se você for ao `/items/foo`, em vez de receber o JSON padrão com o erro:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+você receberá a versão em texto:
+
+```
+1 validation error
+path -> item_id
+ value is not a valid integer (type=type_error.integer)
+```
+
+### `RequestValidationError` vs `ValidationError`
+
+!!! warning "Aviso"
+ Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento.
+
+`RequestValidationError` é uma subclasse do
`ValidationError` existente no Pydantic.
+
+**FastAPI** faz uso dele para que você veja o erro no seu log, caso você utilize um modelo de Pydantic em `response_model`, e seus dados tenham erro.
+
+Contudo, o cliente ou usuário não terão acesso a ele. Ao contrário, o cliente receberá um "Internal Server Error" com o HTTP status code `500`.
+
+E assim deve ser porque seria um bug no seu código ter o `ValidationError` do Pydantic na sua *response*, ou em qualquer outro lugar do seu código (que não na requisição do cliente).
+
+E enquanto você conserta o bug, os clientes / usuários não deveriam ter acesso às informações internas do erro, porque, desse modo, haveria exposição de uma vulnerabilidade de segurança.
+
+Do mesmo modo, você pode sobreescrever o `HTTPException`.
+
+Por exemplo, você pode querer retornar uma *response* em *plain text* ao invés de um JSON para os seguintes erros:
+
+```Python hl_lines="3-4 9-11 22"
+{!../../../docs_src/handling_errors/tutorial004.py!}
+```
+
+!!! note "Detalhes Técnicos"
+ Você pode usar `from starlette.responses import PlainTextResponse`.
+
+ **FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette.
+
+
+### Use o body do `RequestValidationError`.
+
+O `RequestValidationError` contém o `body` que ele recebeu de dados inválidos.
+
+Você pode utilizá-lo enquanto desenvolve seu app para conectar o *body* e debugá-lo, e assim retorná-lo ao usuário, etc.
+
+Tente enviar um item inválido como este:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Você receberá uma *response* informando-o de que a data é inválida, e contendo o *body* recebido:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### O `HTTPException` do FastAPI vs o `HTTPException` do Starlette.
+
+O **FastAPI** tem o seu próprio `HTTPException`.
+
+E a classe de erro `HTTPException` do **FastAPI** herda da classe de erro do `HTTPException` do Starlette.
+
+A diferença entre os dois é a de que o `HTTPException` do **FastAPI** permite que você adicione *headers* que serão incluídos nas *responses*.
+
+Esses *headers* são necessários/utilizados internamente pelo OAuth 2.0 e também por outras utilidades de segurança.
+
+Portanto, você pode continuar lançando o `HTTPException` do **FastAPI** normalmente no seu código.
+
+Porém, quando você registrar um manipulador de exceção, você deve registrá-lo através do `HTTPException` do Starlette.
+
+Dessa forma, se qualquer parte do código interno, extensão ou plug-in do Starlette lançar o `HTTPException`, o seu manipulador de exceção poderá capturar esse lançamento e tratá-lo.
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Re-use os manipulares de exceção do **FastAPI**
+
+Se você quer usar a exceção em conjunto com o mesmo manipulador de exceção *default* do **FastAPI**, você pode importar e re-usar esses manipuladores de exceção do `fastapi.exception_handlers`:
+
+```Python hl_lines="2-5 15 21"
+{!../../../docs_src/handling_errors/tutorial006.py!}
+```
+
+Nesse exemplo você apenas imprime (`print`) o erro com uma mensagem expressiva. Mesmo assim, dá para pegar a ideia. Você pode usar a exceção e então apenas re-usar o manipulador de exceção *default*.
diff --git a/docs/pt/docs/tutorial/index.md b/docs/pt/docs/tutorial/index.md
index f93fd8d75c74e..b1abd32bc19ab 100644
--- a/docs/pt/docs/tutorial/index.md
+++ b/docs/pt/docs/tutorial/index.md
@@ -43,7 +43,7 @@ Para o tutorial, você deve querer instalá-lo com todas as dependências e recu
```console
-$ pip install fastapi[all]
+$ pip install "fastapi[all]"
---> 100%
```
@@ -64,7 +64,7 @@ $ pip install fastapi[all]
Também instale o `uvicorn` para funcionar como servidor:
```
- pip install uvicorn[standard]
+ pip install "uvicorn[standard]"
```
E o mesmo para cada dependência opcional que você quiser usar.
diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md
new file mode 100644
index 0000000000000..1897243961b73
--- /dev/null
+++ b/docs/pt/docs/tutorial/query-params.md
@@ -0,0 +1,224 @@
+# Parâmetros de Consulta
+
+Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta".
+
+```Python hl_lines="9"
+{!../../../docs_src/query_params/tutorial001.py!}
+```
+
+A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`.
+
+Por exemplo, na URL:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+...os parâmetros da consulta são:
+
+* `skip`: com o valor `0`
+* `limit`: com o valor `10`
+
+Como eles são parte da URL, eles são "naturalmente" strings.
+
+Mas quando você declara eles com os tipos do Python (no exemplo acima, como `int`), eles são convertidos para aquele tipo e validados em relação a ele.
+
+Todo o processo que era aplicado para parâmetros de rota também é aplicado para parâmetros de consulta:
+
+* Suporte do editor (obviamente)
+*
"Parsing" de dados
+* Validação de dados
+* Documentação automática
+
+## Valores padrão
+
+Como os parâmetros de consulta não são uma parte fixa da rota, eles podem ser opcionais e podem ter valores padrão.
+
+No exemplo acima eles tem valores padrão de `skip=0` e `limit=10`.
+
+Então, se você for até a URL:
+
+```
+http://127.0.0.1:8000/items/
+```
+
+Seria o mesmo que ir para:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+Mas, se por exemplo você for para:
+
+```
+http://127.0.0.1:8000/items/?skip=20
+```
+
+Os valores dos parâmetros na sua função serão:
+
+* `skip=20`: Por que você definiu isso na URL
+* `limit=10`: Por que esse era o valor padrão
+
+## Parâmetros opcionais
+
+Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params/tutorial002.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params/tutorial002_py310.py!}
+ ```
+
+Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão.
+
+!!! check "Verificar"
+ Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta.
+
+
+## Conversão dos tipos de parâmetros de consulta
+
+Você também pode declarar tipos `bool`, e eles serão convertidos:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="9"
+ {!> ../../../docs_src/query_params/tutorial003.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="7"
+ {!> ../../../docs_src/query_params/tutorial003_py310.py!}
+ ```
+
+Nesse caso, se você for para:
+
+```
+http://127.0.0.1:8000/items/foo?short=1
+```
+
+ou
+
+```
+http://127.0.0.1:8000/items/foo?short=True
+```
+
+ou
+
+```
+http://127.0.0.1:8000/items/foo?short=true
+```
+
+ou
+
+```
+http://127.0.0.1:8000/items/foo?short=on
+```
+
+ou
+
+```
+http://127.0.0.1:8000/items/foo?short=yes
+```
+
+ou qualquer outra variação (tudo em maiúscula, primeira letra em maiúscula, etc), a sua função vai ver o parâmetro `short` com um valor `bool` de `True`. Caso contrário `False`.
+
+## Múltiplos parâmetros de rota e consulta
+
+Você pode declarar múltiplos parâmetros de rota e parâmetros de consulta ao mesmo tempo, o **FastAPI** vai saber o quê é o quê.
+
+E você não precisa declarar eles em nenhuma ordem específica.
+
+Eles serão detectados pelo nome:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="8 10"
+ {!> ../../../docs_src/query_params/tutorial004.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="6 8"
+ {!> ../../../docs_src/query_params/tutorial004_py310.py!}
+ ```
+
+## Parâmetros de consulta obrigatórios
+
+Quando você declara um valor padrão para parâmetros que não são de rota (até agora, nós vimos apenas parâmetros de consulta), então eles não são obrigatórios.
+
+Caso você não queira adicionar um valor específico mas queira apenas torná-lo opcional, defina o valor padrão como `None`.
+
+Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão.
+
+```Python hl_lines="6-7"
+{!../../../docs_src/query_params/tutorial005.py!}
+```
+
+Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`.
+
+Se você abrir no seu navegador a URL:
+
+```
+http://127.0.0.1:8000/items/foo-item
+```
+
+... sem adicionar o parâmetro obrigatório `needy`, você verá um erro como:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "field required",
+ "type": "value_error.missing"
+ }
+ ]
+}
+```
+
+Como `needy` é um parâmetro obrigatório, você precisaria defini-lo na URL:
+
+```
+http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
+```
+
+...isso deve funcionar:
+
+```JSON
+{
+ "item_id": "foo-item",
+ "needy": "sooooneedy"
+}
+```
+
+E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais:
+
+=== "Python 3.6 and above"
+
+ ```Python hl_lines="10"
+ {!> ../../../docs_src/query_params/tutorial006.py!}
+ ```
+
+=== "Python 3.10 and above"
+
+ ```Python hl_lines="8"
+ {!> ../../../docs_src/query_params/tutorial006_py310.py!}
+ ```
+Nesse caso, existem 3 parâmetros de consulta:
+
+* `needy`, um `str` obrigatório.
+* `skip`, um `int` com o valor padrão `0`.
+* `limit`, um `int` opcional.
+
+!!! tip "Dica"
+ Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}.
diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..ed07d1c963102
--- /dev/null
+++ b/docs/pt/docs/tutorial/security/first-steps.md
@@ -0,0 +1,181 @@
+# Segurança - Primeiros Passos
+
+Vamos imaginar que você tem a sua API **backend** em algum domínio.
+
+E você tem um **frontend** em outro domínio ou em um path diferente no mesmo domínio (ou em uma aplicação mobile).
+
+E você quer uma maneira de o frontend autenticar o backend, usando um **username** e **senha**.
+
+Nós podemos usar o **OAuth2** junto com o **FastAPI**.
+
+Mas, vamos poupar-lhe o tempo de ler toda a especificação apenas para achar as pequenas informações que você precisa.
+
+Vamos usar as ferramentas fornecidas pela **FastAPI** para lidar com segurança.
+
+## Como Parece
+
+Vamos primeiro usar o código e ver como funciona, e depois voltaremos para entender o que está acontecendo.
+
+## Crie um `main.py`
+Copie o exemplo em um arquivo `main.py`:
+
+```Python
+{!../../../docs_src/security/tutorial001.py!}
+```
+
+## Execute-o
+
+!!! informação
+ Primeiro, instale
`python-multipart`.
+
+ Ex: `pip install python-multipart`.
+
+ Isso ocorre porque o **OAuth2** usa "dados de um formulário" para mandar o **username** e **senha**.
+
+Execute esse exemplo com:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+
+
+## Verifique-o
+
+Vá até a documentação interativa em:
http://127.0.0.1:8000/docs.
+
+Você verá algo deste tipo:
+
+
+
+!!! marque o "botão de Autorizar!"
+ Você já tem um novo "botão de autorizar!".
+
+ E seu *path operation* tem um pequeno cadeado no canto superior direito que você pode clicar.
+
+E se você clicar, você terá um pequeno formulário de autorização para digitar o `username` e `senha` (e outros campos opcionais):
+
+
+
+!!! nota
+ Não importa o que você digita no formulário, não vai funcionar ainda. Mas nós vamos chegar lá.
+
+Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda sua API.
+
+Pode ser usado pelo time de frontend (que pode ser você no caso).
+
+Pode ser usado por aplicações e sistemas third party (de terceiros).
+
+E também pode ser usada por você mesmo, para debugar, checar e testar a mesma aplicação.
+
+## O Fluxo da `senha`
+
+Agora vamos voltar um pouco e entender o que é isso tudo.
+
+O "fluxo" da `senha` é um dos caminhos ("fluxos") definidos no OAuth2, para lidar com a segurança e autenticação.
+
+OAuth2 foi projetado para que o backend ou a API pudesse ser independente do servidor que autentica o usuário.
+
+Mas nesse caso, a mesma aplicação **FastAPI** irá lidar com a API e a autenticação.
+
+Então, vamos rever de um ponto de vista simplificado:
+
+* O usuário digita o `username` e a `senha` no frontend e aperta `Enter`.
+* O frontend (rodando no browser do usuário) manda o `username` e a `senha` para uma URL específica na sua API (declarada com `tokenUrl="token"`).
+* A API checa aquele `username` e `senha`, e responde com um "token" (nós não implementamos nada disso ainda).
+ * Um "token" é apenas uma string com algum conteúdo que nós podemos utilizar mais tarde para verificar o usuário.
+ * Normalmente, um token é definido para expirar depois de um tempo.
+ * Então, o usuário terá que se logar de novo depois de um tempo.
+ * E se o token for roubado, o risco é menor. Não é como se fosse uma chave permanente que vai funcionar para sempre (na maioria dos casos).
+ * O frontend armazena aquele token temporariamente em algum lugar.
+ * O usuário clica no frontend para ir à outra seção daquele frontend do aplicativo web.
+ * O frontend precisa buscar mais dados daquela API.
+ * Mas precisa de autenticação para aquele endpoint em específico.
+ * Então, para autenticar com nossa API, ele manda um header de `Autorização` com o valor `Bearer` mais o token.
+ * Se o token contém `foobar`, o conteúdo do header de `Autorização` será: `Bearer foobar`.
+
+## **FastAPI**'s `OAuth2PasswordBearer`
+
+**FastAPI** fornece várias ferramentas, em diferentes níveis de abstração, para implementar esses recursos de segurança.
+
+Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`.
+
+!!! informação
+ Um token "bearer" não é a única opção.
+
+ Mas é a melhor no nosso caso.
+
+ E talvez seja a melhor para a maioria dos casos, a não ser que você seja um especialista em OAuth2 e saiba exatamente o porquê de existir outras opções que se adequam melhor às suas necessidades.
+
+ Nesse caso, **FastAPI** também fornece as ferramentas para construir.
+
+Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passamos pelo parâmetro `tokenUrl` Esse parâmetro contém a URL que o client (o frontend rodando no browser do usuário) vai usar para mandar o `username` e `senha` para obter um token.
+
+```Python hl_lines="6"
+{!../../../docs_src/security/tutorial001.py!}
+```
+
+!!! dica
+ Esse `tokenUrl="token"` se refere a uma URL relativa que nós não criamos ainda. Como é uma URL relativa, é equivalente a `./token`.
+
+ Porque estamos usando uma URL relativa, se sua API estava localizada em `https://example.com/`, então irá referir-se à `https://example.com/token`. Mas se sua API estava localizada em `https://example.com/api/v1/`, então irá referir-se à `https://example.com/api/v1/token`.
+
+ Usar uma URL relativa é importante para garantir que sua aplicação continue funcionando, mesmo em um uso avançado tipo [Atrás de um Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+
+Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL `/token` vai ser aquela que o client deve usar para obter o token. Essa informação é usada no OpenAPI, e depois na API Interativa de documentação de sistemas.
+
+Em breve também criaremos o atual path operation.
+
+!!! informação
+ Se você é um "Pythonista" muito rigoroso, você pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`.
+
+ Isso ocorre porque está utilizando o mesmo nome que está nas especificações do OpenAPI. Então, se você precisa investigar mais sobre qualquer um desses esquemas de segurança, você pode simplesmente copiar e colar para encontrar mais informações sobre isso.
+
+A variável `oauth2_scheme` é um instância de `OAuth2PasswordBearer`, mas também é um "callable".
+
+Pode ser chamada de:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Então, pode ser usado com `Depends`.
+
+## Use-o
+
+Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`.
+
+```Python hl_lines="10"
+{!../../../docs_src/security/tutorial001.py!}
+```
+
+Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation*
+
+A **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema da OpenAPI (e na documentação da API automática).
+
+!!! informação "Detalhes técnicos"
+ **FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada na dependência) para definir o esquema de segurança na OpenAPI porque herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.Securitybase`.
+
+ Todos os utilitários de segurança que se integram com OpenAPI (e na documentação da API automática) herdam de `SecurityBase`, é assim que **FastAPI** pode saber como integrá-los no OpenAPI.
+
+## O que ele faz
+
+Ele irá e olhará na requisição para aquele header de `Autorização`, verificará se o valor é `Bearer` mais algum token, e vai retornar o token como uma `str`
+
+Se ele não ver o header de `Autorização` ou o valor não tem um token `Bearer`, vai responder com um código de erro 401 (`UNAUTHORIZED`) diretamente.
+
+Você nem precisa verificar se o token existe para retornar um erro. Você pode ter certeza de que se a sua função for executada, ela terá um `str` nesse token.
+
+Você já pode experimentar na documentação interativa:
+
+
+
+Não estamos verificando a validade do token ainda, mas isso já é um começo
+
+## Recapitulando
+
+Então, em apenas 3 ou 4 linhas extras, você já tem alguma forma primitiva de segurança.
diff --git a/docs/pt/mkdocs.yml b/docs/pt/mkdocs.yml
index 2bb0b568d45dd..c37b855d8a0b9 100644
--- a/docs/pt/mkdocs.yml
+++ b/docs/pt/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -62,11 +64,13 @@ nav:
- tutorial/index.md
- tutorial/first-steps.md
- tutorial/path-params.md
+ - tutorial/query-params.md
- tutorial/body.md
- tutorial/body-fields.md
- tutorial/extra-data-types.md
- tutorial/query-params-str-validations.md
- tutorial/cookie-params.md
+ - tutorial/handling-errors.md
- Segurança:
- tutorial/security/index.md
- Guia de Usuário Avançado:
@@ -98,6 +102,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -130,6 +136,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -148,6 +156,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md
index 9a3957d5f6efa..932bb21390ac6 100644
--- a/docs/ru/docs/index.md
+++ b/docs/ru/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md
new file mode 100644
index 0000000000000..e608f6c8f3010
--- /dev/null
+++ b/docs/ru/docs/tutorial/background-tasks.md
@@ -0,0 +1,102 @@
+# Фоновые задачи
+
+Вы можете создавать фоновые задачи, которые будут выполнятся *после* возвращения ответа сервером.
+
+Это может быть полезно для функций, которые должны выполниться после получения запроса, но ожидание их выполнения необязательно для пользователя.
+
+К примеру:
+
+* Отправка писем на почту после выполнения каких-либо действий:
+ * Т.к. соединение с почтовым сервером и отправка письма идут достаточно "долго" (несколько секунд), вы можете отправить ответ пользователю, а отправку письма выполнить в фоне.
+* Обработка данных:
+ * К примеру, если вы получаете файл, который должен пройти через медленный процесс, вы можете отправить ответ "Accepted" (HTTP 202) и отправить работу с файлом в фон.
+
+## Использование класса `BackgroundTasks`
+
+Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`:
+
+```Python hl_lines="1 13"
+{!../../../docs_src/background_tasks/tutorial001.py!}
+```
+
+**FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр.
+
+## Создание функции для фоновой задачи
+
+Создайте функцию, которую хотите запустить в фоне.
+
+Это совершенно обычная функция, которая может принимать параметры.
+
+Она может быть как асинхронной `async def`, так и обычной `def` функцией, **FastAPI** знает, как правильно ее выполнить.
+
+В нашем примере фоновая задача будет вести запись в файл (симулируя отправку письма).
+
+Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`:
+
+```Python hl_lines="6-9"
+{!../../../docs_src/background_tasks/tutorial001.py!}
+```
+
+## Добавление фоновой задачи
+
+Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне:
+
+```Python hl_lines="14"
+{!../../../docs_src/background_tasks/tutorial001.py!}
+```
+
+`.add_task()` принимает следующие аргументы:
+
+* Функцию, которая будет выполнена в фоне (`write_notification`). Обратите внимание, что передается объект функции, без скобок.
+* Любое упорядоченное количество аргументов, которые принимает функция (`email`).
+* Любое количество именованных аргументов, которые принимает функция (`message="some notification"`).
+
+## Встраивание зависимостей
+
+Класс `BackgroundTasks` также работает с системой встраивания зависимостей, вы можете определить `BackgroundTasks` на разных уровнях: как параметр функции, как завимость, как подзависимость и так далее.
+
+**FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне:
+
+=== "Python 3.6 и выше"
+
+ ```Python hl_lines="13 15 22 25"
+ {!> ../../../docs_src/background_tasks/tutorial002.py!}
+ ```
+
+=== "Python 3.10 и выше"
+
+ ```Python hl_lines="11 13 20 23"
+ {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+ ```
+
+В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен.
+
+Если бы в запросе была очередь `q`, она бы первой записалась в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`).
+
+После другая фоновая задача, которая была сгенерирована в функции, запишет сообщение из параметра `email`.
+
+## Технические детали
+
+Класс `BackgroundTasks` основан на `starlette.background`.
+
+Он интегрирован в FastAPI, так что вы можете импортировать его прямо из `fastapi` и избежать случайного импорта `BackgroundTask` (без `s` на конце) из `starlette.background`.
+
+При использовании `BackgroundTasks` (а не `BackgroundTask`), вам достаточно только определить параметр функции с типом `BackgroundTasks` и **FastAPI** сделает все за вас, также как при использовании объекта `Request`.
+
+Вы все равно можете использовать `BackgroundTask` из `starlette` в FastAPI, но вам придется самостоятельно создавать объект фоновой задачи и вручную обработать `Response` внутри него.
+
+Вы можете подробнее изучить его в
Официальной документации Starlette для BackgroundTasks.
+
+## Предостережение
+
+Если вам нужно выполнить тяжелые вычисления в фоне, которым необязательно быть запущенными в одном процессе с приложением **FastAPI** (к примеру, вам не нужны обрабатываемые переменные или вы не хотите делиться памятью процесса и т.д.), вы можете использовать более серьезные инструменты, такие как
Celery.
+
+Их тяжелее настраивать, также им нужен брокер сообщений наподобие RabbitMQ или Redis, но зато они позволяют вам запускать фоновые задачи в нескольких процессах и даже на нескольких серверах.
+
+Для примера, посмотрите [Project Generators](../project-generation.md){.internal-link target=_blank}, там есть проект с уже настроенным Celery.
+
+Но если вам нужен доступ к общим переменным и объектам вашего **FastAPI** приложения или вам нужно выполнять простые фоновые задачи (наподобие отправки письма из примера) вы можете просто использовать `BackgroundTasks`.
+
+## Резюме
+
+Для создания фоновых задач вам необходимо импортировать `BackgroundTasks` и добавить его в функцию, как параметр с типом `BackgroundTasks`.
diff --git a/docs/ru/mkdocs.yml b/docs/ru/mkdocs.yml
index bb0702489da52..f70b436d29774 100644
--- a/docs/ru/mkdocs.yml
+++ b/docs/ru/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,9 +54,14 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
+- python-types.md
+- Учебник - руководство пользователя:
+ - tutorial/background-tasks.md
+- external-links.md
- async.md
markdown_extensions:
- toc:
@@ -74,6 +80,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -106,6 +114,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -124,6 +134,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/sq/docs/index.md b/docs/sq/docs/index.md
index 29f92e020a7a8..2b64003fe8d15 100644
--- a/docs/sq/docs/index.md
+++ b/docs/sq/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/sq/mkdocs.yml b/docs/sq/mkdocs.yml
index 8914395fef8af..b07f3bc637854 100644
--- a/docs/sq/mkdocs.yml
+++ b/docs/sq/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -73,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -105,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -123,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/sv/docs/index.md b/docs/sv/docs/index.md
new file mode 100644
index 0000000000000..fd52f994c83a9
--- /dev/null
+++ b/docs/sv/docs/index.md
@@ -0,0 +1,468 @@
+
+{!../../../docs/missing-translation.md!}
+
+
+
+
+
+
+ FastAPI framework, high performance, easy to learn, fast to code, ready for production
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+---
+
+**Documentation**: https://fastapi.tiangolo.com
+
+**Source Code**:
https://github.com/tiangolo/fastapi
+
+---
+
+FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
+
+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%. *
+* **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.
+* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
+* **Robust**: Get production-ready code. With automatic interactive documentation.
+* **Standards-based**: Based on (and fully compatible with) the open standards for APIs:
OpenAPI (previously known as Swagger) and
JSON Schema.
+
+
* estimation based on tests on an internal development team, building production applications.
+
+## Sponsors
+
+
+
+{% if sponsors %}
+{% for sponsor in sponsors.gold -%}
+
+{% endfor -%}
+{%- for sponsor in sponsors.silver -%}
+
+{% endfor %}
+{% endif %}
+
+
+
+
Other sponsors
+
+## 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._"
+
+
Kabir Khan -
Microsoft (ref)
+
+---
+
+"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
+
+
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala -
Uber (ref)
+
+---
+
+"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
+
+
Kevin Glisson, Marc Vilanova, Forest Monsen -
Netflix (ref)
+
+---
+
+"_I’m over the moon excited about **FastAPI**. It’s so fun!_"
+
+
+
+---
+
+"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._"
+
+
+
+---
+
+"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_"
+
+"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
+
+
+
+---
+
+## **Typer**, the FastAPI of CLIs
+
+
+
+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
+
+Python 3.6+
+
+FastAPI stands on the shoulders of giants:
+
+*
Starlette for the web parts.
+*
Pydantic for the data parts.
+
+## Installation
+
+
+
+```console
+$ pip install fastapi
+
+---> 100%
+```
+
+
+
+You will also need an ASGI server, for production such as
Uvicorn or
Hypercorn.
+
+
+
+```console
+$ pip install "uvicorn[standard]"
+
+---> 100%
+```
+
+
+
+## Example
+
+### Create it
+
+* Create a file `main.py` with:
+
+```Python
+from typing import Union
+
+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: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+```
+
+
+Or use async def
...
+
+If your code uses `async` / `await`, use `async def`:
+
+```Python hl_lines="9 14"
+from typing import Union
+
+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: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+```
+
+**Note**:
+
+If you don't know, check the _"In a hurry?"_ section about `async` and `await` in the docs.
+
+
+
+### Run it
+
+Run the server with:
+
+
+
+```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
...
+
+The command `uvicorn main:app` refers to:
+
+* `main`: the file `main.py` (the Python "module").
+* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
+* `--reload`: make the server restart after code changes. Only do this for development.
+
+
+
+### Check it
+
+Open your browser at
http://127.0.0.1:8000/items/5?q=somequery.
+
+You will see the JSON response as:
+
+```JSON
+{"item_id": 5, "q": "somequery"}
+```
+
+You already created an API that:
+
+* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
+* Both _paths_ take `GET`
operations (also known as HTTP _methods_).
+* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
+* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.
+
+### Interactive API docs
+
+Now go to
http://127.0.0.1:8000/docs.
+
+You will see the automatic interactive API documentation (provided by
Swagger UI):
+
+![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)
+
+### Alternative API docs
+
+And now, go to
http://127.0.0.1:8000/redoc.
+
+You will see the alternative automatic documentation (provided by
ReDoc):
+
+![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)
+
+## Example upgrade
+
+Now modify the file `main.py` to receive a body from a `PUT` request.
+
+Declare the body using standard Python types, thanks to Pydantic.
+
+```Python hl_lines="4 9-12 25-27"
+from typing import Union
+
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+ is_offer: Union[bool, None] = None
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: Union[str, None] = 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}
+```
+
+The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
+
+### Interactive API docs upgrade
+
+Now go to
http://127.0.0.1:8000/docs.
+
+* The interactive API documentation will be automatically updated, including the new body:
+
+![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
+
+* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
+
+![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)
+
+* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
+
+![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)
+
+### Alternative API docs upgrade
+
+And now, go to
http://127.0.0.1:8000/redoc.
+
+* The alternative documentation will also reflect the new query parameter and body:
+
+![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)
+
+### Recap
+
+In summary, you declare **once** the types of parameters, body, etc. as function parameters.
+
+You do that with standard modern Python types.
+
+You don't have to learn a new syntax, the methods or classes of a specific library, etc.
+
+Just standard **Python 3.6+**.
+
+For example, for an `int`:
+
+```Python
+item_id: int
+```
+
+or for a more complex `Item` model:
+
+```Python
+item: Item
+```
+
+...and with that single declaration you get:
+
+* Editor support, including:
+ * Completion.
+ * Type checks.
+* Validation of data:
+ * Automatic and clear errors when the data is invalid.
+ * Validation even for deeply nested JSON objects.
+*
Conversion of input data: coming from the network to Python data and types. Reading from:
+ * JSON.
+ * Path parameters.
+ * Query parameters.
+ * Cookies.
+ * Headers.
+ * Forms.
+ * Files.
+*
Conversion of output data: converting from Python data and types to network data (as JSON):
+ * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
+ * `datetime` objects.
+ * `UUID` objects.
+ * Database models.
+ * ...and many more.
+* Automatic interactive API documentation, including 2 alternative user interfaces:
+ * Swagger UI.
+ * ReDoc.
+
+---
+
+Coming back to the previous code example, **FastAPI** will:
+
+* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
+* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
+ * If it is not, the client will see a useful, clear error.
+* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests.
+ * As the `q` parameter is declared with `= None`, it is optional.
+ * Without the `None` it would be required (as is the body in the case with `PUT`).
+* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
+ * Check that it has a required attribute `name` that should be a `str`.
+ * Check that it has a required attribute `price` that has to be a `float`.
+ * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
+ * All this would also work for deeply nested JSON objects.
+* Convert from and to JSON automatically.
+* Document everything with OpenAPI, that can be used by:
+ * Interactive documentation systems.
+ * Automatic client code generation systems, for many languages.
+* Provide 2 interactive documentation web interfaces directly.
+
+---
+
+We just scratched the surface, but you already get the idea of how it all works.
+
+Try changing the line with:
+
+```Python
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+...from:
+
+```Python
+ ... "item_name": item.name ...
+```
+
+...to:
+
+```Python
+ ... "item_price": item.price ...
+```
+
+...and see how your editor will auto-complete the attributes and know their types:
+
+![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)
+
+For a more complete example including more features, see the
Tutorial - User Guide.
+
+**Spoiler alert**: the tutorial - user guide includes:
+
+* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
+* How to set **validation constraints** as `maximum_length` or `regex`.
+* A very powerful and easy to use **
Dependency Injection** system.
+* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
+* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
+* **GraphQL** integration with
Strawberry and other libraries.
+* Many extra features (thanks to Starlette) as:
+ * **WebSockets**
+ * extremely easy tests based on `requests` and `pytest`
+ * **CORS**
+ * **Cookie Sessions**
+ * ...and more.
+
+## Performance
+
+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). (*)
+
+To understand more about it, see the section
Benchmarks.
+
+## Optional Dependencies
+
+Used by Pydantic:
+
+*
ujson
- for faster JSON
"parsing".
+*
email_validator
- for email validation.
+
+Used by Starlette:
+
+*
requests
- Required if you want to use the `TestClient`.
+*
jinja2
- Required if you want to use the default template configuration.
+*
python-multipart
- Required if you want to support form
"parsing", with `request.form()`.
+*
itsdangerous
- Required for `SessionMiddleware` support.
+*
pyyaml
- Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
+*
ujson
- Required if you want to use `UJSONResponse`.
+
+Used by FastAPI / Starlette:
+
+*
uvicorn
- for the server that loads and serves your application.
+*
orjson
- Required if you want to use `ORJSONResponse`.
+
+You can install all of these with `pip install "fastapi[all]"`.
+
+## License
+
+This project is licensed under the terms of the MIT license.
diff --git a/docs/sv/mkdocs.yml b/docs/sv/mkdocs.yml
new file mode 100644
index 0000000000000..3332d232d646c
--- /dev/null
+++ b/docs/sv/mkdocs.yml
@@ -0,0 +1,145 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/sv/
+theme:
+ name: material
+ custom_dir: overrides
+ palette:
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb
+ name: Switch to light mode
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb-outline
+ name: Switch to dark mode
+ features:
+ - search.suggest
+ - search.highlight
+ - content.tabs.link
+ icon:
+ repo: fontawesome/brands/github-alt
+ logo: https://fastapi.tiangolo.com/img/icon-white.svg
+ favicon: https://fastapi.tiangolo.com/img/favicon.png
+ language: sv
+repo_name: tiangolo/fastapi
+repo_url: https://github.com/tiangolo/fastapi
+edit_uri: ''
+plugins:
+- search
+- markdownextradata:
+ data: data
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - az: /az/
+ - de: /de/
+ - es: /es/
+ - fa: /fa/
+ - fr: /fr/
+ - he: /he/
+ - id: /id/
+ - it: /it/
+ - ja: /ja/
+ - ko: /ko/
+ - nl: /nl/
+ - pl: /pl/
+ - pt: /pt/
+ - ru: /ru/
+ - sq: /sq/
+ - sv: /sv/
+ - tr: /tr/
+ - uk: /uk/
+ - zh: /zh/
+markdown_extensions:
+- toc:
+ permalink: true
+- markdown.extensions.codehilite:
+ guess_lang: false
+- mdx_include:
+ base_path: docs
+- admonition
+- codehilite
+- extra
+- pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_code_format ''
+- pymdownx.tabbed:
+ alternate_style: true
+- attr_list
+- md_in_html
+extra:
+ analytics:
+ provider: google
+ property: UA-133183413-1
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/tiangolo/fastapi
+ - icon: fontawesome/brands/discord
+ link: https://discord.gg/VQjSZaeJmf
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/fastapi
+ - 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
+ alternate:
+ - link: /
+ name: en - English
+ - link: /az/
+ name: az
+ - link: /de/
+ name: de
+ - link: /es/
+ name: es - español
+ - link: /fa/
+ name: fa
+ - link: /fr/
+ name: fr - français
+ - link: /he/
+ name: he
+ - link: /id/
+ name: id
+ - link: /it/
+ name: it - italiano
+ - link: /ja/
+ name: ja - 日本語
+ - link: /ko/
+ name: ko - 한국어
+ - link: /nl/
+ name: nl
+ - link: /pl/
+ name: pl
+ - link: /pt/
+ name: pt - português
+ - link: /ru/
+ name: ru - русский язык
+ - link: /sq/
+ name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
+ - link: /tr/
+ name: tr - Türkçe
+ - link: /uk/
+ name: uk - українська мова
+ - link: /zh/
+ name: zh - 汉语
+extra_css:
+- https://fastapi.tiangolo.com/css/termynal.css
+- https://fastapi.tiangolo.com/css/custom.css
+extra_javascript:
+- https://fastapi.tiangolo.com/js/termynal.js
+- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/sv/overrides/.gitignore b/docs/sv/overrides/.gitignore
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md
index 5693029b528a1..0d5337c87462d 100644
--- a/docs/tr/docs/index.md
+++ b/docs/tr/docs/index.md
@@ -143,7 +143,7 @@ Uygulamanı kullanılabilir hale getirmek için
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/tr/mkdocs.yml b/docs/tr/mkdocs.yml
index 74186033c6d8a..e29d259365077 100644
--- a/docs/tr/mkdocs.yml
+++ b/docs/tr/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -76,6 +78,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -108,6 +112,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -126,6 +132,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md
index 29f92e020a7a8..2b64003fe8d15 100644
--- a/docs/uk/docs/index.md
+++ b/docs/uk/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/uk/mkdocs.yml b/docs/uk/mkdocs.yml
index ddf299d8b64f4..7113287710bab 100644
--- a/docs/uk/mkdocs.yml
+++ b/docs/uk/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -73,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -105,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -123,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..3e53c53191a4c
--- /dev/null
+++ b/docs/zh/docs/advanced/response-cookies.md
@@ -0,0 +1,47 @@
+# 响应Cookies
+
+## 使用 `Response` 参数
+
+你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。
+
+```Python hl_lines="1 8-9"
+{!../../../docs_src/response_cookies/tutorial002.py!}
+```
+
+而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。
+
+如果你定义了 `response_model`,程序会自动根据`response_model`来过滤和转换你响应的对象。
+
+**FastAPI** 会使用这个 *临时* 响应对象去装在这些cookies信息 (同样还有headers和状态码等信息), 最终会将这些信息和通过`response_model`转化过的数据合并到最终的响应里。
+
+你也可以在depend中定义`Response`参数,并设置cookie和header。
+
+## 直接响应 `Response`
+
+你还可以在直接响应`Response`时直接创建cookies。
+
+你可以参考[Return a Response Directly](response-directly.md){.internal-link target=_blank}来创建response
+
+然后设置Cookies,并返回:
+
+```Python hl_lines="10-12"
+{!../../../docs_src/response_cookies/tutorial001.py!}
+```
+
+!!! tip
+ 需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。
+
+ 所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。
+
+ 同时,你也应当仅反馈通过`response_model`过滤过的数据。
+
+### 更多信息
+
+!!! note "技术细节"
+ 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。
+
+ 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。
+
+ 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。
+
+如果你想查看所有可用的参数和选项,可以参考 Starlette帮助文档
diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md
index 797032c865f22..3898beaee0677 100644
--- a/docs/zh/docs/index.md
+++ b/docs/zh/docs/index.md
@@ -131,7 +131,7 @@ $ pip install fastapi
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md
index 36495ec0b8fb8..6093caeb601ca 100644
--- a/docs/zh/docs/tutorial/index.md
+++ b/docs/zh/docs/tutorial/index.md
@@ -43,7 +43,7 @@ $ uvicorn main:app --reload
```console
-$ pip install fastapi[all]
+$ pip install "fastapi[all]"
---> 100%
```
@@ -64,7 +64,7 @@ $ pip install fastapi[all]
并且安装`uvicorn`来作为服务器:
```
- pip install uvicorn[standard]
+ pip install "uvicorn[standard]"
```
然后对你想使用的每个可选依赖项也执行相同的操作。
diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..116572411c918
--- /dev/null
+++ b/docs/zh/docs/tutorial/security/first-steps.md
@@ -0,0 +1,189 @@
+# 安全 - 第一步
+
+假设**后端** API 在某个域。
+
+**前端**在另一个域,或(移动应用中)在同一个域的不同路径下。
+
+并且,前端要使用后端的 **username** 与 **password** 验证用户身份。
+
+固然,**FastAPI** 支持 **OAuth2** 身份验证。
+
+但为了节省开发者的时间,不要只为了查找很少的内容,不得不阅读冗长的规范文档。
+
+我们建议使用 **FastAPI** 的安全工具。
+
+## 概览
+
+首先,看看下面的代码是怎么运行的,然后再回过头来了解其背后的原理。
+
+## 创建 `main.py`
+
+把下面的示例代码复制到 `main.py`:
+
+```Python
+{!../../../docs_src/security/tutorial001.py!}
+```
+
+## 运行
+
+!!! info "说明"
+
+ 先安装
`python-multipart`。
+
+ 安装命令: `pip install python-multipart`。
+
+ 这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。
+
+用下面的命令运行该示例:
+
+
+
+```console
+$ uvicorn main:app --reload
+
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+```
+
+
+
+## 查看文档
+
+打开 API 文档:
http://127.0.0.1:8000/docs。
+
+界面如下图所示:
+
+
+
+!!! check "Authorize 按钮!"
+
+ 页面右上角出现了一个「**Authorize**」按钮。
+
+ *路径操作*的右上角也出现了一个可以点击的小锁图标。
+
+点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段:
+
+
+
+!!! note "笔记"
+
+ 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。
+
+虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。
+
+前端团队(可能就是开发者本人)可以使用本工具。
+
+第三方应用与系统也可以调用本工具。
+
+开发者也可以用它来调试、检查、测试应用。
+
+## 密码流
+
+现在,我们回过头来介绍这段代码的原理。
+
+`Password` **流**是 OAuth2 定义的,用于处理安全与身份验证的方式(**流**)。
+
+OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户身份。
+
+但在本例中,**FastAPI** 应用会处理 API 与身份验证。
+
+下面,我们来看一下简化的运行流程:
+
+- 用户在前端输入 `username` 与`password`,并点击**回车**
+- (用户浏览器中运行的)前端把 `username` 与`password` 发送至 API 中指定的 URL(使用 `tokenUrl="token"` 声明)
+- API 检查 `username` 与`password`,并用令牌(`Token`) 响应(暂未实现此功能):
+ - 令牌只是用于验证用户的字符串
+ - 一般来说,令牌会在一段时间后过期
+ - 过时后,用户要再次登录
+ - 这样一来,就算令牌被人窃取,风险也较低。因为它与永久密钥不同,**在绝大多数情况下**不会长期有效
+- 前端临时将令牌存储在某个位置
+- 用户点击前端,前往前端应用的其它部件
+- 前端需要从 API 中提取更多数据:
+ - 为指定的端点(Endpoint)进行身份验证
+ - 因此,用 API 验证身份时,要发送值为 `Bearer` + 令牌的请求头 `Authorization`
+ - 假如令牌为 `foobar`,`Authorization` 请求头就是: `Bearer foobar`
+
+## **FastAPI** 的 `OAuth2PasswordBearer`
+
+**FastAPI** 提供了不同抽象级别的安全工具。
+
+本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。
+
+!!! info "说明"
+
+ `Beare` 令牌不是唯一的选择。
+
+ 但它是最适合这个用例的方案。
+
+ 甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。
+
+ 本例中,**FastAPI** 还提供了构建工具。
+
+创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。
+
+```Python hl_lines="6"
+{!../../../docs_src/security/tutorial001.py!}
+```
+
+!!! tip "提示"
+
+ 在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。
+
+ 因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。
+
+ 使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。
+
+该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。
+
+接下来,学习如何创建实际的路径操作。
+
+!!! info "说明"
+
+ 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。
+
+ 这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。
+
+`oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。
+
+以如下方式调用:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+因此,`Depends` 可以调用 `oauth2_scheme` 变量。
+
+### 使用
+
+接下来,使用 `Depends` 把 `oauth2_scheme` 传入依赖项。
+
+```Python hl_lines="10"
+{!../../../docs_src/security/tutorial001.py!}
+```
+
+该依赖项使用字符串(`str`)接收*路径操作函数*的参数 `token` 。
+
+**FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。
+
+!!! info "技术细节"
+
+ **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。
+
+ 所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。
+
+## 实现的操作
+
+FastAPI 校验请求中的 `Authorization` 请求头,核对请求头的值是不是由 `Bearer ` + 令牌组成, 并返回令牌字符串(`str`)。
+
+如果没有找到 `Authorization` 请求头,或请求头的值不是 `Bearer ` + 令牌。FastAPI 直接返回 401 错误状态码(`UNAUTHORIZED`)。
+
+开发者不需要检查错误信息,查看令牌是否存在,只要该函数能够执行,函数中就会包含令牌字符串。
+
+正如下图所示,API 文档已经包含了这项功能:
+
+
+
+目前,暂时还没有实现验证令牌是否有效的功能,不过后文很快就会介绍的。
+
+## 小结
+
+看到了吧,只要多写三四行代码,就可以添加基础的安全表单。
diff --git a/docs/zh/mkdocs.yml b/docs/zh/mkdocs.yml
index a72ecb6576ab9..b60a0b7a188b5 100644
--- a/docs/zh/mkdocs.yml
+++ b/docs/zh/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -91,6 +93,7 @@ nav:
- tutorial/dependencies/global-dependencies.md
- 安全性:
- 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
@@ -104,6 +107,7 @@ nav:
- advanced/additional-status-codes.md
- advanced/response-directly.md
- advanced/custom-response.md
+ - advanced/response-cookies.md
- contributing.md
- help-fastapi.md
- benchmarks.md
@@ -124,6 +128,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -156,6 +162,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -174,6 +182,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs_src/additional_responses/tutorial001.py b/docs_src/additional_responses/tutorial001.py
index 79dcc2efee601..ffa821b910a84 100644
--- a/docs_src/additional_responses/tutorial001.py
+++ b/docs_src/additional_responses/tutorial001.py
@@ -19,5 +19,4 @@ class Message(BaseModel):
async def read_item(item_id: str):
if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
- else:
- return JSONResponse(status_code=404, content={"message": "Item not found"})
+ return JSONResponse(status_code=404, content={"message": "Item not found"})
diff --git a/docs_src/path_params/tutorial005.py b/docs_src/path_params/tutorial005.py
index 8e376774492ce..9a24a4963a188 100644
--- a/docs_src/path_params/tutorial005.py
+++ b/docs_src/path_params/tutorial005.py
@@ -14,7 +14,7 @@ class ModelName(str, Enum):
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
- if model_name == ModelName.alexnet:
+ if model_name is ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW!"}
if model_name.value == "lenet":
diff --git a/docs_src/security/tutorial007.py b/docs_src/security/tutorial007.py
index 90b9ac0546ff5..790ee10bc6b1d 100644
--- a/docs_src/security/tutorial007.py
+++ b/docs_src/security/tutorial007.py
@@ -9,9 +9,17 @@
def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
- correct_username = secrets.compare_digest(credentials.username, "stanleyjobson")
- correct_password = secrets.compare_digest(credentials.password, "swordfish")
- if not (correct_username and correct_password):
+ current_username_bytes = credentials.username.encode("utf8")
+ correct_username_bytes = b"stanleyjobson"
+ is_correct_username = secrets.compare_digest(
+ current_username_bytes, correct_username_bytes
+ )
+ current_password_bytes = credentials.password.encode("utf8")
+ correct_password_bytes = b"swordfish"
+ is_correct_password = secrets.compare_digest(
+ current_password_bytes, correct_password_bytes
+ )
+ if not (is_correct_username and is_correct_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
diff --git a/fastapi/__init__.py b/fastapi/__init__.py
index 2465e2c274a49..3dc86cadf0deb 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.78.0"
+__version__ = "0.80.0"
from starlette import status as status
diff --git a/fastapi/applications.py b/fastapi/applications.py
index 7530ddb9b8fef..ac6050ca4ff56 100644
--- a/fastapi/applications.py
+++ b/fastapi/applications.py
@@ -273,7 +273,7 @@ def add_api_route(
path: str,
endpoint: Callable[..., Coroutine[Any, Any, Response]],
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -331,7 +331,7 @@ def api_route(
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -434,7 +434,7 @@ def get(
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -489,7 +489,7 @@ def put(
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -544,7 +544,7 @@ def post(
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -599,7 +599,7 @@ def delete(
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -654,7 +654,7 @@ def options(
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -709,7 +709,7 @@ def head(
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -764,7 +764,7 @@ def patch(
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -819,7 +819,7 @@ def trace(
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py
index f397e333c0928..d098b65f1a5f5 100644
--- a/fastapi/dependencies/utils.py
+++ b/fastapi/dependencies/utils.py
@@ -34,6 +34,7 @@
from pydantic.error_wrappers import ErrorWrapper
from pydantic.errors import MissingError
from pydantic.fields import (
+ SHAPE_FROZENSET,
SHAPE_LIST,
SHAPE_SEQUENCE,
SHAPE_SET,
@@ -58,6 +59,7 @@
sequence_shapes = {
SHAPE_LIST,
SHAPE_SET,
+ SHAPE_FROZENSET,
SHAPE_TUPLE,
SHAPE_SEQUENCE,
SHAPE_TUPLE_ELLIPSIS,
@@ -161,7 +163,6 @@ def get_sub_dependant(
)
if security_requirement:
sub_dependant.security_requirements.append(security_requirement)
- sub_dependant.security_scopes = security_scopes
return sub_dependant
@@ -278,7 +279,13 @@ def get_dependant(
path_param_names = get_path_param_names(path)
endpoint_signature = get_typed_signature(call)
signature_params = endpoint_signature.parameters
- dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache)
+ dependant = Dependant(
+ call=call,
+ name=name,
+ path=path,
+ security_scopes=security_scopes,
+ use_cache=use_cache,
+ )
for param_name, param in signature_params.items():
if isinstance(param.default, params.Depends):
sub_dependant = get_param_sub_dependant(
@@ -295,10 +302,7 @@ def get_dependant(
assert is_scalar_field(
field=param_field
), "Path params must be of one of the supported types"
- if isinstance(param.default, params.Path):
- ignore_default = False
- else:
- ignore_default = True
+ ignore_default = not isinstance(param.default, params.Path)
param_field = get_param_field(
param=param,
param_name=param_name,
@@ -495,7 +499,6 @@ async def solve_dependencies(
name=sub_dependant.name,
security_scopes=sub_dependant.security_scopes,
)
- use_sub_dependant.security_scopes = sub_dependant.security_scopes
solved_result = await solve_dependencies(
request=request,
diff --git a/fastapi/encoders.py b/fastapi/encoders.py
index 4b7ffe313fa6b..6f571edb261d7 100644
--- a/fastapi/encoders.py
+++ b/fastapi/encoders.py
@@ -80,6 +80,11 @@ def jsonable_encoder(
return obj
if isinstance(obj, dict):
encoded_dict = {}
+ allowed_keys = set(obj.keys())
+ if include is not None:
+ allowed_keys &= set(include)
+ if exclude is not None:
+ allowed_keys -= set(exclude)
for key, value in obj.items():
if (
(
@@ -88,7 +93,7 @@ def jsonable_encoder(
or (not key.startswith("_sa"))
)
and (value is not None or not exclude_none)
- and ((include and key in include) or not exclude or key not in exclude)
+ and key in allowed_keys
):
encoded_key = jsonable_encoder(
key,
@@ -132,10 +137,10 @@ def jsonable_encoder(
if isinstance(obj, classes_tuple):
return encoder(obj)
- errors: List[Exception] = []
try:
data = dict(obj)
except Exception as e:
+ errors: List[Exception] = []
errors.append(e)
try:
data = vars(obj)
@@ -144,6 +149,8 @@ def jsonable_encoder(
raise ValueError(errors)
return jsonable_encoder(
data,
+ include=include,
+ exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
diff --git a/fastapi/openapi/constants.py b/fastapi/openapi/constants.py
index 3e69e55244af6..1897ad750915e 100644
--- a/fastapi/openapi/constants.py
+++ b/fastapi/openapi/constants.py
@@ -1,3 +1,2 @@
METHODS_WITH_BODY = {"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"}
-STATUS_CODES_WITH_NO_BODY = {100, 101, 102, 103, 204, 304}
REF_PREFIX = "#/components/schemas/"
diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py
index e630d9a9f9620..bf335118fc791 100644
--- a/fastapi/openapi/docs.py
+++ b/fastapi/openapi/docs.py
@@ -118,12 +118,14 @@ def get_redoc_html(
def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse:
+ # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html
html = """
-
+
-
-
-
+
+
Swagger UI: OAuth2 Redirect
+
+
+
+