mirror of
https://github.com/fastapi/fastapi.git
synced 2025-12-28 00:30:58 -05:00
Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0388915a8 | ||
|
|
9e2f5c67b6 | ||
|
|
93e4a19e35 | ||
|
|
e1c6d7d310 | ||
|
|
d23b295b96 | ||
|
|
26e94116c1 | ||
|
|
24968937e5 | ||
|
|
5c5b889288 | ||
|
|
436261b3ea | ||
|
|
5c62a59e7b | ||
|
|
acbe79da37 | ||
|
|
a85aa125d2 | ||
|
|
9af8cc69d5 | ||
|
|
7fe79441c1 | ||
|
|
b8ae84d460 | ||
|
|
ca2b1dbb64 |
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -233,3 +233,82 @@ Now, to be able to test that everything works, create a *path operation*:
|
||||
Now, you should be able to disconnect your WiFi, go to your docs at <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>, and reload the page.
|
||||
|
||||
And even without Internet, you would be able to see the docs for your API and interact with it.
|
||||
|
||||
## Configuring Swagger UI
|
||||
|
||||
You can configure some extra <a href="https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration" class="external-link" target="_blank">Swagger UI parameters</a>.
|
||||
|
||||
To configure them, pass the `swagger_ui_parameters` argument when creating the `FastAPI()` app object or to the `get_swagger_ui_html()` function.
|
||||
|
||||
`swagger_ui_parameters` receives a dictionary with the configurations passed to Swagger UI directly.
|
||||
|
||||
FastAPI converts the configurations to **JSON** to make them compatible with JavaScript, as that's what Swagger UI needs.
|
||||
|
||||
### Disable Syntax Highlighting
|
||||
|
||||
For example, you could disable syntax highlighting in Swagger UI.
|
||||
|
||||
Without changing the settings, syntax highlighting is enabled by default:
|
||||
|
||||
<img src="/img/tutorial/extending-openapi/image02.png">
|
||||
|
||||
But you can disable it by setting `syntaxHighlight` to `False`:
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!../../../docs_src/extending_openapi/tutorial003.py!}
|
||||
```
|
||||
|
||||
...and then Swagger UI won't show the syntax highlighting anymore:
|
||||
|
||||
<img src="/img/tutorial/extending-openapi/image03.png">
|
||||
|
||||
### Change the Theme
|
||||
|
||||
The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle):
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!../../../docs_src/extending_openapi/tutorial004.py!}
|
||||
```
|
||||
|
||||
That configuration would change the syntax highlighting color theme:
|
||||
|
||||
<img src="/img/tutorial/extending-openapi/image04.png">
|
||||
|
||||
### Change Default Swagger UI Parameters
|
||||
|
||||
FastAPI includes some default configuration parameters appropriate for most of the use cases.
|
||||
|
||||
It includes these default configurations:
|
||||
|
||||
```Python
|
||||
{!../../../fastapi/openapi/docs.py[ln:7-13]!}
|
||||
```
|
||||
|
||||
You can override any of them by setting a different value in the argument `swagger_ui_parameters`.
|
||||
|
||||
For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`:
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!../../../docs_src/extending_openapi/tutorial005.py!}
|
||||
```
|
||||
|
||||
### Other Swagger UI Parameters
|
||||
|
||||
To see all the other possible configurations you can use, read the official <a href="https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration" class="external-link" target="_blank">docs for Swagger UI parameters</a>.
|
||||
|
||||
### JavaScript-only settings
|
||||
|
||||
Swagger UI also allows other configurations to be **JavaScript-only** objects (for example, JavaScript functions).
|
||||
|
||||
FastAPI also includes these JavaScript-only `presets` settings:
|
||||
|
||||
```JavaScript
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIBundle.SwaggerUIStandalonePreset
|
||||
]
|
||||
```
|
||||
|
||||
These are **JavaScript** objects, not strings, so you can't pass them from Python code directly.
|
||||
|
||||
If you need to use JavaScript-only configurations like those, you can use one of the methods above. Override all the Swagger UI *path operation* and manually write any JavaScript you need.
|
||||
|
||||
BIN
docs/en/docs/img/tutorial/extending-openapi/image02.png
Normal file
BIN
docs/en/docs/img/tutorial/extending-openapi/image02.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
BIN
docs/en/docs/img/tutorial/extending-openapi/image03.png
Normal file
BIN
docs/en/docs/img/tutorial/extending-openapi/image03.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
BIN
docs/en/docs/img/tutorial/extending-openapi/image04.png
Normal file
BIN
docs/en/docs/img/tutorial/extending-openapi/image04.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
@@ -252,7 +252,7 @@ The second type parameter is for the values of the `dict`:
|
||||
=== "Python 3.9 and above"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/python_types/tutorial008.py!}
|
||||
{!> ../../../docs_src/python_types/tutorial008_py39.py!}
|
||||
```
|
||||
|
||||
This means:
|
||||
|
||||
@@ -2,6 +2,28 @@
|
||||
|
||||
## Latest Changes
|
||||
|
||||
|
||||
## 0.72.0
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Enable configuring Swagger UI parameters. Original PR [#2568](https://github.com/tiangolo/fastapi/pull/2568) by [@jmriebold](https://github.com/jmriebold). Here are the new docs: [Configuring Swagger UI](https://fastapi.tiangolo.com/advanced/extending-openapi/#configuring-swagger-ui).
|
||||
|
||||
### Docs
|
||||
|
||||
* 📝 Update Python Types docs, add missing 3.6 / 3.9 example. PR [#4434](https://github.com/tiangolo/fastapi/pull/4434) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Translations
|
||||
|
||||
* 🌐 Update Chinese translation for `docs/help-fastapi.md`. PR [#3847](https://github.com/tiangolo/fastapi/pull/3847) by [@jaystone776](https://github.com/jaystone776).
|
||||
* 🌐 Fix Korean translation for `docs/ko/docs/index.md`. PR [#4195](https://github.com/tiangolo/fastapi/pull/4195) by [@kty4119](https://github.com/kty4119).
|
||||
* 🌐 Add Polish translation for `docs/pl/docs/index.md`. PR [#4245](https://github.com/tiangolo/fastapi/pull/4245) by [@MicroPanda123](https://github.com/MicroPanda123).
|
||||
* 🌐 Add Chinese translation for `docs\tutorial\path-operation-configuration.md`. PR [#3312](https://github.com/tiangolo/fastapi/pull/3312) by [@jaystone776](https://github.com/jaystone776).
|
||||
|
||||
### Internal
|
||||
|
||||
* 🔧 Enable MkDocs Material Insiders' `content.tabs.link`. PR [#4399](https://github.com/tiangolo/fastapi/pull/4399) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.71.0
|
||||
|
||||
### Features
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -35,7 +35,7 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트
|
||||
* **직관적**: 훌륭한 편집기 지원. 모든 곳에서 <abbr title="also known as auto-complete, autocompletion, IntelliSense">자동완성</abbr>. 적은 디버깅 시간.
|
||||
* **쉬움**: 쉽게 사용하고 배우도록 설계. 적은 문서 읽기 시간.
|
||||
* **짧음**: 코드 중복 최소화. 각 매개변수 선언의 여러 기능. 적은 버그.
|
||||
* **견고함**: 준비된 프로덕션 용 코드를 얻으세요. 자동 대화형 문서와 함께.
|
||||
* **견고함**: 준비된 프로덕션 용 코드를 얻으십시오. 자동 대화형 문서와 함께.
|
||||
* **표준 기반**: API에 대한 (완전히 호환되는) 개방형 표준 기반: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (이전에 Swagger로 알려졌던) 및 <a href="http://json-schema.org/" class="external-link" target="_blank">JSON 스키마</a>.
|
||||
|
||||
<small>* 내부 개발팀의 프로덕션 애플리케이션을 빌드한 테스트에 근거한 측정</small>
|
||||
@@ -89,9 +89,9 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트
|
||||
|
||||
---
|
||||
|
||||
"_REST API를 만들기 위해 **현대적인 프레임워크**를 찾고 있다면 **FastAPI**를 확인해 보세요. [...] 빠르고, 쓰기 쉽고, 배우기도 쉽습니다 [...]_"
|
||||
"_REST API를 만들기 위해 **현대적인 프레임워크**를 찾고 있다면 **FastAPI**를 확인해 보십시오. [...] 빠르고, 쓰기 쉽고, 배우기도 쉽습니다 [...]_"
|
||||
|
||||
"_우리 **API**를 **FastAPI**로 바꿨습니다 [...] 아마 여러분도 좋아하실 겁니다 [...]_"
|
||||
"_우리 **API**를 **FastAPI**로 바꿨습니다 [...] 아마 여러분도 좋아하실 것입니다 [...]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> 설립자 - <a href="https://spacy.io" target="_blank">spaCy</a> 제작자</strong> <a href="https://twitter.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://twitter.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
@@ -193,7 +193,7 @@ async def read_item(item_id: int, q: Optional[str] = None):
|
||||
|
||||
### 실행하기
|
||||
|
||||
서버를 실행하세요:
|
||||
서버를 실행하십시오:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -239,7 +239,7 @@ INFO: Application startup complete.
|
||||
|
||||
### 대화형 API 문서
|
||||
|
||||
이제 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>로 가보세요.
|
||||
이제 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>로 가보십시오.
|
||||
|
||||
자동 대화형 API 문서를 볼 수 있습니다 (<a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> 제공):
|
||||
|
||||
@@ -388,7 +388,7 @@ item: Item
|
||||
|
||||
우리는 그저 수박 겉핡기만 했을 뿐인데 여러분은 벌써 어떻게 작동하는지 알고 있습니다.
|
||||
|
||||
다음 줄을 바꿔보세요:
|
||||
다음 줄을 바꿔보십시오:
|
||||
|
||||
```Python
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
@@ -447,7 +447,7 @@ Starlette이 사용하는:
|
||||
* <a href="http://jinja.pocoo.org" target="_blank"><code>jinja2</code></a> - 기본 템플릿 설정을 사용하려면 필요.
|
||||
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - `request.form()`과 함께 <abbr title="HTTP 요청에서 파이썬 데이터로 가는 문자열 변환">"parsing"</abbr>의 지원을 원하면 필요.
|
||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` 지원을 위해 필요.
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요가 없을 겁니다).
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요 없을 것입니다).
|
||||
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - `GraphQLApp` 지원을 위해 필요.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - `UJSONResponse`를 사용하려면 필요.
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
|
||||
{!../../../docs/missing-translation.md!}
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<em>FastAPI framework, high performance, easy to learn, fast to code, ready for production</em>
|
||||
<em>FastAPI to szybki, prosty w nauce i gotowy do użycia w produkcji framework</em>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank">
|
||||
@@ -22,29 +18,28 @@
|
||||
|
||||
---
|
||||
|
||||
**Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
|
||||
**Dokumentacja**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
|
||||
|
||||
**Source Code**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
|
||||
**Kod żródłowy**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
|
||||
|
||||
---
|
||||
|
||||
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
|
||||
FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona 3.6+ bazujący na standardowym typowaniu Pythona.
|
||||
|
||||
The key features are:
|
||||
Kluczowe cechy:
|
||||
|
||||
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
|
||||
* **Wydajność**: FastAPI jest bardzo wydajny, na równi z **NodeJS** oraz **Go** (dzięki Starlette i Pydantic). [Jeden z najszybszych dostępnych frameworków Pythonowych](#wydajnosc).
|
||||
* **Szybkość kodowania**: Przyśpiesza szybkość pisania nowych funkcjonalności o około 200% do 300%. *
|
||||
* **Mniejsza ilość błędów**: Zmniejsza ilość ludzkich (dewelopera) błędy o około 40%. *
|
||||
* **Intuicyjność**: Wspaniałe wsparcie dla edytorów kodu. Dostępne wszędzie <abbr title="znane jako auto-complete, autocompletion, IntelliSense">automatyczne uzupełnianie</abbr> kodu. Krótszy czas debugowania.
|
||||
* **Łatwość**: Zaprojektowany by być prosty i łatwy do nauczenia. Mniej czasu spędzonego na czytanie dokumentacji.
|
||||
* **Kompaktowość**: Minimalizacja powtarzającego się kodu. Wiele funkcjonalności dla każdej deklaracji parametru. Mniej błędów.
|
||||
* **Solidność**: Kod gotowy dla środowiska produkcyjnego. Wraz z automatyczną interaktywną dokumentacją.
|
||||
* **Bazujący na standardach**: Oparty na (i w pełni kompatybilny z) otwartych standardach API: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (wcześniej znane jako Swagger) oraz <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
|
||||
|
||||
* **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. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> 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: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
|
||||
<small>* oszacowania bazowane na testach wykonanych przez wewnętrzny zespół deweloperów, budujących aplikacie używane na środowisku produkcyjnym.</small>
|
||||
|
||||
<small>* estimation based on tests on an internal development team, building production applications.</small>
|
||||
|
||||
## Sponsors
|
||||
## Sponsorzy
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
@@ -59,9 +54,9 @@ The key features are:
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">Other sponsors</a>
|
||||
<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">Inni sponsorzy</a>
|
||||
|
||||
## Opinions
|
||||
## Opinie
|
||||
|
||||
"_[...] 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._"
|
||||
|
||||
@@ -101,24 +96,24 @@ The key features are:
|
||||
|
||||
---
|
||||
|
||||
## **Typer**, the FastAPI of CLIs
|
||||
## **Typer**, FastAPI aplikacji konsolowych
|
||||
|
||||
<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
|
||||
|
||||
If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be used in the terminal instead of a web API, check out <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>.
|
||||
Jeżeli tworzysz aplikacje <abbr title="aplikacja z interfejsem konsolowym">CLI</abbr>, która ma być używana w terminalu zamiast API, sprawdź <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>.
|
||||
|
||||
**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
|
||||
**Typer** to młodsze rodzeństwo FastAPI. Jego celem jest pozostanie **FastAPI aplikacji konsolowych** . ⌨️ 🚀
|
||||
|
||||
## Requirements
|
||||
## Wymagania
|
||||
|
||||
Python 3.6+
|
||||
|
||||
FastAPI stands on the shoulders of giants:
|
||||
FastAPI oparty jest na:
|
||||
|
||||
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts.
|
||||
* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> for the data parts.
|
||||
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> dla części webowej.
|
||||
* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> dla części obsługujących dane.
|
||||
|
||||
## Installation
|
||||
## Instalacja
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -130,7 +125,7 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np. <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> lub <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -142,11 +137,11 @@ $ pip install uvicorn[standard]
|
||||
|
||||
</div>
|
||||
|
||||
## Example
|
||||
## Przykład
|
||||
|
||||
### Create it
|
||||
### Stwórz
|
||||
|
||||
* Create a file `main.py` with:
|
||||
* Utwórz plik o nazwie `main.py` z:
|
||||
|
||||
```Python
|
||||
from typing import Optional
|
||||
@@ -167,9 +162,9 @@ def read_item(item_id: int, q: Optional[str] = None):
|
||||
```
|
||||
|
||||
<details markdown="1">
|
||||
<summary>Or use <code>async def</code>...</summary>
|
||||
<summary>Albo użyj <code>async def</code>...</summary>
|
||||
|
||||
If your code uses `async` / `await`, use `async def`:
|
||||
Jeżeli twój kod korzysta z `async` / `await`, użyj `async def`:
|
||||
|
||||
```Python hl_lines="9 14"
|
||||
from typing import Optional
|
||||
@@ -189,15 +184,15 @@ async def read_item(item_id: int, q: Optional[str] = None):
|
||||
return {"item_id": item_id, "q": q}
|
||||
```
|
||||
|
||||
**Note**:
|
||||
**Przypis**:
|
||||
|
||||
If you don't know, check the _"In a hurry?"_ section about <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">`async` and `await` in the docs</a>.
|
||||
Jeżeli nie znasz, sprawdź sekcję _"In a hurry?"_ o <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">`async` i `await` w dokumentacji</a>.
|
||||
|
||||
</details>
|
||||
|
||||
### Run it
|
||||
### Uruchom
|
||||
|
||||
Run the server with:
|
||||
Uruchom serwer używając:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -214,54 +209,53 @@ INFO: Application startup complete.
|
||||
</div>
|
||||
|
||||
<details markdown="1">
|
||||
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
|
||||
<summary>O komendzie <code>uvicorn main:app --reload</code>...</summary>
|
||||
Komenda `uvicorn main:app` odnosi się do:
|
||||
|
||||
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.
|
||||
* `main`: plik `main.py` ("moduł" w Pythonie).
|
||||
* `app`: obiekt stworzony w `main.py` w lini `app = FastAPI()`.
|
||||
* `--reload`: spraw by serwer resetował się po każdej zmianie w kodzie. Używaj tego tylko w środowisku deweloperskim.
|
||||
|
||||
</details>
|
||||
|
||||
### Check it
|
||||
### Wypróbuj
|
||||
|
||||
Open your browser at <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
|
||||
Otwórz link <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a> w przeglądarce.
|
||||
|
||||
You will see the JSON response as:
|
||||
Zobaczysz następującą odpowiedź JSON:
|
||||
|
||||
```JSON
|
||||
{"item_id": 5, "q": "somequery"}
|
||||
```
|
||||
|
||||
You already created an API that:
|
||||
Właśnie stworzyłeś API które:
|
||||
|
||||
* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
|
||||
* Both _paths_ take `GET` <em>operations</em> (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`.
|
||||
* Otrzymuje żądania HTTP w _ścieżce_ `/` i `/items/{item_id}`.
|
||||
* Obie _ścieżki_ używają <em>operacji</em> `GET` (znane także jako _metody_ HTTP).
|
||||
* _Ścieżka_ `/items/{item_id}` ma _parametr ścieżki_ `item_id` który powinien być obiektem typu `int`.
|
||||
* _Ścieżka_ `/items/{item_id}` ma opcjonalny _parametr zapytania_ typu `str` o nazwie `q`.
|
||||
|
||||
### Interactive API docs
|
||||
### Interaktywna dokumentacja API
|
||||
|
||||
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
Otwórz teraz stronę <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
|
||||
You will see the automatic interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
|
||||
Zobaczysz automatyczną interaktywną dokumentację API (dostarczoną z pomocą <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
|
||||
|
||||

|
||||
|
||||
### Alternative API docs
|
||||
### Alternatywna dokumentacja API
|
||||
|
||||
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
Otwórz teraz <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
|
||||
You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
|
||||
Zobaczysz alternatywną, lecz wciąż automatyczną dokumentację (wygenerowaną z pomocą <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
|
||||
|
||||

|
||||
|
||||
## Example upgrade
|
||||
## Aktualizacja przykładu
|
||||
|
||||
Now modify the file `main.py` to receive a body from a `PUT` request.
|
||||
Zmodyfikuj teraz plik `main.py`, aby otrzmywał treść (body) żądania `PUT`.
|
||||
|
||||
Declare the body using standard Python types, thanks to Pydantic.
|
||||
Zadeklaruj treść żądania, używając standardowych typów w Pythonie dzięki Pydantic.
|
||||
|
||||
```Python hl_lines="4 9-12 25-27"
|
||||
from typing import Optional
|
||||
@@ -293,175 +287,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).
|
||||
Serwer powinien przeładować się automatycznie (ponieważ dodałeś `--reload` do komendy `uvicorn` powyżej).
|
||||
|
||||
### Interactive API docs upgrade
|
||||
### Zaktualizowana interaktywna dokumentacja API
|
||||
|
||||
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
Wejdź teraz na <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
|
||||
* The interactive API documentation will be automatically updated, including the new body:
|
||||
* Interaktywna dokumentacja API zaktualizuje sie automatycznie, także z nową treścią żądania (body):
|
||||
|
||||

|
||||
|
||||
* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
|
||||
* Kliknij przycisk "Try it out" (wypróbuj), pozwoli Ci to wypełnić parametry i bezpośrednio użyć API:
|
||||
|
||||

|
||||
|
||||
* 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:
|
||||
* Kliknij potem przycisk "Execute" (wykonaj), interfejs użytkownika połączy się z API, wyśle parametry, otrzyma odpowiedź i wyświetli ją na ekranie:
|
||||
|
||||

|
||||
|
||||
### Alternative API docs upgrade
|
||||
### Zaktualizowana alternatywna dokumentacja API
|
||||
|
||||
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
Otwórz teraz <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
|
||||
* The alternative documentation will also reflect the new query parameter and body:
|
||||
* Alternatywna dokumentacja również pokaże zaktualizowane parametry i treść żądania (body):
|
||||
|
||||

|
||||
|
||||
### Recap
|
||||
### Podsumowanie
|
||||
|
||||
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
|
||||
Podsumowując, musiałeś zadeklarować typy parametrów, treści żądania (body) itp. tylko **raz**, i są one dostępne jako parametry funkcji.
|
||||
|
||||
You do that with standard modern Python types.
|
||||
Robisz to tak samo jak ze standardowymi typami w Pythonie.
|
||||
|
||||
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
|
||||
Nie musisz sie uczyć żadnej nowej składni, metod lub klas ze specyficznych bibliotek itp.
|
||||
|
||||
Just standard **Python 3.6+**.
|
||||
Po prostu standardowy **Python 3.6+**.
|
||||
|
||||
For example, for an `int`:
|
||||
Na przykład, dla danych typu `int`:
|
||||
|
||||
```Python
|
||||
item_id: int
|
||||
```
|
||||
|
||||
or for a more complex `Item` model:
|
||||
albo dla bardziej złożonego obiektu `Item`:
|
||||
|
||||
```Python
|
||||
item: Item
|
||||
```
|
||||
|
||||
...and with that single declaration you get:
|
||||
...i z pojedyńczą deklaracją otrzymujesz:
|
||||
|
||||
* 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.
|
||||
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network to Python data and types. Reading from:
|
||||
* Wsparcie edytorów kodu, wliczając:
|
||||
* Auto-uzupełnianie.
|
||||
* Sprawdzanie typów.
|
||||
* Walidacja danych:
|
||||
* Automatyczne i przejrzyste błędy gdy dane są niepoprawne.
|
||||
* Walidacja nawet dla głęboko zagnieżdżonych obiektów JSON.
|
||||
* <abbr title="znane również jako: serializacja, przetwarzanie, marshalling">Konwersja</abbr> danych wejściowych: przychodzących z sieci na Pythonowe typy. Pozwala na przetwarzanie danych:
|
||||
* JSON.
|
||||
* Path parameters.
|
||||
* Query parameters.
|
||||
* Cookies.
|
||||
* Headers.
|
||||
* Forms.
|
||||
* Files.
|
||||
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> 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:
|
||||
* Parametrów ścieżki.
|
||||
* Parametrów zapytania.
|
||||
* Dane cookies.
|
||||
* Dane nagłówków (headers).
|
||||
* Formularze.
|
||||
* Pliki.
|
||||
* <abbr title="znane również jako: serializacja, przetwarzanie, marshalling">Konwersja</abbr> danych wyjściowych: wychodzących z Pythona do sieci (jako JSON):
|
||||
* Przetwarzanie Pythonowych typów (`str`, `int`, `float`, `bool`, `list`, itp).
|
||||
* Obiekty `datetime`.
|
||||
* Obiekty `UUID`.
|
||||
* Modele baz danych.
|
||||
* ...i wiele więcej.
|
||||
* Automatyczne interaktywne dokumentacje API, wliczając 2 alternatywne interfejsy użytkownika:
|
||||
* Swagger UI.
|
||||
* ReDoc.
|
||||
|
||||
---
|
||||
|
||||
Coming back to the previous code example, **FastAPI** will:
|
||||
Wracając do poprzedniego przykładu, **FastAPI** :
|
||||
|
||||
* 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.
|
||||
* Potwierdzi, że w ścieżce jest `item_id` dla żądań `GET` i `PUT`.
|
||||
* Potwierdzi, że `item_id` jest typu `int` dla żądań `GET` i `PUT`.
|
||||
* Jeżeli nie jest, odbiorca zobaczy przydatną, przejrzystą wiadomość z błędem.
|
||||
* Sprawdzi czy w ścieżce jest opcjonalny parametr zapytania `q` (np. `http://127.0.0.1:8000/items/foo?q=somequery`) dla żądania `GET`.
|
||||
* Jako że parametr `q` jest zadeklarowany jako `= None`, jest on opcjonalny.
|
||||
* Gdyby tego `None` nie było, parametr ten byłby wymagany (tak jak treść żądania w żądaniu `PUT`).
|
||||
* Dla żądania `PUT` z ścieżką `/items/{item_id}`, odczyta treść żądania jako JSON:
|
||||
* Sprawdzi czy posiada wymagany atrybut `name`, który powinien być typu `str`.
|
||||
* Sprawdzi czy posiada wymagany atrybut `price`, który musi być typu `float`.
|
||||
* Sprawdzi czy posiada opcjonalny atrybut `is_offer`, który (jeżeli obecny) powinien być typu `bool`.
|
||||
* To wszystko będzie również działać dla głęboko zagnieżdżonych obiektów JSON.
|
||||
* Automatycznie konwertuje z i do JSON.
|
||||
* Dokumentuje wszystko w OpenAPI, które może być używane przez:
|
||||
* Interaktywne systemy dokumentacji.
|
||||
* Systemy automatycznego generowania kodu klienckiego, dla wielu języków.
|
||||
* Dostarczy bezpośrednio 2 interaktywne dokumentacje webowe.
|
||||
|
||||
---
|
||||
|
||||
We just scratched the surface, but you already get the idea of how it all works.
|
||||
To dopiero początek, ale już masz mniej-więcej pojęcie jak to wszystko działa.
|
||||
|
||||
Try changing the line with:
|
||||
Spróbuj zmienić linijkę:
|
||||
|
||||
```Python
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
...from:
|
||||
...z:
|
||||
|
||||
```Python
|
||||
... "item_name": item.name ...
|
||||
```
|
||||
|
||||
...to:
|
||||
...na:
|
||||
|
||||
```Python
|
||||
... "item_price": item.price ...
|
||||
```
|
||||
|
||||
...and see how your editor will auto-complete the attributes and know their types:
|
||||
...i zobacz jak edytor kodu automatycznie uzupełni atrybuty i będzie znał ich typy:
|
||||
|
||||

|
||||
|
||||
For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
|
||||
Dla bardziej kompletnych przykładów posiadających więcej funkcjonalności, zobacz <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
|
||||
|
||||
**Spoiler alert**: the tutorial - user guide includes:
|
||||
**Uwaga Spoiler**: tutorial - user guide zawiera:
|
||||
|
||||
* 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 **<abbr title="also known as components, resources, providers, services, injectables">Dependency Injection</abbr>** 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).
|
||||
* Many extra features (thanks to Starlette) as:
|
||||
* **WebSockets**
|
||||
* Deklaracje **parametrów** z innych miejsc takich jak: **nagłówki**, **pliki cookies**, **formularze** i **pliki**.
|
||||
* Jak ustawić **ograniczenia walidacyjne** takie jak `maksymalna długość` lub `regex`.
|
||||
* Potężny i łatwy w użyciu system **<abbr title="znane jako komponenty, resources, providers, services, injectables">Dependency Injection</abbr>**.
|
||||
* Zabezpieczenia i autentykacja, wliczając wsparcie dla **OAuth2** z **tokenami JWT** oraz autoryzacją **HTTP Basic**.
|
||||
* Bardziej zaawansowane (ale równie proste) techniki deklarowania **głęboko zagnieżdżonych modeli JSON** (dzięki Pydantic).
|
||||
* Wiele dodatkowych funkcji (dzięki Starlette) takie jak:
|
||||
* **WebSockety**
|
||||
* **GraphQL**
|
||||
* extremely easy tests based on `requests` and `pytest`
|
||||
* bardzo proste testy bazujące na `requests` oraz `pytest`
|
||||
* **CORS**
|
||||
* **Cookie Sessions**
|
||||
* ...and more.
|
||||
* **Sesje cookie**
|
||||
* ...i więcej.
|
||||
|
||||
## Performance
|
||||
## Wydajność
|
||||
|
||||
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
|
||||
Niezależne benchmarki TechEmpower pokazują, że **FastAPI** (uruchomiony na serwerze Uvicorn) <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">jest jednym z najszybszych dostępnych Pythonowych frameworków</a>, zaraz po Starlette i Uvicorn (używanymi wewnątrznie przez FastAPI). (*)
|
||||
|
||||
To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
|
||||
Aby dowiedzieć się o tym więcej, zobacz sekcję <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
|
||||
|
||||
## Optional Dependencies
|
||||
## Opcjonalne zależności
|
||||
|
||||
Used by Pydantic:
|
||||
Używane przez Pydantic:
|
||||
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - for faster JSON <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
|
||||
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - dla szybszego <abbr title="przetwarzania stringa który przychodzi z żądaniem HTTP na dane używane przez Pythona">"parsowania"</abbr> danych JSON.
|
||||
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - dla walidacji adresów email.
|
||||
|
||||
Used by Starlette:
|
||||
Używane przez Starlette:
|
||||
|
||||
* <a href="https://requests.readthedocs.io" target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
|
||||
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Required if you want to use `FileResponse` or `StaticFiles`.
|
||||
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
|
||||
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
|
||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
|
||||
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` support.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
|
||||
* <a href="https://requests.readthedocs.io" target="_blank"><code>requests</code></a> - Wymagane jeżeli chcesz korzystać z `TestClient`.
|
||||
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Wymagane jeżeli chcesz korzystać z `FileResponse` albo `StaticFiles`.
|
||||
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Wymagane jeżeli chcesz używać domyślnej konfiguracji szablonów.
|
||||
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Wymagane jeżelich chcesz wsparcie <abbr title="przetwarzania stringa którzy przychodzi z żądaniem HTTP na dane używane przez Pythona">"parsowania"</abbr> formularzy, używając `request.form()`.
|
||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Wymagany dla wsparcia `SessionMiddleware`.
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Wymagane dla wsparcia `SchemaGenerator` z Starlette (z FastAPI prawdopodobnie tego nie potrzebujesz).
|
||||
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Wymagane dla wsparcia `GraphQLApp`.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Wymagane jeżeli chcesz korzystać z `UJSONResponse`.
|
||||
|
||||
Used by FastAPI / Starlette:
|
||||
Używane przez FastAPI / Starlette:
|
||||
|
||||
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
|
||||
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
|
||||
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - jako serwer, który ładuje i obsługuje Twoją aplikację.
|
||||
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Wymagane jeżeli chcesz używać `ORJSONResponse`.
|
||||
|
||||
You can install all of these with `pip install fastapi[all]`.
|
||||
Możesz zainstalować wszystkie te aplikacje przy pomocy `pip install fastapi[all]`.
|
||||
|
||||
## License
|
||||
## Licencja
|
||||
|
||||
This project is licensed under the terms of the MIT license.
|
||||
Ten projekt jest na licencji MIT.
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
|
||||
@@ -1,107 +1,149 @@
|
||||
# 帮助 FastAPI - 获取帮助
|
||||
# 帮助 FastAPI 与求助
|
||||
|
||||
你喜欢 **FastAPI** 吗?
|
||||
您喜欢 **FastAPI** 吗?
|
||||
|
||||
您愿意去帮助 FastAPI,帮助其他用户以及作者吗?
|
||||
想帮助 FastAPI?其它用户?还有项目作者?
|
||||
|
||||
或者你想要获得有关 **FastAPI** 的帮助?
|
||||
或要求助怎么使用 **FastAPI**?
|
||||
|
||||
下面是一些非常简单的方式去提供帮助(有些只需单击一两次链接)。
|
||||
以下几种帮助的方式都非常简单(有些只需要点击一两下鼠标)。
|
||||
|
||||
以及几种获取帮助的途径。
|
||||
求助的渠道也很多。
|
||||
|
||||
## 在 GitHub 上 Star **FastAPI**
|
||||
## 订阅新闻邮件
|
||||
|
||||
你可以在 GitHub 上 "star" FastAPI(点击右上角的 star 按钮):<a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>。
|
||||
您可以订阅 [**FastAPI 和它的小伙伴** 新闻邮件](/newsletter/){.internal-link target=_blank}(不会经常收到)
|
||||
|
||||
通过添加 star,其他用户将会更容易发现 FastAPI,并了解已经有许多人认为它有用。
|
||||
* FastAPI 及其小伙伴的新闻 🚀
|
||||
* 指南 📝
|
||||
* 功能 ✨
|
||||
* 破坏性更改 🚨
|
||||
* 开发技巧 ✅
|
||||
|
||||
## Watch GitHub 仓库的版本发布
|
||||
## 在推特上关注 FastAPI
|
||||
|
||||
你可以在 GitHub 上 "watch" FastAPI(点击右上角的 watch 按钮):<a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>。
|
||||
<a href="https://twitter.com/fastapi" class="external-link" target="_blank">在 **Twitter** 上关注 @fastapi</a> 获取 **FastAPI** 的最新消息。🐦
|
||||
|
||||
这时你可以选择 "Releases only" 选项。
|
||||
## 在 GitHub 上为 **FastAPI** 加星
|
||||
|
||||
之后,只要有 **FastAPI** 的新版本(包含缺陷修复和新功能)发布,你都会(通过电子邮件)收到通知。
|
||||
您可以在 GitHub 上 **Star** FastAPI(只要点击右上角的星星就可以了): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi。</a>⭐️
|
||||
|
||||
## 加入聊天室
|
||||
**Star** 以后,其它用户就能更容易找到 FastAPI,并了解到已经有其他用户在使用它了。
|
||||
|
||||
加入 Gitter 上的聊天室:<a href="https://gitter.im/tiangolo/fastapi" class="external-link" target="_blank">https://gitter.im/tiangolo/fastapi</a>。
|
||||
## 关注 GitHub 资源库的版本发布
|
||||
|
||||
在这里你可以快速提问、帮助他人、分享想法等。
|
||||
您还可以在 GitHub 上 **Watch** FastAPI,(点击右上角的 **Watch** 按钮)<a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi。</a>👀
|
||||
|
||||
## 与作者联系
|
||||
您可以选择只关注发布(**Releases only**)。
|
||||
|
||||
你可以联系 <a href="https://tiangolo.com" class="external-link" target="_blank">我 (Sebastián Ramírez / `tiangolo`)</a> - FastAPI 的作者。
|
||||
这样,您就可以(在电子邮件里)接收到 **FastAPI** 新版发布的通知,及时了解 bug 修复与新功能。
|
||||
|
||||
你可以:
|
||||
## 联系作者
|
||||
|
||||
* <a href="https://github.com/tiangolo" class="external-link" target="_blank">在 **GitHub** 上关注我</a>。
|
||||
* 查看我创建的其他的可能对你有帮助的开源项目。
|
||||
* 关注我以了解我创建的新开源项目。
|
||||
* <a href="https://twitter.com/tiangolo" class="external-link" target="_blank">在 **Twitter** 上关注我</a>。
|
||||
* 告诉我你是如何使用 FastAPI 的(我很乐意听到)。
|
||||
* 提出问题。
|
||||
* <a href="https://www.linkedin.com/in/tiangolo/" class="external-link" target="_blank">在 **Linkedin** 上联系我</a>。
|
||||
* 与我交流。
|
||||
* 认可我的技能或推荐我 :)
|
||||
* <a href="https://medium.com/@tiangolo" class="external-link" target="_blank">在 **Medium** 上阅读我写的文章(或关注我)</a>。
|
||||
* 阅读我创建的其他想法,文章和工具。
|
||||
* 关注我以了解我发布的新内容。
|
||||
您可以联系项目作者,就是<a href="https://tiangolo.com" class="external-link" target="_blank">我(Sebastián Ramírez / `tiangolo`</a>)。
|
||||
|
||||
## 发布和 **FastAPI** 有关的推特
|
||||
您可以:
|
||||
|
||||
<a href="https://twitter.com/compose/tweet?text=I'm loving FastAPI because... https://github.com/tiangolo/fastapi cc @tiangolo" class="external-link" target="_blank"> 发布和 **FastAPI** 有关的推特</a> 让我和其他人知道你为什么喜欢它。
|
||||
* <a href="https://github.com/tiangolo" class="external-link" target="_blank">在 **GitHub** 上关注我</a>
|
||||
* 了解其它我创建的开源项目,或许对您会有帮助
|
||||
* 关注我什么时候创建新的开源项目
|
||||
* <a href="https://twitter.com/tiangolo" class="external-link" target="_blank">在 **Twitter** 上关注我</a>
|
||||
* 告诉我您使用 FastAPI(我非常乐意听到这种消息)
|
||||
* 接收我发布公告或新工具的消息
|
||||
* 您还可以关注<a href="https://twitter.com/fastapi" class="external-link" target="_blank">@fastapi on Twitter</a>,这是个独立的账号
|
||||
* <a href="https://www.linkedin.com/in/tiangolo/" class="external-link" target="_blank">在**领英**上联系我</a>
|
||||
* 接收我发布公告或新工具的消息(虽然我用 Twitter 比较多)
|
||||
* 阅读我在 <a href="https://dev.to/tiangolo" class="external-link" target="_blank">**Dev.to**</a> 或 <a href="https://medium.com/@tiangolo" class="external-link" target="_blank">**Medium**</a> 上的文章,或关注我
|
||||
* 阅读我的其它想法、文章,了解我创建的工具
|
||||
* 关注我,这样就可以随时看到我发布的新文章
|
||||
|
||||
## 告诉我你正在如何使用 **FastAPI**
|
||||
## Tweet about **FastAPI**
|
||||
|
||||
我很乐意听到有关 **FastAPI** 被如何使用、你喜欢它的哪一点、被投入使用的项目/公司等等信息。
|
||||
<a href="https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/tiangolo/fastapi" class="external-link" target="_blank">Tweet about **FastAPI**</a> 让我和大家知道您为什么喜欢 FastAPI。🎉
|
||||
|
||||
你可以通过以下平台让我知道:
|
||||
|
||||
* <a href="https://twitter.com/compose/tweet?text=Hey @tiangolo, I'm using FastAPI at..." class="external-link" target="_blank">**Twitter**</a>。
|
||||
* <a href="https://www.linkedin.com/in/tiangolo/" class="external-link" target="_blank">**Linkedin**</a>。
|
||||
* <a href="https://medium.com/@tiangolo" class="external-link" target="_blank">**Medium**</a>。
|
||||
知道有人使用 **FastAPI**,我会很开心,我也想知道您为什么喜欢 FastAPI,以及您在什么项目/哪些公司使用 FastAPI,等等。
|
||||
|
||||
## 为 FastAPI 投票
|
||||
|
||||
* <a href="https://www.slant.co/options/34241/~fastapi-review" class="external-link" target="_blank">在 Slant 上为 **FastAPI** 投票</a>。
|
||||
* <a href="https://www.slant.co/options/34241/~fastapi-review" class="external-link" target="_blank">在 Slant 上为 **FastAPI** 投票</a>
|
||||
* <a href="https://alternativeto.net/software/fastapi/" class="external-link" target="_blank">在 AlternativeTo 上为 **FastAPI** 投票</a>
|
||||
|
||||
## 帮助他人解决 GitHub 的 issues
|
||||
## 在 GitHub 上帮助其他人解决问题
|
||||
|
||||
你可以查看 <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">已有的 issues</a> 并尝试帮助其他人。
|
||||
您可以查看<a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">现有 issues</a>,并尝试帮助其他人解决问题,说不定您能解决这些问题呢。🤓
|
||||
|
||||
## Watch GitHub 仓库
|
||||
如果帮助很多人解决了问题,您就有可能成为 [FastAPI 的官方专家](fastapi-people.md#experts){.internal-link target=_blank}。🎉
|
||||
|
||||
你可以在 GitHub 上 "watch" FastAPI(点击右上角的 "watch" 按钮):<a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>。
|
||||
## 监听 GitHub 资源库
|
||||
|
||||
如果你选择的是 "Watching" 而不是 "Releases only" 选项,你会在其他人创建了新的 issue 时收到通知。
|
||||
您可以在 GitHub 上「监听」FastAPI(点击右上角的 "watch" 按钮): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀
|
||||
|
||||
然后你可以尝试帮助他们解决这些 issue。
|
||||
如果您选择 "Watching" 而不是 "Releases only",有人创建新 Issue 时,您会接收到通知。
|
||||
|
||||
## 创建 issue
|
||||
然后您就可以尝试并帮助他们解决问题。
|
||||
|
||||
你可以在 GitHub 仓库中 <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">创建一个新 issue</a> 用来:
|
||||
## 创建 Issue
|
||||
|
||||
* 报告 bug 或问题。
|
||||
* 提议新的特性。
|
||||
* 提问。
|
||||
您可以在 GitHub 资源库中<a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">创建 Issue</a>,例如:
|
||||
|
||||
## 创建 Pull Request
|
||||
* 提出**问题**或**意见**
|
||||
* 提出新**特性**建议
|
||||
|
||||
你可以 <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">创建一个 Pull Request</a> 用来:
|
||||
**注意**:如果您创建 Issue,我会要求您也要帮助别的用户。😉
|
||||
|
||||
* 纠正你在文档中发现的错别字。
|
||||
* 添加新的文档内容。
|
||||
* 修复已有的 bug 或问题。
|
||||
* 添加新的特性。
|
||||
## 创建 PR
|
||||
|
||||
您可以创建 PR 为源代码做[贡献](contributing.md){.internal-link target=_blank},例如:
|
||||
|
||||
* 修改文档错别字
|
||||
* <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">编辑这个文件</a>,分享 FastAPI 的文章、视频、博客,不论是您自己的,还是您看到的都成
|
||||
* 注意,添加的链接要放在对应区块的开头
|
||||
* [翻译文档](contributing.md#translations){.internal-link target=_blank}
|
||||
* 审阅别人翻译的文档
|
||||
* 添加新的文档内容
|
||||
* 修复现有问题/Bug
|
||||
* 添加新功能
|
||||
|
||||
## 加入聊天
|
||||
|
||||
快加入 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord 聊天服务器</a> 👥 和 FastAPI 社区里的小伙伴一起哈皮吧。
|
||||
|
||||
!!! tip "提示"
|
||||
|
||||
如有问题,请在 <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub Issues</a> 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#experts){.internal-link target=_blank}的帮助。
|
||||
|
||||
聊天室仅供闲聊。
|
||||
|
||||
我们之前还使用过 <a href="https://gitter.im/tiangolo/fastapi" class="external-link" target="_blank">Gitter chat</a>,但它不支持频道等高级功能,聊天也比较麻烦,所以现在推荐使用 Discord。
|
||||
|
||||
### 别在聊天室里提问
|
||||
|
||||
注意,聊天室更倾向于“闲聊”,经常有人会提出一些笼统得让人难以回答的问题,所以在这里提问一般没人回答。
|
||||
|
||||
GitHub Issues 里提供了模板,指引您提出正确的问题,有利于获得优质的回答,甚至可能解决您还没有想到的问题。而且就算答疑解惑要耗费不少时间,我还是会尽量在 GitHub 里回答问题。但在聊天室里,我就没功夫这么做了。😅
|
||||
|
||||
聊天室里的聊天内容也不如 GitHub 里好搜索,聊天里的问答很容易就找不到了。只有在 GitHub Issues 里的问答才能帮助您成为 [FastAPI 专家](fastapi-people.md#experts){.internal-link target=_blank},在 GitHub Issues 中为您带来更多关注。
|
||||
|
||||
另一方面,聊天室里有成千上万的用户,在这里,您有很大可能遇到聊得来的人。😄
|
||||
|
||||
## 赞助作者
|
||||
|
||||
你还可以通过 <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub sponsors</a> 在经济上支持作者(我)。
|
||||
您还可以通过 <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub 赞助商</a>资助本项目的作者(就是我)。
|
||||
|
||||
这样你可以给我买杯咖啡☕️以示谢意😄。
|
||||
给我买杯咖啡 ☕️ 以示感谢 😄
|
||||
|
||||
当然您也可以成为 FastAPI 的金牌或银牌赞助商。🏅🎉
|
||||
|
||||
## 赞助 FastAPI 使用的工具
|
||||
|
||||
如您在本文档中所见,FastAPI 站在巨人的肩膀上,它们分别是 Starlette 和 Pydantic。
|
||||
|
||||
您还可以赞助:
|
||||
|
||||
* <a href="https://github.com/sponsors/samuelcolvin" class="external-link" target="_blank">Samuel Colvin (Pydantic)</a>
|
||||
* <a href="https://github.com/sponsors/encode" class="external-link" target="_blank">Encode (Starlette, Uvicorn)</a>
|
||||
|
||||
---
|
||||
|
||||
感谢!
|
||||
谢谢!🚀
|
||||
|
||||
|
||||
101
docs/zh/docs/tutorial/path-operation-configuration.md
Normal file
101
docs/zh/docs/tutorial/path-operation-configuration.md
Normal file
@@ -0,0 +1,101 @@
|
||||
# 路径操作配置
|
||||
|
||||
*路径操作装饰器*支持多种配置参数。
|
||||
|
||||
!!! warning "警告"
|
||||
|
||||
注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。
|
||||
|
||||
## `status_code` 状态码
|
||||
|
||||
`status_code` 用于定义*路径操作*响应中的 HTTP 状态码。
|
||||
|
||||
可以直接传递 `int` 代码, 比如 `404`。
|
||||
|
||||
如果记不住数字码的涵义,也可以用 `status` 的快捷常量:
|
||||
|
||||
```Python hl_lines="3 17"
|
||||
{!../../../docs_src/path_operation_configuration/tutorial001.py!}
|
||||
```
|
||||
|
||||
状态码在响应中使用,并会被添加到 OpenAPI 概图。
|
||||
|
||||
!!! note "技术细节"
|
||||
|
||||
也可以使用 `from starlette import status` 导入状态码。
|
||||
|
||||
**FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。
|
||||
|
||||
## `tags` 参数
|
||||
|
||||
`tags` 参数的值是由 `str` 组成的 `list` (一般只有一个 `str` ),`tags` 用于为*路径操作*添加标签:
|
||||
|
||||
```Python hl_lines="17 22 27"
|
||||
{!../../../docs_src/path_operation_configuration/tutorial002.py!}
|
||||
```
|
||||
|
||||
OpenAPI 概图会自动添加标签,供 API 文档接口使用:
|
||||
|
||||
<img src="/img/tutorial/path-operation-configuration/image01.png">
|
||||
|
||||
## `summary` 和 `description` 参数
|
||||
|
||||
路径装饰器还支持 `summary` 和 `description` 这两个参数:
|
||||
|
||||
```Python hl_lines="20-21"
|
||||
{!../../../docs_src/path_operation_configuration/tutorial003.py!}
|
||||
```
|
||||
|
||||
## 文档字符串(`docstring`)
|
||||
|
||||
描述内容比较长且占用多行时,可以在函数的 <abbr title="函数中作为第一个表达式,用于文档目的的一个多行字符串(并没有被分配个任何变量)">docstring</abbr> 中声明*路径操作*的描述,**FastAPI** 支持从文档字符串中读取描述内容。
|
||||
|
||||
文档字符串支持 <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a>,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。
|
||||
|
||||
```Python hl_lines="19-27"
|
||||
{!../../../docs_src/path_operation_configuration/tutorial004.py!}
|
||||
```
|
||||
|
||||
下图为 Markdown 文本在 API 文档中的显示效果:
|
||||
|
||||
<img src="/img/tutorial/path-operation-configuration/image02.png">
|
||||
|
||||
## 响应描述
|
||||
|
||||
`response_description` 参数用于定义响应的描述说明:
|
||||
|
||||
```Python hl_lines="21"
|
||||
{!../../../docs_src/path_operation_configuration/tutorial005.py!}
|
||||
```
|
||||
|
||||
!!! info "说明"
|
||||
|
||||
注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。
|
||||
|
||||
!!! check "检查"
|
||||
|
||||
OpenAPI 规定每个*路径操作*都要有响应描述。
|
||||
|
||||
如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。
|
||||
|
||||
<img src="/img/tutorial/path-operation-configuration/image03.png">
|
||||
|
||||
## 弃用*路径操作*
|
||||
|
||||
`deprecated` 参数可以把*路径操作*标记为<abbr title="过时,建议不要使用">弃用</abbr>,无需直接删除:
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!../../../docs_src/path_operation_configuration/tutorial006.py!}
|
||||
```
|
||||
|
||||
API 文档会把该路径操作标记为弃用:
|
||||
|
||||
<img src="/img/tutorial/path-operation-configuration/image04.png">
|
||||
|
||||
下图显示了正常*路径操作*与弃用*路径操作* 的区别:
|
||||
|
||||
<img src="/img/tutorial/path-operation-configuration/image05.png">
|
||||
|
||||
## 小结
|
||||
|
||||
通过传递参数给*路径操作装饰器* ,即可轻松地配置*路径操作*、添加元数据。
|
||||
@@ -20,6 +20,7 @@ theme:
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
- content.tabs.link
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -77,6 +78,7 @@ nav:
|
||||
- tutorial/request-files.md
|
||||
- tutorial/request-forms-and-files.md
|
||||
- tutorial/handling-errors.md
|
||||
- tutorial/path-operation-configuration.md
|
||||
- tutorial/body-updates.md
|
||||
- 依赖项:
|
||||
- tutorial/dependencies/index.md
|
||||
|
||||
8
docs_src/extending_openapi/tutorial003.py
Normal file
8
docs_src/extending_openapi/tutorial003.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI(swagger_ui_parameters={"syntaxHighlight": False})
|
||||
|
||||
|
||||
@app.get("/users/{username}")
|
||||
async def read_user(username: str):
|
||||
return {"message": f"Hello {username}"}
|
||||
8
docs_src/extending_openapi/tutorial004.py
Normal file
8
docs_src/extending_openapi/tutorial004.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI(swagger_ui_parameters={"syntaxHighlight.theme": "obsidian"})
|
||||
|
||||
|
||||
@app.get("/users/{username}")
|
||||
async def read_user(username: str):
|
||||
return {"message": f"Hello {username}"}
|
||||
8
docs_src/extending_openapi/tutorial005.py
Normal file
8
docs_src/extending_openapi/tutorial005.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI(swagger_ui_parameters={"deepLinking": False})
|
||||
|
||||
|
||||
@app.get("/users/{username}")
|
||||
async def read_user(username: str):
|
||||
return {"message": f"Hello {username}"}
|
||||
@@ -1,4 +1,7 @@
|
||||
def process_items(prices: dict[str, float]):
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def process_items(prices: Dict[str, float]):
|
||||
for item_name, item_price in prices.items():
|
||||
print(item_name)
|
||||
print(item_price)
|
||||
|
||||
4
docs_src/python_types/tutorial008_py39.py
Normal file
4
docs_src/python_types/tutorial008_py39.py
Normal file
@@ -0,0 +1,4 @@
|
||||
def process_items(prices: dict[str, float]):
|
||||
for item_name, item_price in prices.items():
|
||||
print(item_name)
|
||||
print(item_price)
|
||||
@@ -1,6 +1,6 @@
|
||||
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
|
||||
|
||||
__version__ = "0.71.0"
|
||||
__version__ = "0.72.0"
|
||||
|
||||
from starlette import status as status
|
||||
|
||||
|
||||
@@ -65,6 +65,7 @@ class FastAPI(Starlette):
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
deprecated: Optional[bool] = None,
|
||||
include_in_schema: bool = True,
|
||||
swagger_ui_parameters: Optional[Dict[str, Any]] = None,
|
||||
**extra: Any,
|
||||
) -> None:
|
||||
self._debug: bool = debug
|
||||
@@ -120,6 +121,7 @@ class FastAPI(Starlette):
|
||||
self.redoc_url = redoc_url
|
||||
self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url
|
||||
self.swagger_ui_init_oauth = swagger_ui_init_oauth
|
||||
self.swagger_ui_parameters = swagger_ui_parameters
|
||||
self.extra = extra
|
||||
self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {}
|
||||
|
||||
@@ -174,6 +176,7 @@ class FastAPI(Starlette):
|
||||
title=self.title + " - Swagger UI",
|
||||
oauth2_redirect_url=oauth2_redirect_url,
|
||||
init_oauth=self.swagger_ui_init_oauth,
|
||||
swagger_ui_parameters=self.swagger_ui_parameters,
|
||||
)
|
||||
|
||||
self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False)
|
||||
|
||||
@@ -4,6 +4,14 @@ from typing import Any, Dict, Optional
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from starlette.responses import HTMLResponse
|
||||
|
||||
swagger_ui_default_parameters = {
|
||||
"dom_id": "#swagger-ui",
|
||||
"layout": "BaseLayout",
|
||||
"deepLinking": True,
|
||||
"showExtensions": True,
|
||||
"showCommonExtensions": True,
|
||||
}
|
||||
|
||||
|
||||
def get_swagger_ui_html(
|
||||
*,
|
||||
@@ -14,7 +22,11 @@ def get_swagger_ui_html(
|
||||
swagger_favicon_url: str = "https://fastapi.tiangolo.com/img/favicon.png",
|
||||
oauth2_redirect_url: Optional[str] = None,
|
||||
init_oauth: Optional[Dict[str, Any]] = None,
|
||||
swagger_ui_parameters: Optional[Dict[str, Any]] = None,
|
||||
) -> HTMLResponse:
|
||||
current_swagger_ui_parameters = swagger_ui_default_parameters.copy()
|
||||
if swagger_ui_parameters:
|
||||
current_swagger_ui_parameters.update(swagger_ui_parameters)
|
||||
|
||||
html = f"""
|
||||
<!DOCTYPE html>
|
||||
@@ -34,19 +46,17 @@ def get_swagger_ui_html(
|
||||
url: '{openapi_url}',
|
||||
"""
|
||||
|
||||
for key, value in current_swagger_ui_parameters.items():
|
||||
html += f"{json.dumps(key)}: {json.dumps(jsonable_encoder(value))},\n"
|
||||
|
||||
if oauth2_redirect_url:
|
||||
html += f"oauth2RedirectUrl: window.location.origin + '{oauth2_redirect_url}',"
|
||||
|
||||
html += """
|
||||
dom_id: '#swagger-ui',
|
||||
presets: [
|
||||
presets: [
|
||||
SwaggerUIBundle.presets.apis,
|
||||
SwaggerUIBundle.SwaggerUIStandalonePreset
|
||||
],
|
||||
layout: "BaseLayout",
|
||||
deepLinking: true,
|
||||
showExtensions: true,
|
||||
showCommonExtensions: true
|
||||
})"""
|
||||
|
||||
if init_oauth:
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from docs_src.extending_openapi.tutorial003 import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_swagger_ui():
|
||||
response = client.get("/docs")
|
||||
assert response.status_code == 200, response.text
|
||||
assert (
|
||||
'"syntaxHighlight": false' in response.text
|
||||
), "syntaxHighlight should be included and converted to JSON"
|
||||
assert (
|
||||
'"dom_id": "#swagger-ui"' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert "presets: [" in response.text, "default configs should be preserved"
|
||||
assert (
|
||||
"SwaggerUIBundle.presets.apis," in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
"SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"layout": "BaseLayout",' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"deepLinking": true,' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"showExtensions": true,' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"showCommonExtensions": true,' in response.text
|
||||
), "default configs should be preserved"
|
||||
|
||||
|
||||
def test_get_users():
|
||||
response = client.get("/users/foo")
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {"message": "Hello foo"}
|
||||
@@ -0,0 +1,44 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from docs_src.extending_openapi.tutorial004 import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_swagger_ui():
|
||||
response = client.get("/docs")
|
||||
assert response.status_code == 200, response.text
|
||||
assert (
|
||||
'"syntaxHighlight": false' not in response.text
|
||||
), "not used parameters should not be included"
|
||||
assert (
|
||||
'"syntaxHighlight.theme": "obsidian"' in response.text
|
||||
), "parameters with middle dots should be included in a JSON compatible way"
|
||||
assert (
|
||||
'"dom_id": "#swagger-ui"' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert "presets: [" in response.text, "default configs should be preserved"
|
||||
assert (
|
||||
"SwaggerUIBundle.presets.apis," in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
"SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"layout": "BaseLayout",' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"deepLinking": true,' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"showExtensions": true,' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"showCommonExtensions": true,' in response.text
|
||||
), "default configs should be preserved"
|
||||
|
||||
|
||||
def test_get_users():
|
||||
response = client.get("/users/foo")
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {"message": "Hello foo"}
|
||||
@@ -0,0 +1,44 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from docs_src.extending_openapi.tutorial005 import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_swagger_ui():
|
||||
response = client.get("/docs")
|
||||
assert response.status_code == 200, response.text
|
||||
assert (
|
||||
'"deepLinking": false,' in response.text
|
||||
), "overridden configs should be preserved"
|
||||
assert (
|
||||
'"deepLinking": true' not in response.text
|
||||
), "overridden configs should not include the old value"
|
||||
assert (
|
||||
'"syntaxHighlight": false' not in response.text
|
||||
), "not used parameters should not be included"
|
||||
assert (
|
||||
'"dom_id": "#swagger-ui"' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert "presets: [" in response.text, "default configs should be preserved"
|
||||
assert (
|
||||
"SwaggerUIBundle.presets.apis," in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
"SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"layout": "BaseLayout",' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"showExtensions": true,' in response.text
|
||||
), "default configs should be preserved"
|
||||
assert (
|
||||
'"showCommonExtensions": true,' in response.text
|
||||
), "default configs should be preserved"
|
||||
|
||||
|
||||
def test_get_users():
|
||||
response = client.get("/users/foo")
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.json() == {"message": "Hello foo"}
|
||||
Reference in New Issue
Block a user