diff --git a/README.md b/README.md index ab5143084..25a1d9179 100644 --- a/README.md +++ b/README.md @@ -470,15 +470,20 @@ Used by Starlette: * jinja2 - Required if you want to use the default template configuration. * python-multipart - Required if you want to support form "parsing", with `request.form()`. -Used by FastAPI / Starlette: +Used by FastAPI: * uvicorn - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving. -* `fastapi-cli` - to provide the `fastapi` command. +* `fastapi-cli[standard]` - to provide the `fastapi` command. + * This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to FastAPI Cloud. ### Without `standard` Dependencies If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`. +### Without `fastapi-cloud-cli` + +If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`. + ### Additional Optional Dependencies There are some additional dependencies you might want to install. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 0f3623ed5..938882d7d 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -468,15 +468,20 @@ Used by Starlette: * jinja2 - Required if you want to use the default template configuration. * python-multipart - Required if you want to support form "parsing", with `request.form()`. -Used by FastAPI / Starlette: +Used by FastAPI: * uvicorn - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving. -* `fastapi-cli` - to provide the `fastapi` command. +* `fastapi-cli[standard]` - to provide the `fastapi` command. + * This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to FastAPI Cloud. ### Without `standard` Dependencies If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`. +### Without `fastapi-cloud-cli` + +If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`. + ### Additional Optional Dependencies There are some additional dependencies you might want to install. diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f135ab134..d085081e2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,12 +7,27 @@ hide: ## Latest Changes +## 0.116.0 + +### Features + +* ✨ Add support for deploying to FastAPI Cloud with `fastapi deploy`. PR [#13870](https://github.com/fastapi/fastapi/pull/13870) by [@tiangolo](https://github.com/tiangolo). + +Installing `fastapi[standard]` now includes `fastapi-cloud-cli`. + +This will allow you to deploy to [FastAPI Cloud](https://fastapicloud.com) with the `fastapi deploy` command. + +If you want to install `fastapi` with the standard dependencies but without `fastapi-cloud-cli`, you can install instead `fastapi[standard-no-fastapi-cloud-cli]`. + ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/advanced/response-directly.md`. PR [#13801](https://github.com/fastapi/fastapi/pull/13801) by [@NavesSapnis](https://github.com/NavesSapnis). +* 🌐 Add Russian translation for `docs/ru/docs/advanced/additional-status-codes.md`. PR [#13799](https://github.com/fastapi/fastapi/pull/13799) by [@NavesSapnis](https://github.com/NavesSapnis). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-updates.md`. PR [#13804](https://github.com/fastapi/fastapi/pull/13804) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). ### Internal +* ⬆ Bump pillow from 11.1.0 to 11.3.0. PR [#13852](https://github.com/fastapi/fastapi/pull/13852) by [@dependabot[bot]](https://github.com/apps/dependabot). * 👥 Update FastAPI People - Sponsors. PR [#13846](https://github.com/fastapi/fastapi/pull/13846) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI GitHub topic repositories. PR [#13848](https://github.com/fastapi/fastapi/pull/13848) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump mkdocs-material from 9.6.1 to 9.6.15. PR [#13849](https://github.com/fastapi/fastapi/pull/13849) by [@dependabot[bot]](https://github.com/apps/dependabot). diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index 4fe38256c..17f6fb685 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -76,10 +76,12 @@ $ pip install "fastapi[standard]" /// note -When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies. +When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies, including `fastapi-cloud-cli`, which allows you to deploy to FastAPI Cloud. If you don't want to have those optional dependencies, you can instead install `pip install fastapi`. +If you want to install the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`. + /// ## Advanced User Guide diff --git a/docs/ru/docs/advanced/additional-status-codes.md b/docs/ru/docs/advanced/additional-status-codes.md new file mode 100644 index 000000000..aab1f8ee3 --- /dev/null +++ b/docs/ru/docs/advanced/additional-status-codes.md @@ -0,0 +1,41 @@ +# Дополнительные статус коды + +По умолчанию **FastAPI** возвращает ответы, используя `JSONResponse`, помещая содержимое, которое вы возвращаете из вашей *операции пути*, внутрь этого `JSONResponse`. + +Он будет использовать код статуса по умолчанию или тот, который вы укажете в вашей *операции пути*. + +## Дополнительные статус коды + +Если вы хотите возвращать дополнительный статус код помимо основного, вы можете сделать это, возвращая объект `Response` напрямую, как `JSONResponse`, и устанавливая нужный статус код напрямую. + +Например, скажем, вы хотите создать *операцию пути*, которая позволяет обновлять элементы и возвращает HTTP-код 200 "OK" при успешном выполнении. + +Но вы также хотите, чтобы она принимала новые элементы. И если элемент ранее не существовал, он создаётся, и возвращался HTTP-код 201 "Created". + +Чтобы реализовать это, импортируйте `JSONResponse` и возвращайте ваш контент напрямую, устанавливая нужный `status_code`: + +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} + +/// warning | Внимание + +Когда вы возвращаете объект `Response` напрямую, как в примере выше, он будет возвращён как есть. + +Он не будет сериализован при помощи модели и т.д. + +Убедитесь, что в нём содержатся именно те данные, которые вы хотите, и что значения являются валидным JSON (если вы используете `JSONResponse`). + +/// + +/// note | Технические детали + +Вы также можете использовать `from starlette.responses import JSONResponse`. + +**FastAPI** предоставляет тот же `starlette.responses` через `fastapi.responses` просто для вашего удобства, как разработчика. Но большинство доступных Response-классов поступают напрямую из Starlette. То же самое касается и `status`. + +/// + +## OpenAPI и документация API + +Если вы возвращаете дополнительные коды статусов и ответы напрямую, они не будут включены в схему OpenAPI (документацию API), потому что FastAPI не может заранее знать, что вы собираетесь вернуть. + +Но вы можете задокументировать это в вашем коде, используя: [Дополнительные ответы в OpenAPI](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/ru/docs/advanced/response-directly.md b/docs/ru/docs/advanced/response-directly.md new file mode 100644 index 000000000..ee83d22b1 --- /dev/null +++ b/docs/ru/docs/advanced/response-directly.md @@ -0,0 +1,65 @@ +# Возврат ответа напрямую + +Когда вы создаёте **FastAPI** *операцию пути*, вы можете возвращать из неё любые данные: `dict`, `list`, Pydantic-модель, модель базы данных и т.д. + +По умолчанию **FastAPI** автоматически преобразует возвращаемое значение в JSON с помощью `jsonable_encoder`, как описано в [JSON кодировщик](../tutorial/encoder.md){.internal-link target=_blank}. + +Затем "под капотом" эти данные, совместимые с JSON (например `dict`), помещаются в `JSONResponse`, который используется для отправки ответа клиенту. + +Но вы можете возвращать `JSONResponse` напрямую из ваших *операций пути*. + +Это может быть полезно, например, если нужно вернуть пользовательские заголовки или куки. + +## Возврат `Response` + +На самом деле, вы можете возвращать любой объект `Response` или его подкласс. + +/// tip | Подсказка + +`JSONResponse` сам по себе является подклассом `Response`. + +/// + +И когда вы возвращаете `Response`, **FastAPI** передаст его напрямую. + +Это не приведет к преобразованию данных с помощью Pydantic-моделей, содержимое не будет преобразовано в какой-либо тип и т.д. + +Это даёт вам большую гибкость. Вы можете возвращать любые типы данных, переопределять любые объявления или валидацию данных и т.д. + +## Использование `jsonable_encoder` в `Response` + +Поскольку **FastAPI** не изменяет объект `Response`, который вы возвращаете, вы должны убедиться, что его содержимое готово к отправке. + +Например, вы не можете поместить Pydantic-модель в `JSONResponse`, не преобразовав её сначала в `dict` с помощью преобразования всех типов данных (таких как `datetime`, `UUID` и т.д.) в совместимые с JSON типы. + +В таких случаях вы можете использовать `jsonable_encoder` для преобразования данных перед передачей их в ответ: + +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | Технические детали + +Вы также можете использовать `from starlette.responses import JSONResponse`. + +**FastAPI** предоставляет `starlette.responses` через `fastapi.responses` просто для вашего удобства, как разработчика. Но большинство доступных Response-классов поступают напрямую из Starlette. + +/// + +## Возврат пользовательского `Response` + +Пример выше показывает все необходимые части, но он пока не очень полезен, так как вы могли бы просто вернуть `item` напрямую, и **FastAPI** поместил бы его в `JSONResponse`, преобразовав в `dict` и т.д. Всё это происходит по умолчанию. + +Теперь давайте посмотрим, как можно использовать это для возврата пользовательского ответа. + +Допустим, вы хотите вернуть ответ в формате XML. + +Вы можете поместить ваш XML-контент в строку, поместить её в `Response` и вернуть: + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +## Примечания + +Когда вы возвращаете объект `Response` напрямую, его данные не валидируются, не преобразуются (не сериализуются) и не документируются автоматически. + +Но вы всё равно можете задокументировать это, как описано в [Дополнительные ответы в OpenAPI](additional-responses.md){.internal-link target=_blank}. + +В следующих разделах вы увидите, как использовать/объявлять такие кастомные `Response`, при этом сохраняя автоматическое преобразование данных, документацию и т.д. diff --git a/fastapi/__init__.py b/fastapi/__init__.py index e672ec9e5..873ae18e0 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.115.14" +__version__ = "0.116.0" from starlette import status as status diff --git a/pyproject.toml b/pyproject.toml index 1c540e2f6..a3fc54e3d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,7 +58,26 @@ Changelog = "https://fastapi.tiangolo.com/release-notes/" [project.optional-dependencies] standard = [ - "fastapi-cli[standard] >=0.0.5", + "fastapi-cli[standard] >=0.0.8", + # For the test client + "httpx >=0.23.0", + # For templates + "jinja2 >=3.1.5", + # For forms and file uploads + "python-multipart >=0.0.18", + # To validate email fields + "email-validator >=2.0.0", + # Uvicorn with uvloop + "uvicorn[standard] >=0.12.0", + # TODO: this should be part of some pydantic optional extra dependencies + # # Settings management + # "pydantic-settings >=2.0.0", + # # Extra Pydantic data types + # "pydantic-extra-types >=2.0.0", +] + +standard-no-fastapi-cloud-cli = [ + "fastapi-cli[standard-no-fastapi-cloud-cli] >=0.0.8", # For the test client "httpx >=0.23.0", # For templates @@ -77,7 +96,7 @@ standard = [ ] all = [ - "fastapi-cli[standard] >=0.0.5", + "fastapi-cli[standard] >=0.0.8", # # For the test client "httpx >=0.23.0", # For templates diff --git a/requirements-docs.txt b/requirements-docs.txt index 059203ec1..5c5701f73 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -8,7 +8,7 @@ pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 # For image processing by Material for MkDocs -pillow==11.1.0 +pillow==11.3.0 # For image processing by Material for MkDocs cairosvg==2.7.1 mkdocstrings[python]==0.26.1