docs/en/docs/release-notes.md
Unblocks ✨ SO MANY THINGS ✨
Before this, router.include_router(other_router) would take each path operation from other_router and "clone" it, or recreate it from scratch.
This would mean that in the end there was only one top level router, part of the app.
The way it is structured here is that there are a few additional classes to handle intermediate metadata for router and route inclusion. That way the information of "router X includes Y and Y includes Z" is stored somewhere, without affecting (recreating / clonning) the final route.
Dependencies for 404: previously I intended to support dependencies that would be executed even for 404, but that would conflict with the fact that a router could not find a match, but the next router did find a match. Executing dependencies in the router that did not find a match would not make sense, they could consume the request, body, etc. This original idea was discarded.
Now router.routes is no longer a plain list of APIRoute objects, it can contain these intermediate objects that can contain additional routers, forming a tree.
Any logic that depended on iterating on the router.routes directly would be affected, that logic cannot expect to be able to extract data from a plain list of routes, as it's no longer a plain list but a tree.
Additionally, any logic that iterated on router.routes to modify them would now also see these new objects, and would not see all the routes in the app.
router.routes should be considered an internal implementation detail, only passed around to the FastAPI functions that need it.
subrouter in mainrouter can be done before adding routes (path operations) to subrouter, because now the the entire object is stored instead of copying the routes.This is not documented yet, so it's not officially supported yet and could change in the future.
But, as APIRoute and APIRouter instances are now preserved, they could be customized.
APIRouter has two new methods, .matches() and .handle(), counterpart to the existing ones in APIRoute. With this a router could customize how it matches and handles requests. For example, it could match only requests that include some specific header, for example for handling versions in headers.
Still, for now, consider this very experimental and potentially changing and breaking in the future.
APIRoute subclasses (undocumented, but alraedy works as desccribed above)APIRouter subclasses (undocumented, but already works as described above)Annotated in inline example in docs/en/docs/tutorial/body-multiple-params.md. PR #15591 by @TheArchons.docs/en/docs/tutorial/security/oauth2-jwt.md. PR #14781 by @zadevhub.changing_dir instead of CLIRunner.isolated_filesystem to set working dir. PR #15616 by @YuriiMotov.httpx2 test dependency to avoid deprecation warning. PR #15603 by @YuriiMotov.convert_underscores=True (the default). PR #15589 by @tiangolo.--entrypoint CLI option. PR #15464 by @YuriiMotov.index.md. PR #15534 by @YuriiMotov.virtual-environments.md. PR #15463 by @isaacbernat.docs/pt/docs/advanced/generate-clients.md. PR #15456 by @Will-thom.translate workflow. PR #15468 by @YuriiMotov.@app.vibe(). PR #15280 by @tiangolo.
lint.sh. PR #15136 by @svlandeg.pyproject.toml with entrypoint. PR #15075 by @tiangolo.target=_blank for links in docs. PR #15063 by @tiangolo.max_digits and decimal_places. PR #14944 by @YuriiMotov.scripts/people.py. PR #15088 by @YuriiMotov.commit_in_place passed via env variable in translate.yml workflow. PR #15151 by @YuriiMotov.ty to precommit. PR #15091 by @svlandeg.docs/en/docs/_llm-test.md. PR #15007 by @adityagiri3600.yield. PR #15022 by @tiangolo.
>=0.40.0 to >=0.46.0, as it's needed to properly unrwap and re-raise exceptions from exception groups.yield. PR #15023 by @tiangolo.await in StreamingResponse code example to allow cancellation. PR #14681 by @casperdcl.docs_src/websockets to docs_src/websockets_ to avoid import errors. PR #14979 by @YuriiMotov.pytest-xdist and pytest-cov. PR #14992 by @YuriiMotov.benchmark job in test workflow. PR #14974 by @YuriiMotov.strict_content_type checking for JSON requests. PR #14978 by @tiangolo.
Content-Type header with a valid JSON value, like application/json, and rejects requests that don't.Content-Type header you can disable this with strict_content_type=False.griffelib instead of griffe. PR #14973 by @svlandeg.FastAPI People workflow. PR #14951 by @YuriiMotov.fastapi-slim. PR #14958 by @tiangolo.fastapi-slim, no more versions will be released, use only "fastapi[standard]" or fastapi. PR #14957 by @tiangolo."contentMediaType": "application/octet-stream" instead of "format": "binary". PR #14953 by @tiangolo.master branch and when run by scheduler. PR #14940 by @YuriiMotov.docs/en/docs/tutorial/first-steps.md. PR #14708 by @SanjanaS10.fastapi-slim, deprecate it, and make it only depend on fastapi. PR #14894 by @tiangolo.dict by Mapping on HTTPException.headers. PR #12997 by @rijenkii.dfn tag for definitions instead of abbr in docs. PR #14744 by @YuriiMotov.abbr and dfn tags. PR #14747 by @YuriiMotov.test workflow to run tests with inline-snapshot=review. PR #14876 by @YuriiMotov.on_startup and on_shutdown parameters of APIRouter. PR #14873 by @YuriiMotov.create_model_field, better types for lenient_issubclass. PR #14860 by @tiangolo.on_event in FastAPI for compatibility with the next Starlette, while keeping backwards compatibility. PR #14851 by @tiangolo.fastapi[all] minimum dependencies: ujson >=5.8.0, orjson >=3.9.3. PR #14846 by @tiangolo.TypeAliasType. PR #13920 by @cstruct.Response type hint as dependency annotation. PR #14794 by @jonathan-fulton.Json[list[str]] type (issue #10997). PR #14616 by @mkanetsuna.advanced-dependencies.md. PR #14815 by @Rayyan-Oumlil.viewport meta tag to improve Swagger UI on mobile devices. PR #14777 by @Joab0.ValidationError schema to include input and ctx. PR #14791 by @jonathan-fulton.Authorization header credentials. PR #14786 by @WaveTheory1.anyOf refs for app-level responses with specified content and model as Union. PR #14463 by @DJMcoder.IncEx type from Pydantic instead of duplicating it. PR #14641 by @mvanderlee.docs_src/app_testing/app_b code example. PR #14573 by @timakaa.docs/en/docs/contributing.md. PR #14757 by @YuriiMotov.response_model when possible. PR #14753 by @YuriiMotov.WSGIMiddleware from a2wsgi instead of deprecated fastapi.middleware.wsgi.WSGIMiddleware. PR #14756 by @YuriiMotov.uk documentation. PR #14795 by @roli2py.llm-prompt.md for Korean language. PR #14763 by @seuthootDev.uv.lock gets the internal label. PR #14759 by @svlandeg.lint job from test CI workflow. PR #14593 by @YuriiMotov.pydantic.v1. PR #14575 by @tiangolo.
pydantic >=2.7.0.standard dependencies now include pydantic-settings >=2.0.0 and pydantic-extra-types >=2.0.0.docs_src/python_types/tutorial005_py39.py. PR #14565 by @paras-verma7454.markdown-include-variants from 0.0.7 to 0.0.8. PR #14556 by @YuriiMotov.Annotated with Body(). PR #14512 by @tiangolo.scripts/mkdocs_hooks.py. PR #14457 by @yujiteshima.__call__ method. PR #14458 by @YuriiMotov.separate_input_output_schemas=False with computed_field. PR #14453 by @YuriiMotov.functools.partial(). PR #9753 by @lieryan.@functools.wraps()) used with forward references. PR #5077 by @lucaswiman.is_coroutine check to reuse internal supported variants (unwrap, check class). PR #14434 by @tiangolo.separate_input_output_schemas=False. PR #13207 by @vgrafe.servers parameter. PR #14405 by @YuriiMotov.serialize sequence value with Pydantic V2. PR #14297 by @YuriiMotov.{type_} in FastAPIError. PR #14416 by @Just-Helpful.Form parameter list. PR #14303 by @YuriiMotov.None if that's the default), for compatibility with HTML forms. PR #13537 by @MarinPostma.pip in case of No module named pip error in virtual-environments.md. PR #14211 by @zadevhub.TypeError when encoding a decimal with a NaN or Infinity value. PR #12935 by @kentwelcome.401 status code in security classes when credentials are missing. PR #13786 by @YuriiMotov.
403 status code, check the new docs about how to override the classes, to use the same old behavior: Use Old 403 Authentication Error Status Codes.lang-all label. PR #14213 by @YuriiMotov.latest-changes GitHub Action and pin actions/checkout@v5. PR #14403 by @svlandeg.add-permalinks and add-permalinks-page to scripts/docs.py. PR #14033 by @YuriiMotov.Depends() and Security() hashable, as a workaround for other tools interacting with these internal parts. PR #14372 by @tiangolo.0.51.0. PR #14282 by @musicinmybrain.Depends(func, scope='function') for top level (parameterless) dependencies. PR #14301 by @luzzodev.yield, noting the changes in 0.121.0, adding scope. PR #14287 by @tiangolo.scope="request" for dependencies with yield that exit before the response is sent. PR #14262 by @tiangolo.
get_param_sub_dependant. PR #14255 by @tiangolo.0.50.0. PR #14234 by @YuriiMotov.license and license-files to pyproject.toml, remove License from classifiers. PR #14230 by @YuriiMotov.There are no major nor breaking changes in this release. ☕️
The internal reference documentation now uses annotated_doc.Doc instead of typing_extensions.Doc, this adds a new (very small) dependency on annotated-doc, a package made just to provide that Doc documentation utility class.
I would expect typing_extensions.Doc to be deprecated and then removed at some point from typing_extensions, for that reason there's the new annotated-doc micro-package. If you are curious about this, you can read more in the repo for annotated-doc.
This new version 0.120.0 only contains that transition to the new home package for that utility class Doc.
typing_extensions.Doc to annotated_doc.Doc. PR #14222 by @tiangolo.waiting label in issue-manager. PR #14156 by @YuriiMotov.FastAPI now (temporarily) supports both Pydantic v2 models and pydantic.v1 models at the same time in the same app, to make it easier for any FastAPI apps still using Pydantic v1 to gradually but quickly migrate to Pydantic v2.
from fastapi import FastAPI
from pydantic import BaseModel as BaseModelV2
from pydantic.v1 import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
class ItemV2(BaseModelV2):
title: str
summary: str | None = None
app = FastAPI()
@app.post("/items/", response_model=ItemV2)
def create_item(item: Item):
return {"title": item.name, "summary": item.description}
Adding this feature was a big effort with the main objective of making it easier for the few applications still stuck in Pydantic v1 to migrate to Pydantic v2.
And with this, support for Pydantic v1 is now deprecated and will be removed from FastAPI in a future version soon.
Note: have in mind that the Pydantic team already stopped supporting Pydantic v1 for recent versions of Python, starting with Python 3.14.
You can read in the docs more about how to Migrate from Pydantic v1 to Pydantic v2.
from pydantic.v1 import BaseModel, mixed Pydantic v1 and v2 models in the same app. PR #14168 by @tiangolo.mkdocs_hooks.py to add title to page's metadata (remove permalinks in social cards). PR #14125 by @YuriiMotov.StreamingResponses with dependencies with yield or UploadFiles, close after the response is done. PR #14099 by @tiangolo.Before FastAPI 0.118.0, if you used a dependency with yield, it would run the exit code after the path operation function returned but right before sending the response.
This change also meant that if you returned a StreamingResponse, the exit code of the dependency with yield would have been already run.
For example, if you had a database session in a dependency with yield, the StreamingResponse would not be able to use that session while streaming data because the session would have already been closed in the exit code after yield.
This behavior was reverted in 0.118.0, to make the exit code after yield be executed after the response is sent.
You can read more about it in the docs for Advanced Dependencies - Dependencies with yield, HTTPException, except and Background Tasks. Including what you could do if you wanted to close a database session earlier, before returning the response to the client.
tutorial/security/oauth2-jwt/ to use pwdlib with Argon2 instead of passlib. PR #13917 by @Neizvestnyj.File is declared after Form parameter. PR #11194 by @thomasleveil.None as return type for bodiless responses. PR #9425 by @hofrob.type field. PR #13639 by @sammasak.external_docs parameter to FastAPI. PR #13713 by @cmtoro.default_factory for response model field with Pydantic V1. PR #9704 by @vvanglro.jsonable_encoder alters json_encoders of Pydantic v1 objects. PR #4972 by @aboubacs.allow_arbitrary_types when only 1 argument is used on the API endpoint. PR #13694 by @rmawatson.inspect.getcoroutinefunction() can break testing with unittest.mock.patch(). PR #14022 by @secrett2633.dependency-cache dict in solve_dependencies only if None (don't re-create if empty). PR #13689 by @bokshitsky.test_tutorial/test_header_params/test_tutorial003.py. PR #13864 by @Amogha-ark.httpx to >=0.23.0,<1.0.0. PR #14086 by @YuriiMotov.tutorial/cookie-params.md. PR #13510 by @Kludex.path-params-numeric-validations.md for languages en, es and uk.. PR #14059 by @svlandeg.docs.py generate-readme command to remove permalinks from headers. PR #14055 by @YuriiMotov.--forwarded-allow-ips="*". PR #14028 by @tiangolo.dict() in docs/tutorial/body.md. PR #13906 by @jomkv.termynal.js. PR #13714 by @Ashish-Pandey62.url field in error responses in docs. PR #13655 by @Taoup.scope claim in line with the standard in docs_src/security/tutorial005.py. PR #11189 by @DurandA.docs/en/docs/advanced/generate-clients.md. PR #13793 by @mrlubos.docs/zh/docs/python-types.md. PR #13997 by @anfreshman.docs/pt/docs/async.md. PR #13863 by @EdmilsonRodrigues.docs/ja/docs/tutorial/body.md. PR #13927 by @KoyoMiyazaki.docs/fa/docs/environment-variables.md. PR #13923 by @Mohammad222PR.docs/fa/docs/python-types.md. PR #13524 by @Mohammad222PR.docs/pt/docs/project-generation.md. PR #13875 by @EdmilsonRodrigues.docs/fa/docs/async.md. PR #13541 by @Mohammad222PR.docs/bn/about/index.md. PR #13882 by @sajjadrahman56.mkdocs_hooks to handle headers with permalinks when building docs. PR #14025 by @tiangolo.mkdocs-macros-plugin from 1.3.7 to 1.3.9. PR #14003 by @YuriiMotov.docs/en/docs/contributing.md. PR #13886 by @YuriiMotov.Installing fastapi[standard] now includes fastapi-cloud-cli.
This will allow you to deploy to FastAPI Cloud 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].
docs/ru/docs/advanced/response-directly.md. PR #13801 by @NavesSapnis.docs/ru/docs/advanced/additional-status-codes.md. PR #13799 by @NavesSapnis.docs/uk/docs/tutorial/body-updates.md. PR #13804 by @valentinDruzhinin.Form. PR #13827 by @patrick91.docs/en/docs/advanced/response-directly.md. PR #13800 by @NavesSapnis.docs/uk/docs/tutorial/response-model.md. PR #13792 by @valentinDruzhinin.docs/uk/docs/tutorial/security/index.md. PR #13805 by @valentinDruzhinin.docs/ja/docs/tutorial/encoder.md. PR #13815 by @ruzia.docs/ja/docs/tutorial/handling-errors.md. PR #13814 by @ruzia.docs/ja/docs/tutorial/body-fields.md. PR #13802 by @ruzia.docs/ru/docs/advanced/index.md. PR #13797 by @NavesSapnis.\f) character for Pydantic V2. PR #13698 by @YuriiMotov.refreshUrl parameter in OAuth2PasswordBearer. PR #11460 by @snosratiershad.password and client_secret in OAuth2PasswordRequestForm, make docs show password fields for passwords. PR #11032 by @Thodoris1999.settings. PR #13505 by @valentinDruzhinin.validate_response_recursive. PR #13507 by @valentinDruzhinin.async def without await. PR #13642 by @swastikpradhan1999.docs/en/docs/tutorial/handling-errors.md. PR #13623 by @gsheni.docs/ru/docs/advanced/response-change-status-code.md. PR #13791 by @NavesSapnis.docs/fa/docs/learn/index.md. PR #13518 by @Mohammad222PR.docs/ko/docs/advanced/sub-applications.md. PR #4543 by @NinaHwang.docs/uk/docs/tutorial/schema-extra-example.md. PR #13769 by @valentinDruzhinin.docs/uk/docs/tutorial/query-param-models.md. PR #13748 by @valentinDruzhinin.docs/bn/docs/environment-variables.md. PR #13629 by @SakibSibly.docs/uk/docs/tutorial/query-params-str-validations.md page. PR #13546 by @valentinDruzhinin.docs/ru/docs/tutorial/cookie-param-models.md. PR #13616 by @EgorOnishchuk.docs/ko/docs/tutorial/extra-models.md. PR #13063 by @timothy-jeong.docs/uk/docs/tutorial/path-params-numeric-validations.md page. PR #13548 by @valentinDruzhinin.docs/uk/docs/tutorial/middleware.md page. PR #13520 by @valentinDruzhinin.docs/uk/docs/tutorial/background-tasks.md page. PR #13502 by @valentinDruzhinin.docs/uk/docs/tutorial/cors.md page. PR #13519 by @valentinDruzhinin.docs/ko/docs/advanced/events.md. PR #13487 by @bom1215.docs/uk/docs/tutorial/handling-errors.md page. PR #13420 by @valentinDruzhinin.docs/ru/docs/tutorial/request-form-models.md. PR #13552 by @EgorOnishchuk.docs/ko/docs/virtual-environments.md. PR #13630 by @sungchan1.docs/ru/docs/tutorial/header-param-models.md. PR #13526 by @minaton-ru.docs/zh/docs/tutorial/index.md. PR #13374 by @Zhongheng-Cheng.docs/zh/docs/deployment/manually.md. PR #13324 by @Zhongheng-Cheng.docs/zh/docs/deployment/server-workers.md. PR #13292 by @Zhongheng-Cheng.docs/zh/docs/tutorial/first-steps.md. PR #13348 by @Zhongheng-Cheng.inline-snapshot to support different Pydantic versions in the test suite. PR #12534 by @15r10nk.docs/en/mkdocs.yml configuration file. PR #13542 by @svlandeg.docs/en/docs/tutorial/middleware.md. PR #13444 by @Rishat-F.docs/uk/docs/tutorial/metadata.md page. PR #13459 by @valentinDruzhinin.docs/uk/docs/tutorial/response-status-code.md page. PR #13462 by @valentinDruzhinin.docs/uk/docs/tutorial/cookie-param-models.md page. PR #13460 by @valentinDruzhinin.docs/uk/docs/tutorial/header-param-models.md page. PR #13461 by @valentinDruzhinin.docs/ja/docs/virtual-environments.md. PR #13304 by @k94-ishi.docs/ko/docs/tutorial/security/oauth2-jwt.md. PR #13333 by @yes0ng.docs/vi/docs/deployment/cloud.md. PR #13407 by @ptt3199.Annotated custom validations, like AfterValidator, revert #13440. PR #13442 by @tiangolo.
>=0.40.0,<0.47.0. PR #13426 by @musicinmybrain.docs/uk/docs/tutorial/debugging.md. PR #13370 by @valentinDruzhinin.docs/uk/docs/tutorial/query-params.md. PR #13362 by @valentinDruzhinin.docs/uk/docs/tutorial/path-params.md. PR #13354 by @valentinDruzhinin.docs/ja/docs/tutorial/cookie-param-models.md. PR #13330 by @k94-ishi.docs/uk/docs/tutorial/body-multiple-params.md. PR #13408 by @valentinDruzhinin.docs/ja/docs/tutorial/query-param-models.md. PR #13323 by @k94-ishi.docs/uk/docs/tutorial/body-nested-models.md. PR #13409 by @valentinDruzhinin.docs/vi/docs/deployment/versions.md. PR #13406 by @ptt3199.docs/vi/docs/deployment/index.md. PR #13405 by @ptt3199.docs/uk/docs/tutorial/request-forms.md. PR #13383 by @valentinDruzhinin.docs/uk/docs/tutorial/testing.md. PR #13371 by @valentinDruzhinin.query_params_str_validations. PR #13218 by @alv2017.app_testing. PR #13220 by @alv2017.dependency_testing. PR #13223 by @alv2017....). PR #13377 by @tiangolo.body-multiple-params. PR #13345 by @DanielYang59.docs/uk/docs/tutorial/header-params.md. PR #13381 by @valentinDruzhinin.docs/uk/docs/tutorial/request-files.md. PR #13395 by @valentinDruzhinin.docs/uk/docs/tutorial/request-form-models.md. PR #13384 by @valentinDruzhinin.docs/uk/docs/tutorial/request-forms-and-files.md. PR #13386 by @valentinDruzhinin.docs/ko/docs/help-fastapi.md. PR #13262 by @Zerohertz.docs/ko/docs/advanced/custom-response.md. PR #13265 by @11kkw.docs/ko/docs/tutorial/security/simple-oauth2.md. PR #13335 by @yes0ng.docs/ru/docs/advanced/response-cookies.md. PR #13327 by @Stepakinoyan.docs/vi/docs/tutorial/static-files.md. PR #11291 by @ptt3199.docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md. PR #13257 by @11kkw.docs/vi/docs/virtual-environments.md. PR #13282 by @ptt3199.docs/uk/docs/tutorial/static-files.md. PR #13285 by @valentinDruzhinin.docs/vi/docs/environment-variables.md. PR #13287 by @ptt3199.docs/vi/docs/fastapi-cli.md. PR #13294 by @ptt3199.docs/uk/docs/features.md. PR #13308 by @valentinDruzhinin.docs/uk/docs/learn/index.md. PR #13306 by @valentinDruzhinin.docs/pt/docs/deployment/https.md. PR #13317 by @Joao-Pedro-P-Holanda.docs/pt/docs/index.md. PR #13328 by @ceb10n.docs/ru/docs/advanced/websockets.md. PR #13279 by @Rishat-F.tests/test_modules_same_name_body/test_main.py. PR #13411 by @alv2017.wrangler-action v3. PR #13415 by @joakimnordling.OAuth2PasswordRequestForm and OAuth2PasswordRequestFormStrict fixed grant_type "password" RegEx. PR #9783 by @skarfie123.APIKeyBase super class. PR #3142 by @ShahriyarR.docs/en/docs/tutorial/extra-models.md. PR #13061 by @timothy-jeong.tutorial002 to deal with tax=0 case. PR #13230 by @togogh.docs/ja/docs/environment-variables.md. PR #13226 by @k94-ishi.docs/ru/docs/advanced/async-tests.md. PR #13227 by @Rishat-F.docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md. PR #13252 by @Rishat-F.docs/ru/docs/tutorial/bigger-applications.md. PR #13154 by @alv2017.>=3.2.1,<5.0.0. PR #13273 by @tiangolo.notify_translations.py empty env var handling for PR label events vs workflow_dispatch. PR #13272 by @tiangolo.scripts/notify_translations.py, no need for a custom GitHub Action. PR #13270 by @tiangolo.python-multipart to >=0.0.18. PR #13219 by @DanielKusyDev.>=0.40.0,<0.46.0. PR #13117 by @Kludex.jinja2 to >=3.1.5. PR #13194 by @DanielKusyDev.fastapi-cli UI examples in docs. PR #13107 by @Zhongheng-Cheng.docs/en/docs/virtual-environments.md. PR #13124 by @tiangolo.docs/en/docs/contributing.md. PR #12899 by @kingsubin.docs/en/docs/tutorial/sql-databases.md. PR #13081 by @alv2017.docs/ru/docs/tutorial/query-param-models.md. PR #12994 by @alejsdev.fastapi-cli. PR #13031 by @tiangolo.docs/pt/docs/tutorial/request-forms.md. PR #13216 by @Joao-Pedro-P-Holanda.docs/pt/docs/advanced/settings.md. PR #13209 by @ceb10n.docs/pt/docs/tutorial/security/oauth2-jwt.md. PR #13205 by @ceb10n.docs/id/docs/index.md. PR #13191 by @gerry-sabar.docs/id/docs/tutorial/static-files.md. PR #13092 by @guspan-tanadi.docs/pt/docs/tutorial/security/get-current-user.md. PR #13188 by @ceb10n.docs/pt/docs/advanced/benchmarks.md. PR #13187 by @ceb10n.docs/ru/docs/tutorial/security/first-steps.md. PR #13159 by @Yarous.docs/ja/docs/tutorial/path-params-numeric-validations.md. PR #12238 by @FakeDocument.docs/zh/docs/fastapi-cli.md. PR #13102 by @Zhongheng-Cheng.docs/zh/docs/advanced/security/oauth2-scopes.md. PR #13110 by @ChenPu2002.docs/id/docs/tutorial/path-params.md. PR #13086 by @gerry-sabar.docs/ko/docs/tutorial/sql-databases.md. PR #13093 by @GeumBinLee.docs/zh/docs/async.md. PR #13095 by @Zhongheng-Cheng.docs/zh/docs/advanced/openapi-webhooks.md. PR #13091 by @Zhongheng-Cheng.docs/zh/docs/advanced/async-tests.md. PR #13074 by @Zhongheng-Cheng.docs/uk/docs/fastapi-cli.md. PR #13020 by @ykertytsky.docs/zh/docs/advanced/events.md. PR #12512 by @ZhibangYue./docs/ru/docs/tutorial/sql-databases.md. PR #13079 by @alv2017.docs/zh/docs/advanced/testing-dependencies.md. PR #13066 by @Zhongheng-Cheng.docs/zh-hant/docs/tutorial/index.md. PR #13075 by @codingjenny.docs/zh/docs/tutorial/sql-databases.md. PR #13051 by @Zhongheng-Cheng.docs/zh/docs/tutorial/query-params-str-validations.md. PR #12928 by @Vincy1230.docs/zh/docs/tutorial/header-param-models.md. PR #13040 by @Zhongheng-Cheng.docs/zh/docs/tutorial/path-params.md. PR #12926 by @Vincy1230.docs/zh/docs/tutorial/first-steps.md. PR #12923 by @Vincy1230.docs/ru/docs/deployment/docker.md. PR #13048 by @anklav24.docs/pt/docs/advanced/generate-clients.md. PR #13030 by @vitumenezes.docs/id/docs/tutorial/first-steps.md. PR #13042 by @gerry-sabar.docs/zh/docs/tutorial/cookie-param-models.md. PR #13038 by @Zhongheng-Cheng.docs/zh/docs/tutorial/request-form-models.md. PR #13045 by @Zhongheng-Cheng.docs/ru/docs/virtual-environments.md. PR #13026 by @alv2017.docs/ko/docs/tutorial/testing.md. PR #12968 by @jts8257.docs/ko/docs/advanced/async-test.md. PR #12918 by @icehongssii.docs/ru/docs/tutorial/security/oauth2-jwt.md. PR #10601 by @AlertRED.docs/ru/docs/tutorial/security/simple-oauth2.md. PR #10599 by @AlertRED.docs/ru/docs/tutorial/security/get-current-user.md. PR #10594 by @AlertRED.docs/zh-hant/docs/features.md. PR #12441 by @codingjenny.docs/zh-hant/docs/virtual-environments.md. PR #12791 by @Vincy1230.docs/ko/docs/advanced/templates.md. PR #12726 by @Heumhub.docs/ru/docs/fastapi-cli.md. PR #13041 by @alv2017.docs/ko/docs/tutorial/cookie-param-models.md. PR #13000 by @hard-coders.docs/ko/docs/tutorial/header-param-models.md. PR #13001 by @hard-coders.docs/ko/docs/tutorial/request-form-models.md. PR #13002 by @hard-coders.docs/ko/docs/tutorial/request-forms.md. PR #13003 by @hard-coders.docs/ko/docs/resources/index.md. PR #13004 by @hard-coders.docs/ko/docs/how-to/configure-swagger-ui.md. PR #12898 by @nahyunkeem.docs/ko/docs/advanced/additional-status-codes.md. PR #12715 by @nahyunkeem.docs/zh-hant/docs/tutorial/first-steps.md. PR #12467 by @codingjenny.notify-translations.yml. PR #12915 by @tinyboxvk.yield. PR #5823 by @sombek.docs/de/docs/advanced/using-request-directly.md. PR #12685 by @alissadb.docs/de/docs/how-to/conditional-openapi.md. PR #12689 by @alissadb.docs/zh-hant/docs/async.md. PR #12990 by @ILoveSorasakiHina.docs/zh-hant/docs/tutorial/query-param-models.md. PR #12932 by @Vincy1230.docs/ko/docs/advanced/testing-dependencies.md. PR #12992 by @Limsunoh.docs/ko/docs/advanced/websockets.md. PR #12991 by @kwang1215.docs/pt/docs/tutorial/response-model.md. PR #12933 by @AndreBBM.docs/ko/docs/advanced/middlewares.md. PR #12753 by @nahyunkeem.docs/ko/docs/advanced/openapi-webhooks.md. PR #12752 by @saeye.docs/zh/docs/tutorial/query-param-models.md. PR #12931 by @Vincy1230.docs/ru/docs/tutorial/query-param-models.md. PR #12445 by @gitgernit.docs/ko/docs/tutorial/query-param-models.md. PR #12940 by @jts8257.docs/zh/docs/tutorial/sql-databases.md, it references files that are no longer on the repo. PR #12949 by @tiangolo.docs/en/docs/tutorial/body.md. PR #12757 by @gsheni.docs/en/docs/advanced/testing-dependencies.md. PR #12647 by @AyushSinghal1794.docs/en/docs/tutorial/metadata.md. PR #12773 by @Nimitha-jagadeesha.docs/en/docs/tutorial/dependencies/dependencies-with-yield.md. PR #12045 by @xuvjso.docs/en/docs/tutorial/dependencies/global-dependencies.md. PR #12653 by @vishnuvskvkl.docs/en/docs/tutorial/body-updates.md. PR #12712 by @davioc.docs/en/docs/tutorial/header-param-models.md. PR #12814 by @zhaohan-dong.contributing.md docs, include note to not translate this page. PR #12841 by @tiangolo.docs/en/docs/tutorial/request-forms.md. PR #12648 by @vishnuvskvkl.docs/en/docs/tutorial/request-form-models.md. PR #12649 by @vishnuvskvkl.docs/en/docs/tutorial/security/oauth2-jwt.md. PR #12650 by @OCE1960.docs/vi/docs/tutorial/first-steps.md. PR #12754 by @MxPy.docs/pt/docs/advanced/wsgi.md. PR #12769 by @Nimitha-jagadeesha.docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md. PR #12815 by @handabaldeep.docs/en/docs/tutorial/dependencies/classes-as-dependencies.md. PR #12813 by @handabaldeep.docs/en/docs/tutorial/middleware.md. PR #12819 by @alejsdev.docs/en/docs/tutorial/security/get-current-user.md. PR #12645 by @OCE1960.docs/en/docs/tutorial/security/first-steps.md. PR #12643 by @OCE1960.docs/de/docs/advanced/additional-responses.md. PR #12821 by @zhaohan-dong.docs/en/docs/advanced/generate-clients.md. PR #12642 by @AyushSinghal1794.docs/zh/docs/advanced/additional-responses.md. PR #12828 by @zhaohan-dong.docs/en/docs/tutorial/path-params-numeric-validations.md. PR #12825 by @zhaohan-dong.docs/en/docs/advanced/testing-websockets.md. PR #12761 by @hamidrasti.docs/en/docs/advanced/using-request-directly.md. PR #12760 by @hamidrasti.docs/advanced/wsgi.md. PR #12758 by @hamidrasti.docs/de/docs/tutorial/middleware.md. PR #12729 by @paintdog.docs/en/docs/tutorial/schema-extra-example.md. PR #12822 by @tiangolo.docs/fr/docs/advanced/additional-responses.md. PR #12634 by @fegmorte.docs/fr/docs/advanced/path-operation-advanced-configuration.md. PR #12633 by @kantandane.docs/fr/docs/advanced/response-directly.md. PR #12632 by @kantandane.docs/en/docs/tutorial/header-params.md. PR #12640 by @vishnuvskvkl.docs/en/docs/tutorial/cookie-param-models.md. PR #12639 by @vishnuvskvkl.docs/en/docs/tutorial/extra-models.md. PR #12638 by @vishnuvskvkl.docs/en/docs/tutorial/cors.md. PR #12637 by @vishnuvskvkl.docs/en/docs/tutorial/dependencies/sub-dependencies.md. PR #12810 by @handabaldeep.docs/en/docs/tutorial/body-nested-models.md. PR #12812 by @zhaohan-dong.docs/en/docs/tutorial/path-operation-configuration.md. PR #12809 by @AlexWendland.docs/en/docs/tutorial/request-files.md. PR #12818 by @zhaohan-dong.docs/en/docs/tutorial/query-param-models.md. PR #12817 by @handabaldeep.docs/en/docs/tutorial/path-params.md. PR #12811 by @AlexWendland.docs/en/docs/tutorial/response-model.md. PR #12621 by @kantandane.docs/en/docs/advanced/websockets.md. PR #12606 by @vishnuvskvkl.docs/en/docs/tutorial/cookie-params.md. PR #12808 by @handabaldeep.docs/en/docs/tutorial/middleware.md. PR #12807 by @AlexWendland.docs/en/docs/advanced/sub-applications.md. PR #12806 by @zhaohan-dong.docs/en/docs/advanced/response-headers.md. PR #12805 by @zhaohan-dong.docs/fr/docs/tutorial/first-steps.md. PR #12594 by @kantandane.docs/en/docs/advanced/response-cookies.md. PR #12804 by @zhaohan-dong.docs/en/docs/advanced/path-operation-advanced-configuration.md. PR #12802 by @zhaohan-dong.docs/en/docs/advanced/response-directly.md. PR #12803 by @handabaldeep.docs/zh/docs/tutorial/background-tasks.md. PR #12798 by @zhaohan-dong.docs/de/docs/tutorial/body-multiple-params.md. PR #12699 by @alissadb.docs/em/docs/tutorial/body-updates.md. PR #12799 by @AlexWendland.docs/en/docs/advanced/response-change-status-code.md. PR #12801 by @handabaldeep.docs/en/docs/advanced/openapi-callbacks.md. PR #12800 by @handabaldeep.docs/fr/docs/tutorial/body-multiple-params.md. PR #12598 by @kantandane.docs/en/docs/tutorial/body-multiple-params.md. PR #12593 by @Tashanam-Shahbaz.docs/pt/docs/tutorial/background-tasks.md. PR #12736 by @bhunao.docs/en/docs/advanced/custom-response.md. PR #12797 by @handabaldeep.docs/pt/docs/python-types.md. PR #12671 by @ceb10n.docs/de/docs/python-types.md. PR #12660 by @alissadb.docs/de/docs/advanced/dataclasses.md. PR #12658 by @alissadb.docs/fr/docs/tutorial/path-params.md. PR #12592 by @kantandane.docs/de/docs/how-to/configure-swagger-ui.md. PR #12690 by @alissadb.docs/en/docs/advanced/security/oauth2-scopes.md. PR #12572 by @krishnamadhavan.docs/en/docs/how-to/conditional-openapi.md. PR #12624 by @rabinlamadong.docs/en/docs/tutorial/dependencies/index.md. PR #12615 by @bharara.docs/en/docs/tutorial/response-status-code.md. PR #12620 by @kantandane.docs/en/docs/how-to/custom-docs-ui-assets.md. PR #12623 by @rabinlamadong.docs/en/docs/advanced/openapi-webhooks.md. PR #12605 by @salmantec.docs/en/docs/advanced/events.md. PR #12604 by @salmantec.docs/en/docs/advanced/dataclasses.md. PR #12603 by @salmantec.docs/es/docs/tutorial/cookie-params.md. PR #12602 by @antonyare93.docs/fr/docs/tutorial/path-params-numeric-validations.md. PR #12601 by @kantandane.docs/fr/docs/tutorial/background-tasks.md. PR #12600 by @kantandane.docs/en/docs/tutorial/encoder.md. PR #12597 by @tonyjly.docs/en/docs/how-to/custom-docs-ui-assets.md. PR #12557 by @philipokiokio.docs/en/docs/how-to/custom-request-and-route.md. PR #12560 by @philipokiokio.docs/ko/docs/advanced/testing-websockets.md. PR #12739 by @Limsunoh.docs/zh-hant/docs/environment-variables.md. PR #12785 by @Vincy1230.docs/zh/docs/environment-variables.md. PR #12784 by @Vincy1230.ko/docs/advanced/response-headers.md. PR #12740 by @kwang1215.docs/zh/docs/virtual-environments.md. PR #12790 by @Vincy1230./docs/ko/docs/environment-variables.md. PR #12526 by @Tolerblanc.docs/ko/docs/history-design-future.md. PR #12646 by @saeye.docs/ko/docs/advanced/advanced-dependencies.md. PR #12675 by @kim-sangah.docs/ko/docs/how-to/conditional-openapi.md. PR #12731 by @sptcnl.docs/ko/docs/advanced/using_request_directly.md. PR #12738 by @kwang1215.docs/ko/docs/advanced/testing-events.md. PR #12741 by @9zimin9.docs/ko/docs/security/index.md. PR #12743 by @kim-sangah.docs/pt/docs/advanced/path-operation-advanced-configuration.md. PR #12762 by @Joao-Pedro-P-Holanda.docs/ko/docs/advanced/wsgi.md. PR #12659 by @Limsunoh.docs/pt/docs/advanced/websockets.md. PR #12703 by @devfernandoa.docs/pt/docs/tutorial/security/simple-oauth2.md. PR #12520 by @LidiaDomingos.docs/ko/docs/advanced/response-directly.md. PR #12674 by @9zimin9.docs/pt/docs/advanced/middleware.md. PR #12704 by @devluisrodrigues.docs/pt/docs/advanced/openapi-callbacks.md. PR #12705 by @devfernandoa.docs/pt/docs/tutorial/request-files.md. PR #12706 by @devluisrodrigues.docs/pt/docs/advanced/custom-response.md. PR #12631 by @Joao-Pedro-P-Holanda.docs/pt/docs/tutorial/metadata.md. PR #12538 by @LinkolnR.docs/ko/docs/tutorial/metadata.md. PR #12541 by @kwang1215.docs/ko/docs/advanced/response-cookies.md. PR #12546 by @kim-sangah.docs/ko/docs/fastapi-cli.md. PR #12515 by @dhdld.docs/ko/docs/advanced/response-change-status-code.md. PR #12547 by @9zimin9.python-multipart for compatibility with newer version. PR #12627 by @tiangolo.docs/fr/docs/tutorial/body.md. PR #12596 by @kantandane.docs/fr/docs/tutorial/debugging.md. PR #12595 by @kantandane.docs/fr/docs/tutorial/query-params-str-validations.md. PR #12591 by @kantandane.docs/fr/docs/tutorial/query-params.md. PR #12589 by @kantandane.docs/en/tutorial/body-fields.md. PR #12588 by @lucaromagnoli.docs/de/docs/tutorial/response-status-code.md. PR #12585 by @abejaranoh.docs/en/docs/tutorial/body.md. PR #12586 by @lucaromagnoli.docs/en/docs/advanced/behind-a-proxy.md. PR #12583 by @imjuanleonard.docs/pl/docs/tutorial/first-steps.md. PR #12584 by @sebkozlo.docs/en/docs/advanced/middleware.md. PR #12582 by @montanarograziano.docs/en/docs/advanced/additional-status-codes.md. PR #12577 by @krishnamadhavan.docs/en/docs/advanced/advanced-dependencies.md. PR #12578 by @krishnamadhavan.docs/en/docs/advanced/additional-responses.md. PR #12576 by @krishnamadhavan.docs/en/docs/tutorial/static-files.md. PR #12575 by @lucaromagnoli.docs/en/docs/advanced/async-tests.md. PR #12568 by @krishnamadhavan.docs/pt/docs/advanced/behind-a-proxy.md. PR #12563 by @asmioglou.docs/de/docs/advanced/security/http-basic-auth.md. PR #12561 by @Nimitha-jagadeesha.docs/en/docs/tutorial/background-tasks.md. PR #12559 by @FarhanAliRaza.docs/fr/docs/python-types.md. PR #12558 by @Ismailtlem.docs/en/docs/how-to/graphql.md. PR #12564 by @philipokiokio.docs/en/docs/how-to/extending-openapi.md. PR #12562 by @philipokiokio.docs/en/docs/how-to/configure-swagger-ui.md. PR #12556 by @tiangolo.docs/en/docs/how-to/separate-openapi-schemas.md. PR #12555 by @tiangolo.docs/en/docs/advanced/security/http-basic-auth.md. PR #12553 by @tiangolo.docs/en/docs/tutorial/first-steps.md. PR #12552 by @tiangolo.docs/en/docs/python-types.md. PR #12551 by @tiangolo.docs/de/docs/advanced/async-tests.md. PR #12567 by @imjuanleonard.docs/pt/docs/tutorial/sql-databases.md. PR #12530 by @ilacftemp.docs/ko/docs/benchmarks.md. PR #12540 by @Limsunoh.docs/pt/docs/how-to/separate-openapi-schemas.md. PR #12518 by @ilacftemp.docs/zh-hant/docs/deployment/index.md. PR #12521 by @codingjenny.docs/zh-hant/docs/deployment/cloud.md. PR #12522 by @codingjenny.docs/zh-hant/docs/how-to/index.md. PR #12523 by @codingjenny.docs/zh-hant/docs/tutorial/index.md. PR #12524 by @codingjenny.docs/zh-hant/docs/how-to/index.md. PR #12468 by @codingjenny.docs/zh-hant/docs/tutorial/index.md. PR #12466 by @codingjenny.docs/pt/docs/tutorial/header-param-models.md. PR #12437 by @Joao-Pedro-P-Holanda.docs/pt/docs/how-to/extending-openapi.md. PR #12470 by @ilacftemp.docs/pt/docs/advanced/dataclasses.md. PR #12475 by @leoscarlato.docs/pt/docs/how-to/custom-request-and-route.md. PR #12483 by @devfernandoa.docs/zh-hant/docs/fastapi-cli.md. PR #12444 by @codingjenny.docs/zh-hant/docs/deployment/index.md. PR #12439 by @codingjenny.docs/pt/docs/how-to/testing-database.md. PR #12472 by @GuilhermeRameh.docs/pt/docs/how-to/custom-docs-ui-assets.md. PR #12473 by @devluisrodrigues.docs/pt/docs/advanced/response-headers.md. PR #12458 by @leonardopaloschi.docs/zh-hant/docs/deployment/cloud.md. PR #12440 by @codingjenny.docs/pt/docs/python-types.md. PR #12428 by @ceb10n.docs/ru/docs/environment-variables.md. PR #12436 by @wisderfin.docs/zh-hant/docs/resources/index.md. PR #12443 by @codingjenny.docs/zh-hant/docs/about/index.md. PR #12438 by @codingjenny.docs/pt/docs/tutorial/query-param-models.md. PR #12414 by @ceb10n.docs/pt/docs/deployment.md. PR #12427 by @ceb10n.docs/pt/docs/tutorial/body-updates.md. PR #12381 by @andersonrocha0.docs/pt/docs/advanced/response-cookies.md. PR #12417 by @Paulofalcao2002.Required shadowing from fastapi using Pydantic v2. PR #12197 by @pachewise.base_path for mdx_include Markdown extension in MkDocs. PR #12391 by @tiangolo.docs/project-generation.md. PR #12274 by @kayqueGovetri.docs/pt/docs/tutorial/cookie-param-models.md. PR #12298 by @ceb10n.docs/pt/docs/how-to/graphql.md. PR #12215 by @AnandaCampelo.docs/pt/docs/advanced/security/oauth2-scopes.md. PR #12263 by @ceb10n.docs/pt/docs/deployment/concepts.md. PR #12219 by @marcelomarkus.docs/pt/docs/how-to/conditional-openapi.md. PR #12221 by @marcelomarkus.docs/pt/docs/advanced/response-directly.md. PR #12266 by @Joao-Pedro-P-Holanda.docs/pt/docs/tutorial/cookie-params.md. PR #12297 by @ceb10n.docs/ko/docs/tutorial/index.md. PR #12278 by @kkotipy.docs/pt/docs/advanced/security/http-basic-auth.md. PR #12275 by @andersonrocha0.docs/pt/docs/deployment/cloud.md. PR #12217 by @marcelomarkus.docs/es/docs/python-types.md. PR #12235 by @JavierSanchezCastro.docs/nl/docs/environment-variables.md. PR #12200 by @maxscheijen.docs/pt/docs/deployment/manually.md. PR #12210 by @JoaoGustavoRogel.docs/pt/docs/deployment/server-workers.md. PR #12220 by @marcelomarkus.docs/pt/docs/how-to/configure-swagger-ui.md. PR #12222 by @marcelomarkus.sponsors_badge.yml. PR #12404 by @tiangolo.Now you can declare Query, Header, and Cookie parameters with Pydantic models. 🎉
Query Parameter ModelsUse Pydantic models for Query parameters:
from typing import Annotated, Literal
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
app = FastAPI()
class FilterParams(BaseModel):
limit: int = Field(100, gt=0, le=100)
offset: int = Field(0, ge=0)
order_by: Literal["created_at", "updated_at"] = "created_at"
tags: list[str] = []
@app.get("/items/")
async def read_items(filter_query: Annotated[FilterParams, Query()]):
return filter_query
Read the new docs: Query Parameter Models.
Header Parameter ModelsUse Pydantic models for Header parameters:
from typing import Annotated
from fastapi import FastAPI, Header
from pydantic import BaseModel
app = FastAPI()
class CommonHeaders(BaseModel):
host: str
save_data: bool
if_modified_since: str | None = None
traceparent: str | None = None
x_tag: list[str] = []
@app.get("/items/")
async def read_items(headers: Annotated[CommonHeaders, Header()]):
return headers
Read the new docs: Header Parameter Models.
Cookie Parameter ModelsUse Pydantic models for Cookie parameters:
from typing import Annotated
from fastapi import Cookie, FastAPI
from pydantic import BaseModel
app = FastAPI()
class Cookies(BaseModel):
session_id: str
fatebook_tracker: str | None = None
googall_tracker: str | None = None
@app.get("/items/")
async def read_items(cookies: Annotated[Cookies, Cookie()]):
return cookies
Read the new docs: Cookie Parameter Models.
Use Pydantic models to restrict extra values for Query parameters (also applies to Header and Cookie parameters).
To achieve it, use Pydantic's model_config = {"extra": "forbid"}:
from typing import Annotated, Literal
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
app = FastAPI()
class FilterParams(BaseModel):
model_config = {"extra": "forbid"}
limit: int = Field(100, gt=0, le=100)
offset: int = Field(0, ge=0)
order_by: Literal["created_at", "updated_at"] = "created_at"
tags: list[str] = []
@app.get("/items/")
async def read_items(filter_query: Annotated[FilterParams, Query()]):
return filter_query
This applies to Query, Header, and Cookie parameters, read the new docs:
Query, Cookie, Header. PR #12199 by @tiangolo.docs/pt/docs/advanced/security/http-basic-auth.md. PR #12195 by @ceb10n.alias. PR #12194 by @Wurstnase.docs/pt/docs/tutorial/request-form-models.md. PR #12175 by @ceb10n.docs/zh/docs/project-generation.md. PR #12170 by @waketzheng.docs/nl/docs/python-types.md. PR #12158 by @maxscheijen.docs/pt/docs/virtual-environments.md. PR #12163 by @marcelomarkus.docs/pt/docs/environment-variables.md. PR #12162 by @marcelomarkus.docs/pt/docs/tutorial/testing.md. PR #12164 by @marcelomarkus.docs/pt/docs/tutorial/debugging.md. PR #12165 by @marcelomarkus.docs/ko/docs/project-generation.md. PR #12157 by @BORA040126.issue-manager.yml. PR #12159 by @tiangolo.fastapi/params.py. PR #12143 by @surreal30.You can restrict form fields to only include those declared in a Pydantic model and forbid any extra field sent in the request using Pydantic's model_config = {"extra": "forbid"}:
from typing import Annotated
from fastapi import FastAPI, Form
from pydantic import BaseModel
app = FastAPI()
class FormData(BaseModel):
username: str
password: str
model_config = {"extra": "forbid"}
@app.post("/login/")
async def login(data: Annotated[FormData, Form()]):
return data
Read the new docs: Form Models - Forbid Extra Form Fields.
Now you can declare form fields with Pydantic models:
from typing import Annotated
from fastapi import FastAPI, Form
from pydantic import BaseModel
app = FastAPI()
class FormData(BaseModel):
username: str
password: str
@app.post("/login/")
async def login(data: Annotated[FormData, Form()]):
return data
Read the new docs: Form Models.
This release is mainly a big internal refactor to enable adding support for Pydantic models for Form fields, but that feature comes in the next release.
This release shouldn't affect apps using FastAPI in any way. You don't even have to upgrade to this version yet. It's just a checkpoint. 🤓
embed body fields, do not overwrite fields, compute once per router, refactor internals in preparation for Pydantic models in Form, Query and others. PR #12117 by @tiangolo.Form parameters" to make a checkpoint release. PR #12128 by @tiangolo. Restored by PR #12129.Form parameters. PR #12127 by @tiangolo. Reverted by PR #12128 to make a checkpoint release with only refactors. Restored by PR #12129.This release is mainly internal refactors, it shouldn't affect apps using FastAPI in any way. You don't even have to upgrade to this version yet. There are a few bigger releases coming right after. 🚀
check_file_field(), rename to ensure_multipart_is_installed() to clarify its purpose. PR #12106 by @tiangolo.create_response_field() to create_model_field() as it's used for more than response models. PR #12103 by @tiangolo.solve_dependencies() using dataclasses. PR #12100 by @tiangolo.analyze_param() to structure data with dataclasses instead of tuple. PR #12099 by @tiangolo.time.perf_counter() in middlewares. PR #12095 by @tiangolo.time.time() to time.perf_counter(). PR #11957 by @domdent.docs_src/path_params_numeric_validations/tutorial006.py. PR #11478 by @MuhammadAshiqAmeer.docs/en/docs/async.md. PR #12062 by @Alec-Gillis.response_class parameter, validations, and returning a response directly. PR #12067 by @tiangolo.CMD exec form. PR #11960 by @GPla.docs/nl/docs/features.md. PR #12101 by @maxscheijen.docs/pt/docs/advanced/testing-events.md. PR #12108 by @ceb10n.docs/pt/docs/advanced/security/index.md. PR #12114 by @ceb10n.docs/nl/docs/index.md. PR #12042 by @svlandeg.docs/zh/docs/how-to/index.md. PR #12070 by @synthpop123.include-hidden-files to True when using the upload-artifact GH action. PR #12118 by @svlandeg.latest-changes GitHub Action. PR #12073 by @tiangolo.allow_inf_nan option for Param and Body classes. PR #11867 by @giunio-prc.app.include_router merges nested lifespans. PR #9630 by @Lancetnik.FastAPI.add_api_route(). PR #10240 by @ordinary-jamie.docs/en/docs/virtual-environments.md. PR #12064 by @aymenkrifa.Security. PR #11168 by @0shah0.docs/en/docs/tutorial/body-multiple-params.md. PR #11978 by @svlandeg.email-validator dependency with dash. PR #11515 by @jirikuncar.docs/es/docs/project-generation.md. PR #11947 by @alejsdev.compresslevel parameter on docs for GZipMiddleware. PR #11350 by @junah201.docs/en/docs/tutorial/body.md with Python 3.10 union type example. PR #11415 by @rangzen.docs/pt/docs/tutorial/request_file.md. PR #12018 by @Joao-Pedro-P-Holanda.docs/ja/docs/learn/index.md. PR #11592 by @ukwhatn.docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md. PR #12028 by @xuvjso.docs/ur/docs/benchmarks.md. PR #10046 by @AhsanSheraz..gitignore. PR #11940 by @gitworkflows.>=0.37.2,<0.39.0. PR #11876 by @musicinmybrain.docs/pt/docs/tutorial/bigger-applications.md. PR #11971 by @marcelomarkus.docs/pt/docs/advanced/testing-websockets.md. PR #11994 by @ceb10n.docs/pt/docs/advanced/testing-dependencies.md. PR #11995 by @ceb10n.docs/pt/docs/advanced/using-request-directly.md. PR #11956 by @ceb10n.docs/fr/docs/tutorial/body-multiple-params.md. PR #11796 by @pe-brian.docs/zh/docs/tutorial/query-params.md. PR #11557 by @caomingpei.docs/zh/docs/advanced/testing-dependencies.md. PR #11944 by @bestony.docs/pt/docs/advanced/sub-applications.md and docs/pt/docs/advanced/behind-a-proxy.md. PR #11856 by @marcelomarkus.docs/pt/docs/tutorial/cors.md and docs/pt/docs/tutorial/middleware.md. PR #11916 by @wesinalves.docs/fr/docs/tutorial/path-params-numeric-validations.md. PR #11788 by @pe-brian.pyproject.toml, shows in PyPI. PR #11152 by @Pierre-VF.deploy_docs_status.py to account for deploy URLs with or without trailing slash. PR #11965 by @tiangolo.pip install "fastapi[standard]" with standard dependencies and python -m fastapi. PR #11935 by @tiangolo.Install with:
pip install "fastapi[standard]"
python -m fastapi
fastapi-cli[standard] >=0.0.5.Before this, fastapi would include the standard dependencies, with Uvicorn and the fastapi-cli, etc.
And fastapi-slim would not include those standard dependencies.
Now fastapi doesn't include those standard dependencies unless you install with pip install "fastapi[standard]".
Before, you would install pip install fastapi, now you should include the standard optional dependencies (unless you want to exclude one of those): pip install "fastapi[standard]".
This change is because having the standard optional dependencies installed by default was being inconvenient to several users, and having to install instead fastapi-slim was not being a feasible solution.
Discussed here: #11522 and here: #11525
docs/pt/docs/alternatives.md. PR #11931 by @ceb10n.docs/ru/docs/tutorial/dependencies/sub-dependencies.md. PR #10515 by @AlertRED.docs/pt/docs/advanced/response-change-status-code.md. PR #11863 by @ceb10n.docs/pt/docs/reference/background.md. PR #11849 by @lucasbalieiro.docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md. PR #11848 by @Joao-Pedro-P-Holanda.docs/pt/docs/reference/apirouter.md. PR #11843 by @lucasbalieiro.approved-1. PR #11907 by @tiangolo.orjson and ujson from default dependencies. PR #11842 by @tiangolo.
pip install "fastapi[all]". But they are not included in pip install fastapi.docs/en/docs/fastapi-cli.md. PR #11716 by @alejsdev.docs/en/docs/fastapi-cli.md. PR #11715 by @alejsdev.docs/en/docs/tutorial/body-multiple-params.md. PR #11698 by @mwb-u.security/first-steps.md. PR #11674 by @alejsdev.security/first-steps.md. PR #11673 by @alejsdev.path-params-numeric-validations.md. PR #11672 by @alejsdev.Annotated and Query() params. PR #11664 by @tiangolo.fastapi/applications.py. PR #11593 by @petarmaric.fastapi-cli.md. PR #11524 by @svlandeg.docs/es/docs/how-to/graphql.md. PR #11697 by @camigomezdev.docs/pt/docs/reference/index.md. PR #11840 by @lucasbalieiro.docs/pt/docs/tutorial/dependencies/sub-dependencies.md. PR #11792 by @Joao-Pedro-P-Holanda.docs/tr/docs/tutorial/request-forms.md. PR #11553 by @hasansezertasan.docs/pt/docs/reference/exceptions.md. PR #11834 by @lucasbalieiro.docs/pt/docs/tutorial/dependencies/global-dependencies.md. PR #11826 by @Joao-Pedro-P-Holanda.docs/pt/docs/how-to/general.md. PR #11825 by @lucasbalieiro.docs/pt/docs/advanced/async-tests.md. PR #11808 by @ceb10n.docs/uk/docs/tutorial/first-steps.md. PR #11809 by @vkhoroshchak.docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-operators.md. PR #11804 by @Joao-Pedro-P-Holanda.docs/zh/docs/fastapi-cli.md. PR #11786 by @logan2d5.docs/pt/docs/advanced/openapi-webhooks.md. PR #11791 by @ceb10n.docs/tutorial/security/oauth2-jwt.md. PR #11781 by @logan2d5.docs/fr/docs/async.md . PR #11787 by @pe-brian.docs/pt/docs/advanced/advanced-dependencies.md. PR #11775 by @ceb10n.docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md. PR #11768 by @Joao-Pedro-P-Holanda.docs/pt/docs/advanced/additional-status-codes.md. PR #11753 by @ceb10n.docs/pt/docs/tutorial/dependencies/index.md. PR #11757 by @Joao-Pedro-P-Holanda.docs/pt/docs/advanced/settings.md. PR #11739 by @Joao-Pedro-P-Holanda.docs/fr/docs/learn/index.md. PR #11712 by @benjaminvandammeholberton.docs/pt/docs/how-to/index.md. PR #11731 by @vhsenna.docs/pt/docs/advanced/additional-responses.md. PR #11736 by @ceb10n.docs/pt/docs/advanced/benchmarks.md. PR #11713 by @ceb10n.docs/ko/docs/tutorial/response-status-code.md. PR #11718 by @nayeonkinn.docs/ko/docs/tutorial/extra-data-types.md. PR #11711 by @nayeonkinn.docs/ko/docs/tutorial/body-nested-models.md. PR #11710 by @nayeonkinn.docs/pt/docs/advanced/fastapi-cli.md. PR #11641 by @ayr-ton.docs/zh-hant/docs/fastapi-people.md. PR #11639 by @hsuanchi.docs/tr/docs/advanced/index.md. PR #11606 by @hasansezertasan.docs/tr/docs/deployment/cloud.md. PR #11610 by @hasansezertasan.docs/tr/docs/advanced/security/index.md. PR #11609 by @hasansezertasan.docs/tr/docs/advanced/testing-websockets.md. PR #11608 by @hasansezertasan.docs/tr/docs/how-to/general.md. PR #11607 by @hasansezertasan.docs/zh/docs/advanced/templates.md. PR #11620 by @chaoless.docs/tr/docs/deployment/index.md. PR #11605 by @hasansezertasan.docs/tr/docs/tutorial/static-files.md. PR #11599 by @hasansezertasan.docs/pl/docs/fastapi-people.md. PR #10196 by @isulim.docs/tr/docs/advanced/wsgi.md. PR #11575 by @hasansezertasan.docs/tr/docs/tutorial/cookie-params.md. PR #11561 by @hasansezertasan.docs/ru/docs/about/index.md. PR #10961 by @s111d.docs/zh/docs/tutorial/sql-databases.md. PR #11539 by @chaoless.docs/zh/docs/how-to/configure-swagger-ui.md. PR #11501 by @Lucas-lyh./docs/advanced/security/http-basic-auth.md. PR #11512 by @nick-cjyx9.fastapi command. PR #11522 by @tiangolo.
Try it out with:
$ pip install --upgrade fastapi
$ fastapi dev main.py
╭────────── FastAPI CLI - Development mode ───────────╮
│ │
│ Serving at: http://127.0.0.1:8000 │
│ │
│ API docs: http://127.0.0.1:8000/docs │
│ │
│ Running in development mode, for production use: │
│ │
│ fastapi run │
│ │
╰─────────────────────────────────────────────────────╯
INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [2248755] using WatchFiles
INFO: Started server process [2248757]
INFO: Waiting for application startup.
INFO: Application startup complete.
fastapi-slim including optional extras fastapi-slim[standard], and fastapi including by default the same standard extras. PR #11503 by @tiangolo.fastapi/security/api_key.py. PR #11481 by @ch33zer.security/http.py. PR #11455 by @omarmoo5.docs/zh-hant/benchmarks.md. PR #11484 by @KNChiu.docs/zh/docs/fastapi-people.md. PR #11476 by @billzhong.docs/zh/docs/how-to/index.md and docs/zh/docs/how-to/general.md. PR #11443 by @billzhong.docs/es/docs/tutorial/cookie-params.md. PR #11410 by @fabianfalon.UndefinedType. PR #9929 by @arjwilliams.fastapi/openapi/models.py. PR #10886 by @JoeTanto2.docs_src/extra_data_types. PR #10535 by @nilslindemann.docs/es/docs/async.md. PR #11400 by @fabianfalon.@hey-api/openapi-ts. PR #11339 by @jordanshatford.docs/zh/docs/index.html. PR #11430 by @waketzheng.docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md. PR #11411 by @anton2yakovlev.learn/index.md resources/index.md help/index.md about/index.md. PR #10807 by @nazarepiedady.docs/bn/docs/python-types.md. PR #11376 by @imtiaz101325.docs/ko/docs/tutorial/security/simple-oauth2.md. PR #5744 by @KdHyeon0661.docs/ko/docs/help-fastapi.md. PR #4139 by @kty4119.docs/ko/docs/advanced/events.md. PR #5087 by @pers0n4.docs/ja/docs/tutorial/path-operation-configuration.md. PR #1954 by @SwftAlpc.docs/ja/docs/tutorial/request-forms-and-files.md. PR #1946 by @SwftAlpc.docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md. PR #10532 by @AlertRED.docs/ko/docs/tutorial/debugging.md. PR #5695 by @JungWooGeon.fastapi/applications.py. PR #11335 by @igeni.fastapi/security/oauth2.py. PR #11368 by @shandongbinzhou.docs/en/docs/tutorial/extra-models.md. PR #11329 by @alejsdev.project-generation.md. PR #11326 by @alejsdev.python-multipart GitHub link in all docs from https://andrew-d.github.io/python-multipart/ to https://github.com/Kludex/python-multipart. PR #11239 by @joshjhans.docs/de/docs/tutorial/response-status-code.md. PR #10357 by @nilslindemann.docs/zh/docs/tutorial/query-params.md. PR #3480 by @jaystone776.docs/zh/docs/tutorial/body.md. PR #3481 by @jaystone776.docs/zh/docs/tutorial/path-params.md. PR #3479 by @jaystone776.docs/tutorial/body-fields.md. PR #3496 by @jaystone776.docs/tutorial/extra-models.md. PR #3497 by @jaystone776.docs/ja/docs/tutorial/metadata.md. PR #2667 by @tokusumi.docs/de/docs/contributing.md. PR #10487 by @nilslindemann.docs/ja/docs/tutorial/query-params.md. PR #10808 by @urushio.docs/zh/docs/tutorial/security/get-current-user.md. PR #3842 by @jaystone776.docs/zh/docs/advanced/openapi-callbacks.md. PR #3825 by @jaystone776.docs/zh/docs/advanced/extending-openapi.md. PR #3823 by @jaystone776.docs/zh/docs/advanced/testing-dependencies.md. PR #3819 by @jaystone776.docs/zh/docs/advanced/custom-request-and-route.md. PR #3816 by @jaystone776.docs/zh/docs/external-links.md. PR #3833 by @jaystone776.docs/zh/docs/advanced/templates.md. PR #3812 by @jaystone776.docs/zh/docs/advanced/sub-applications.md. PR #3811 by @jaystone776.docs/zh/docs/advanced/async-sql-databases.md. PR #3805 by @jaystone776.docs/zh/docs/advanced/middleware.md. PR #3804 by @jaystone776.docs/zh/docs/advanced/dataclasses.md. PR #3803 by @jaystone776.docs/zh/docs/advanced/using-request-directly.md. PR #3802 by @jaystone776.docs/zh/docs/advanced/security/http-basic-auth.md. PR #3801 by @jaystone776.docs/zh/docs/advanced/security/oauth2-scopes.md. PR #3800 by @jaystone776.docs/zh/docs/tutorial/cookie-params.md. PR #3486 by @jaystone776.docs/zh/docs/tutorial/header-params.md. PR #3487 by @jaystone776.docs/tutorial/response-status-code.md. PR #3498 by @jaystone776.docs/de/docs/tutorial/security/first-steps.md. PR #10432 by @nilslindemann.docs/de/docs/advanced/events.md. PR #10693 by @nilslindemann.docs/de/docs/deployment/cloud.md. PR #10746 by @nilslindemann.docs/de/docs/advanced/behind-a-proxy.md. PR #10675 by @nilslindemann.docs/de/docs/help-fastapi.md. PR #10455 by @nilslindemann.docs/de/docs/python-types.md. PR #10287 by @nilslindemann.docs/de/docs/tutorial/path-params.md. PR #10290 by @nilslindemann.docs/de/docs/tutorial/handling-errors.md. PR #10379 by @nilslindemann.docs/de/docs/index.md. PR #10283 by @nilslindemann.docs/de/docs/advanced/security/http-basic-auth.md. PR #10651 by @nilslindemann.docs/de/docs/tutorial/bigger-applications.md. PR #10554 by @nilslindemann.docs/de/docs/advanced/path-operation-advanced-configuration.md. PR #10612 by @nilslindemann.docs/de/docs/tutorial/static-files.md. PR #10584 by @nilslindemann.docs/de/docs/tutorial/security/oauth2-jwt.md. PR #10522 by @nilslindemann.docs/de/docs/tutorial/response-model.md. PR #10345 by @nilslindemann.docs/de/docs/tutorial/extra-models.md. PR #10351 by @nilslindemann.docs/de/docs/tutorial/body-updates.md. PR #10396 by @nilslindemann.docs/de/docs/alternatives.md. PR #10855 by @nilslindemann.docs/de/docs/advanced/templates.md. PR #10678 by @nilslindemann.docs/de/docs/advanced/security/oauth2-scopes.md. PR #10643 by @nilslindemann.docs/de/docs/advanced/async-tests.md. PR #10708 by @nilslindemann.docs/de/docs/tutorial/metadata.md. PR #10581 by @nilslindemann.docs/de/docs/tutorial/testing.md. PR #10586 by @nilslindemann.docs/de/docs/tutorial/schema-extra-example.md. PR #10597 by @nilslindemann.docs/de/docs/advanced/index.md. PR #10611 by @nilslindemann.docs/de/docs/advanced/response-directly.md. PR #10618 by @nilslindemann.docs/de/docs/advanced/additional-responses.md. PR #10626 by @nilslindemann.docs/de/docs/advanced/response-cookies.md. PR #10627 by @nilslindemann.docs/de/docs/advanced/response-headers.md. PR #10628 by @nilslindemann.docs/de/docs/advanced/response-change-status-code.md. PR #10632 by @nilslindemann.docs/de/docs/advanced/advanced-dependencies.md. PR #10633 by @nilslindemann.docs/de/docs/advanced/security/index.md. PR #10635 by @nilslindemann.docs/de/docs/advanced/using-request-directly.md. PR #10653 by @nilslindemann.docs/de/docs/advanced/dataclasses.md. PR #10667 by @nilslindemann.docs/de/docs/advanced/middleware.md. PR #10668 by @nilslindemann.docs/de/docs/advanced/sub-applications.md. PR #10671 by @nilslindemann.docs/de/docs/advanced/websockets.md. PR #10687 by @nilslindemann.docs/de/docs/advanced/testing-websockets.md. PR #10703 by @nilslindemann.docs/de/docs/advanced/testing-events.md. PR #10704 by @nilslindemann.docs/de/docs/advanced/testing-dependencies.md. PR #10706 by @nilslindemann.docs/de/docs/advanced/openapi-callbacks.md. PR #10710 by @nilslindemann.docs/de/docs/advanced/settings.md. PR #10709 by @nilslindemann.docs/de/docs/advanced/wsgi.md. PR #10713 by @nilslindemann.docs/de/docs/deployment/index.md. PR #10733 by @nilslindemann.docs/de/docs/deployment/https.md. PR #10737 by @nilslindemann.docs/de/docs/deployment/manually.md. PR #10738 by @nilslindemann.docs/de/docs/deployment/concepts.md. PR #10744 by @nilslindemann.docs/de/docs/features.md. PR #10284 by @nilslindemann.docs/de/docs/deployment/server-workers.md. PR #10747 by @nilslindemann.docs/de/docs/deployment/docker.md. PR #10759 by @nilslindemann.docs/de/docs/how-to/index.md. PR #10769 by @nilslindemann.docs/de/docs/how-to/general.md. PR #10770 by @nilslindemann.docs/de/docs/how-to/graphql.md. PR #10788 by @nilslindemann.docs/de/docs/how-to/custom-request-and-route.md. PR #10789 by @nilslindemann.docs/de/docs/how-to/conditional-openapi.md. PR #10790 by @nilslindemann.docs/de/docs/how-to/separate-openapi-schemas.md. PR #10796 by @nilslindemann.docs/de/docs/how-to/configure-swagger-ui.md. PR #10804 by @nilslindemann.docs/de/docs/how-to/custom-docs-ui-assets.md. PR #10803 by @nilslindemann.docs/de/docs/reference/parameters.md. PR #10814 by @nilslindemann.docs/de/docs/reference/status.md. PR #10815 by @nilslindemann.docs/de/docs/reference/uploadfile.md. PR #10816 by @nilslindemann.docs/de/docs/reference/exceptions.md. PR #10817 by @nilslindemann.docs/de/docs/reference/dependencies.md. PR #10818 by @nilslindemann.docs/de/docs/reference/apirouter.md. PR #10819 by @nilslindemann.docs/de/docs/reference/websockets.md. PR #10822 by @nilslindemann.docs/de/docs/reference/httpconnection.md. PR #10823 by @nilslindemann.docs/de/docs/reference/response.md. PR #10824 by @nilslindemann.docs/de/docs/reference/middleware.md. PR #10837 by @nilslindemann.docs/de/docs/reference/openapi/*.md. PR #10838 by @nilslindemann.docs/de/docs/reference/security/index.md. PR #10839 by @nilslindemann.docs/de/docs/reference/staticfiles.md. PR #10841 by @nilslindemann.docs/de/docs/reference/testclient.md. PR #10843 by @nilslindemann.docs/de/docs/project-generation.md. PR #10851 by @nilslindemann.docs/de/docs/history-design-future.md. PR #10865 by @nilslindemann.docs/de/docs/tutorial/dependencies/dependencies-with-yield.md. PR #10422 by @nilslindemann.docs/de/docs/tutorial/dependencies/global-dependencies.md. PR #10420 by @nilslindemann.docs/de/docs/fastapi-people.md. PR #10285 by @nilslindemann.docs/de/docs/tutorial/dependencies/sub-dependencies.md. PR #10409 by @nilslindemann.docs/de/docs/tutorial/security/index.md. PR #10429 by @nilslindemann.docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md. PR #10411 by @nilslindemann.docs/de/docs/tutorial/extra-data-types.md. PR #10534 by @nilslindemann.docs/de/docs/tutorial/security/simple-oauth2.md. PR #10504 by @nilslindemann.docs/de/docs/tutorial/security/get-current-user.md. PR #10439 by @nilslindemann.docs/de/docs/tutorial/request-forms-and-files.md. PR #10368 by @nilslindemann.docs/de/docs/tutorial/encoder.md. PR #10385 by @nilslindemann.docs/de/docs/tutorial/request-forms.md. PR #10361 by @nilslindemann.docs/de/docs/deployment/versions.md. PR #10491 by @nilslindemann.docs/de/docs/async.md. PR #10449 by @nilslindemann.docs/de/docs/tutorial/cookie-params.md. PR #10323 by @nilslindemann.docs/de/docs/tutorial/dependencies/classes-as-dependencies.md. PR #10407 by @nilslindemann.docs/de/docs/tutorial/dependencies/index.md. PR #10399 by @nilslindemann.docs/de/docs/tutorial/header-params.md. PR #10326 by @nilslindemann.docs/de/docs/tutorial/path-params-numeric-validations.md. PR #10307 by @nilslindemann.docs/de/docs/tutorial/query-params-str-validations.md. PR #10304 by @nilslindemann.docs/de/docs/tutorial/request-files.md. PR #10364 by @nilslindemann.docs/pt/docs/advanced/templates.md. PR #11338 by @SamuelBFavarin.docs/bn/docs/learn/index.md. PR #11337 by @imtiaz101325.docs/ko/docs/index.md. PR #11296 by @choi-haram.docs/ko/docs/about/index.md. PR #11299 by @choi-haram.docs/ko/docs/advanced/index.md. PR #9613 by @ElliottLarsen.docs/de/docs/how-to/extending-openapi.md. PR #10794 by @nilslindemann.docs/zh/docs/tutorial/metadata.md. PR #11286 by @jackleeio.docs/zh/docs/contributing.md. PR #10887 by @Aruelius.docs/az/docs/fastapi-people.md. PR #11195 by @vusallyv.docs/ru/docs/tutorial/dependencies/index.md. PR #11223 by @kohiry.docs/zh/docs/tutorial/query-params.md. PR #11242 by @jackleeio.docs/az/learn/index.md. PR #11192 by @vusallyv.yield and except to require raising again as in regular Python. PR #11191 by @tiangolo.
yield, used except in those dependencies, and didn't raise again.yield and except.In short, if you had dependencies that looked like:
def my_dep():
try:
yield
except SomeException:
pass
Now you need to make sure you raise again after except, just as you would in regular Python:
def my_dep():
try:
yield
except SomeException:
raise
docs/ko/docs/. PR #11126 by @KaniKim.fastapi/applications.py. PR #11099 by @JacobHayes.docs/de/docs/reference/background.md. PR #10820 by @nilslindemann.docs/de/docs/reference/templating.md. PR #10842 by @nilslindemann.docs/de/docs/external-links.md. PR #10852 by @nilslindemann.docs/tr/docs/tutorial/query-params.md. PR #11162 by @hasansezertasan.docs/de/docs/reference/encoders.md. PR #10840 by @nilslindemann.docs/de/docs/reference/responses.md. PR #10825 by @nilslindemann.docs/de/docs/reference/request.md. PR #10821 by @nilslindemann.docs/tr/docs/tutorial/query-params.md. PR #11078 by @emrhnsyts.docs/de/docs/reference/fastapi.md. PR #10813 by @nilslindemann.docs/de/docs/newsletter.md. PR #10853 by @nilslindemann.docs/zh-hant/docs/learn/index.md. PR #11142 by @hsuanchi./docs/ko/docs/tutorial/dependencies/global-dependencies.md. PR #11123 by @riroan./docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md. PR #11124 by @riroan./docs/ko/docs/tutorial/schema-extra-example.md. PR #11121 by @KaniKim./docs/ko/docs/tutorial/body-fields.md. PR #11112 by @KaniKim./docs/ko/docs/tutorial/cookie-params.md. PR #11118 by @riroan./docs/ko/docs/dependencies/index.md. PR #11114 by @KaniKim./docs/ko/docs/deployment/docker.md. PR #11113 by @KaniKim.docs/tr/docs/tutorial/first-steps.md. PR #11094 by @hasansezertasan.docs/es/docs/advanced/security/index.md. PR #2278 by @Xaraxx.docs/es/docs/advanced/response-headers.md. PR #2276 by @Xaraxx.docs/es/docs/deployment/index.md and ~/deployment/versions.md. PR #9669 by @pabloperezmoya.docs/es/docs/benchmarks.md. PR #10928 by @pablocm83.docs/es/docs/advanced/response-change-status-code.md. PR #11100 by @alejsdev.python-multipart to >=0.0.7 to fix a vulnerability when using form data with a ReDos attack. You can also simply upgrade python-multipart.Read more in the advisory: Content-Type Header ReDoS.
fastapi/utils.py. PR #10576 by @eukub.tests/test_tutorial/test_header_params/test_tutorial003.py after fix in Starlette. PR #10904 by @ooknimm.help-fastapi.md. PR #11040 by @tiangolo.fastapi/security/oauth2.py. PR #10972 by @RafalSkolasinski.HTTPException details in docs/en/docs/tutorial/handling-errors.md. PR #5418 by @papb.docs/de/docs/tutorial/first-steps.md. PR #10959 by @nilslindemann.docs/en/docs/advanced/async-tests.md. PR #10960 by @nilslindemann.docs/tutorial/sql-databases.md in several languages. PR #10716 by @theoohoho.external_links.yml. PR #10943 by @Torabek.url_for. PR #5937 by @EzzEddin.docs/en/docs/tutorial/bigger-applications.md. PR #5490 by @papb.docs/en/docs/tutorial/static-files.md. PR #10243 by @hungtsetse.en/docs/contributing.md. PR #10480 by @nilslindemann.tutorial/bigger-applications.md. PR #10552 by @nilslindemann.docs/en/docs/advanced/path-operation-advanced-configuration.md. PR #10826 by @ahmedabdou14.docs/es/docs/external-links.md. PR #10933 by @pablocm83.docs/ko/docs/tutorial/first-steps.md, docs/ko/docs/tutorial/index.md, docs/ko/docs/tutorial/path-params.md, and docs/ko/docs/tutorial/query-params.md. PR #4218 by @SnowSuno.docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md. PR #10870 by @zhiquanchi.docs/zh/docs/deployment/concepts.md. PR #10282 by @xzmeng.docs/az/docs/index.md. PR #11047 by @aykhans.docs/ko/docs/tutorial/middleware.md. PR #2829 by @JeongHyeongKim.docs/de/docs/tutorial/body-nested-models.md. PR #10313 by @nilslindemann.docs/fa/docs/tutorial/middleware.md. PR #9695 by @mojtabapaso.docs/fa/docs/index.md. PR #10216 by @theonlykingpin.docs/de/docs/tutorial/body-fields.md. PR #10310 by @nilslindemann.docs/de/docs/tutorial/body.md. PR #10295 by @nilslindemann.docs/de/docs/tutorial/body-multiple-params.md. PR #10308 by @nilslindemann.docs/ja/docs/tutorial/security/get-current-user.md. PR #2681 by @sh0nk.docs/zh/docs/advanced/advanced-dependencies.md. PR #3798 by @jaystone776.docs/zh/docs/advanced/events.md. PR #3815 by @jaystone776.docs/zh/docs/advanced/behind-a-proxy.md. PR #3820 by @jaystone776.docs/zh/docs/advanced/testing-events.md. PR #3818 by @jaystone776.docs/zh/docs/advanced/testing-websockets.md. PR #3817 by @jaystone776.docs/zh/docs/advanced/testing-database.md. PR #3821 by @jaystone776.docs/zh/docs/deployment/deta.md. PR #3837 by @jaystone776.docs/zh/docs/history-design-future.md. PR #3832 by @jaystone776.docs/zh/docs/project-generation.md. PR #3831 by @jaystone776.docs/zh/docs/deployment/docker.md. PR #10296 by @xzmeng.docs/es/docs/features.md. PR #10884 by @pablocm83.docs/es/docs/newsletter.md. PR #10922 by @pablocm83.docs/ko/docs/tutorial/background-tasks.md. PR #5910 by @junah201.docs/tr/docs/alternatives.md. PR #10502 by @alperiox.docs/ko/docs/tutorial/dependencies/index.md. PR #10989 by @KaniKim./docs/ko/docs/tutorial/body.md. PR #11000 by @KaniKim.docs/pt/docs/tutorial/schema-extra-example.md. PR #4065 by @luccasmmg.docs/tr/docs/history-design-future.md. PR #11012 by @hasansezertasan.docs/tr/docs/resources/index.md. PR #11020 by @hasansezertasan.docs/tr/docs/how-to/index.md. PR #11021 by @hasansezertasan.docs/de/docs/tutorial/query-params.md. PR #10293 by @nilslindemann.docs/de/docs/benchmarks.md. PR #10866 by @nilslindemann.docs/tr/docs/learn/index.md. PR #11014 by @hasansezertasan.docs/fa/docs/tutorial/security/index.md. PR #9945 by @mojtabapaso.docs/tr/docs/help/index.md. PR #11013 by @hasansezertasan.docs/tr/docs/about/index.md. PR #11006 by @hasansezertasan.docs/tr/docs/benchmarks.md. PR #11005 by @hasansezertasan.docs/it/docs/index.md. PR #5233 by @matteospanio.docs/ko/docs/help/index.md. PR #10983 by @KaniKim.docs/ko/docs/features.md. PR #10976 by @KaniKim.docs/ko/docs/tutorial/security/get-current-user.md. PR #5737 by @KdHyeon0661.docs/ru/docs/tutorial/security/first-steps.md. PR #10541 by @AlertRED.docs/ru/docs/tutorial/handling-errors.md. PR #10375 by @AlertRED.docs/ru/docs/tutorial/encoder.md. PR #10374 by @AlertRED.docs/ru/docs/tutorial/body-updates.md. PR #10373 by @AlertRED.fastapi-people.md.. PR #10255 by @NiKuma0.docs/ja/docs/tutorial/security/index.md. PR #5798 by @3w36zj6.docs/de/docs/advanced/generate-clients.md. PR #10725 by @nilslindemann.docs/de/docs/advanced/openapi-webhooks.md. PR #10712 by @nilslindemann.docs/de/docs/advanced/custom-response.md. PR #10624 by @nilslindemann.docs/de/docs/advanced/additional-status-codes.md. PR #10617 by @nilslindemann.docs/de/docs/tutorial/middleware.md. PR #10391 by @JohannesJungbluth.docs/ja/docs/tutorial/encoder.md. PR #1955 by @SwftAlpc.docs/ja/docs/tutorial/extra-data-types.md. PR #1932 by @SwftAlpc.docs/tr/docs/async.md. PR #5191 by @BilalAlpaslan.docs/tr/docs/project-generation.md. PR #5192 by @BilalAlpaslan.docs/ko/docs/deployment/docker.md. PR #5657 by @nearnear.docs/ko/docs/deployment/server-workers.md. PR #4935 by @jujumilk3.docs/ko/docs/deployment/index.md. PR #4561 by @jujumilk3.docs/ko/docs/tutorial/path-operation-configuration.md. PR #3639 by @jungsu-kwon.zh - Traditional Chinese. PR #10889 by @cherinyy.docs/ko/docs/tutorial/static-files.md. PR #2957 by @jeesang7.docs/ko/docs/tutorial/response-model.md. PR #2766 by @hard-coders.docs/ko/docs/tutorial/body-multiple-params.md. PR #2461 by @PandaHun.docs/ko/docs/tutorial/query-params-str-validations.md. PR #2415 by @hard-coders.docs/ko/docs/python-types.md. PR #2267 by @jrim.docs/ko/docs/tutorial/body-nested-models.md. PR #2506 by @hard-coders.docs/ko/docs/learn/index.md. PR #10977 by @KaniKim.docs/de/docs/tutorial/index.md. PR #10962 by @nilslindemann.docs/ko/docs/tutorial/path-params.md. PR #10758 by @2chanhaeng.docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md. PR #1961 by @SwftAlpc.docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md. PR #1960 by @SwftAlpc.docs/ja/docs/tutorial/dependencies/sub-dependencies.md. PR #1959 by @SwftAlpc.docs/ja/docs/tutorial/background-tasks.md. PR #2668 by @tokusumi.docs/ja/docs/tutorial/dependencies/index.md and docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md. PR #1958 by @SwftAlpc.docs/ja/docs/tutorial/response-model.md. PR #1938 by @SwftAlpc.docs/ja/docs/tutorial/body-multiple-params.md. PR #1903 by @SwftAlpc.docs/ja/docs/tutorial/path-params-numeric-validations.md. PR #1902 by @SwftAlpc.docs/ja/docs/python-types.md. PR #1899 by @SwftAlpc.docs/ja/docs/tutorial/handling-errors.md. PR #1953 by @SwftAlpc.docs/ja/docs/tutorial/response-status-code.md. PR #1942 by @SwftAlpc.docs/ja/docs/tutorial/extra-models.md. PR #1941 by @SwftAlpc.docs/ja/docs/tutorial/schema-extra-example.md. PR #1931 by @SwftAlpc.docs/ja/docs/tutorial/body-nested-models.md. PR #1930 by @SwftAlpc.docs/ja/docs/tutorial/body-fields.md. PR #1923 by @SwftAlpc.docs/de/docs/tutorial/index.md. PR #9502 by @fhabers21.docs/de/docs/tutorial/background-tasks.md. PR #10566 by @nilslindemann.docs/ru/docs/index.md. PR #10672 by @Delitel-WEB.docs/zh/docs/tutorial/extra-data-types.md. PR #10727 by @HiemalBeryl.docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md. PR #10410 by @AlertRED.mkdocs.yml. PR #11016 by @alejsdev.mkdocs.yml languages in CI, update docs.py. PR #11009 by @tiangolo.label-approved.yml to accept translations with 1 reviewer. PR #11007 by @alejsdev.zh-hant. PR #10950 by @tiangolo.docs/en/docs/alternatives.md. PR #10931 by @s111d.email with username in docs_src/security/tutorial007 code examples. PR #10649 by @nilslindemann..model_dump(). PR #10929 by @tiangolo.docs/en/docs/tutorial/sql-databases.md. PR #10765 by @HurSungYun.docs/en/docs/alternatives.md and docs/en/docs/tutorial/dependencies/index.md. PR #10906 by @s111d.docs/en/docs/tutorial/dependencies/dependencies-with-yield.md. PR #10834 by @Molkree.AsyncClient. PR #4167 by @andrew-chang-dewitt./docs/reference/exceptions.md and /en/docs/reference/status.md. PR #10809 by @clarencepenz.openapi-callbacks.md. PR #10673 by @kayjan.fastapi/routing.py . PR #10520 by @sepsh.create_item with update_item when appropriate. PR #5913 by @OttoAndrey.docs/bn/docs/index.md. PR #9177 by @Fahad-Md-Kamal.index.md in several languages. PR #10711 by @tamago3keran.docs/ru/docs/tutorial/request-forms-and-files.md. PR #10347 by @AlertRED.docs/uk/docs/index.md. PR #10362 by @rostik1410.docs/ko/docs/index.md. PR #10680 by @Eeap.docs/fa/docs/features.md. PR #5887 by @amirilf.docs/zh/docs/advanced/additional-responses.md. PR #10325 by @ShuibeiC.docs/ru/docs/tutorial/background-tasks.md, docs/ru/docs/tutorial/body-nested-models.md, docs/ru/docs/tutorial/debugging.md, docs/ru/docs/tutorial/testing.md. PR #10311 by @AlertRED.docs/ru/docs/tutorial/request-files.md. PR #10332 by @AlertRED.docs/zh/docs/deployment/server-workers.md. PR #10292 by @xzmeng.docs/zh/docs/deployment/cloud.md. PR #10291 by @xzmeng.docs/zh/docs/deployment/manually.md. PR #10279 by @xzmeng.docs/zh/docs/deployment/https.md. PR #10277 by @xzmeng.docs/zh/docs/deployment/index.md. PR #10275 by @xzmeng.docs/de/docs/tutorial/first-steps.md. PR #9530 by @fhabers21.docs/tr/docs/index.md. PR #10444 by @hasansezertasan.docs/zh/docs/learn/index.md. PR #10479 by @KAZAMA-DREAM.docs/ru/docs/learn/index.md. PR #10539 by @AlertRED.docs/zh/docs/tutorial/sql-databases.md. PR #9712 by @Royc30ne.docs/tr/docs/external-links.md. PR #10549 by @hasansezertasan.docs/es/docs/learn/index.md. PR #10885 by @pablocm83.docs/uk/docs/tutorial/body-fields.md. PR #10670 by @ArtemKhymenko./docs/hu/docs/index.md. PR #10812 by @takacs.docs/tr/docs/newsletter.md. PR #10550 by @hasansezertasan.docs/es/docs/help/index.md. PR #10907 by @pablocm83.docs/es/docs/about/index.md. PR #10908 by @pablocm83.docs/es/docs/resources/index.md. PR #10909 by @pablocm83.>=0.29.0,<0.33.0, update docs and usage of templates with new Starlette arguments. Remove pin of AnyIO >=3.7.1,<4.0.0, add support for AnyIO 4.x.x. PR #10846 by @tiangolo.Using resources from dependencies with yield in background tasks is no longer supported.
This change is what supports the new features, read below. 🤓
yield, HTTPException and Background TasksDependencies with yield now can raise HTTPException and other exceptions after yield. 🎉
Read the new docs here: Dependencies with yield and HTTPException.
from fastapi import Depends, FastAPI, HTTPException
from typing_extensions import Annotated
app = FastAPI()
data = {
"plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
"portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
}
class OwnerError(Exception):
pass
def get_username():
try:
yield "Rick"
except OwnerError as e:
raise HTTPException(status_code=400, detail=f"Owner error: {e}")
@app.get("/items/{item_id}")
def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
if item_id not in data:
raise HTTPException(status_code=404, detail="Item not found")
item = data[item_id]
if item["owner"] != username:
raise OwnerError(username)
return item
Before FastAPI 0.106.0, raising exceptions after yield was not possible, the exit code in dependencies with yield was executed after the response was sent, so Exception Handlers would have already run.
This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished.
Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0.
Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection).
If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with yield.
For example, instead of using the same database session, you would create a new database session inside of the background task, and you would obtain the objects from the database using this new session. And then instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object and then obtain the object again inside the background task function.
The sequence of execution before FastAPI 0.106.0 was like this diagram:
Time flows from top to bottom. And each column is one of the parts interacting or executing code.
sequenceDiagram
participant client as Client
participant handler as Exception handler
participant dep as Dep with yield
participant operation as Path Operation
participant tasks as Background tasks
Note over client,tasks: Can raise exception for dependency, handled after response is sent
Note over client,operation: Can raise HTTPException and can change the response
client ->> dep: Start request
Note over dep: Run code up to yield
opt raise
dep -->> handler: Raise HTTPException
handler -->> client: HTTP error response
dep -->> dep: Raise other exception
end
dep ->> operation: Run dependency, e.g. DB session
opt raise
operation -->> dep: Raise HTTPException
dep -->> handler: Auto forward exception
handler -->> client: HTTP error response
operation -->> dep: Raise other exception
dep -->> handler: Auto forward exception
end
operation ->> client: Return response to client
Note over client,operation: Response is already sent, can't change it anymore
opt Tasks
operation -->> tasks: Send background tasks
end
opt Raise other exception
tasks -->> dep: Raise other exception
end
Note over dep: After yield
opt Handle other exception
dep -->> dep: Handle exception, can't change response. E.g. close DB session.
end
The new execution flow can be found in the docs: Execution of dependencies with yield.
HTTPException) in dependencies with yield in the exit code, do not support them in background tasks. PR #10831 by @tiangolo.Annotated[str, Field(), Query()]. PR #10773 by @tiangolo.docs/en/docs/tutorial/metadata.md. PR #10433 by @worldworm.docs/en/docs/tutorial/path-params.md. PR #10043 by @giuliowaitforitdavide.docs/en/docs/reference/dependencies.md. PR #10465 by @suravshresth.docs/en/docs/tutorial/body-nested-models.md. PR #10468 by @yogabonito.pydantic.Required in docs/en/docs/tutorial/query-params-str-validations.md. PR #10469 by @yogabonito.docs/en/docs/reference/index.md. PR #10467 by @tarsil.docs/en/docs/async.md and docs/zh/docs/async.md to make them relative. PR #10498 by @hasnatsajid.docs/em/docs/async.md. PR #10507 by @hasnatsajid.docs/em/docs/index.md, Python 3.8. PR #10521 by @kerriop.CITATION.cff file for academic citations. PR #10496 by @tiangolo.BackgroundTasks, refactor docs structure. PR #10392 by @tiangolo. New docs at FastAPI Reference - Code API.docs/uk/docs/tutorial/extra-data-types.md. PR #10132 by @ArtemKhymenko.docs/fr/docs/advanced/path-operation-advanced-configuration.md, docs/fr/docs/alternatives.md, docs/fr/docs/async.md, docs/fr/docs/features.md, docs/fr/docs/help-fastapi.md, docs/fr/docs/index.md, docs/fr/docs/python-types.md, docs/fr/docs/tutorial/body.md, docs/fr/docs/tutorial/first-steps.md, docs/fr/docs/tutorial/query-params.md. PR #10154 by @s-rigaud.docs/zh/docs/async.md. PR #5591 by @mkdir700.docs/tutorial/security/simple-oauth2.md. PR #3844 by @jaystone776.docs/ko/docs/deployment/cloud.md. PR #10191 by @Sion99.docs/ja/docs/deployment/https.md. PR #10298 by @tamtam-fitness.docs/ru/docs/tutorial/body-fields.md. PR #10224 by @AlertRED.docs/pl/docs/help-fastapi.md. PR #10121 by @romabozhanovgithub.docs/ru/docs/tutorial/header-params.md. PR #10226 by @AlertRED.docs/zh/docs/deployment/versions.md. PR #10276 by @xzmeng.regex to pattern. PR #10085 by @pablodorrio.docs/en/docs/deployment/server-workers.md. PR #10066 by @tamtam-fitness.docs/en/docs/tutorial/extra-data-types.md. PR #10155 by @hasnatsajid.docs/en/docs/tutorial/handling-errors.md. PR #10170 by @poupapaa.docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md. PR #10172 by @ragul-kachiappan.docs/pt/docs/tutorial/path-params.md. PR #10126 by @LecoOliveira.docs/yo/docs/index.md. PR #10033 by @AfolabiOlaoluwa.docs/uk/docs/python-types.md. PR #10080 by @rostik1410.docs/vi/docs/tutorial/first-steps.md and docs/vi/docs/tutorial/index.md. PR #10088 by @magiskboy.docs/uk/docs/alternatives.md. PR #10060 by @whysage.docs/uk/docs/tutorial/index.md. PR #10079 by @rostik1410.docs/en/docs/how-to/separate-openapi-schemas.md and docs/en/docs/tutorial/schema-extra-example.md. PR #10189 by @xzmeng.docs/zh/docs/advanced/generate-clients.md. PR #9883 by @funny-cat-happy.fastapi/applications.py. PR #10045 by @AhsanSheraz.openapi_examples in all FastAPI parameters. PR #10152 by @tiangolo.
separate_input_output_schemas=False. PR #10145 by @tiangolo.
ResponseValidationError printable details, to show up in server error logs. PR #10078 by @tiangolo.fastapi/params.py. PR #9854 by @russbiggs.fastapi/concurrency.py and fastapi/routing.py. PR #9590 by @ElliottLarsen.docs/en/docs/contributing.md. PR #9878 by @VicenteMerino.docs/en/docs/tutorial/bigger-applications.md. PR #9806 by @theonlykingpin.docs/ja/docs/deployment/concepts.md. PR #10062 by @tamtam-fitness.docs/ja/docs/deployment/server-workers.md. PR #10064 by @tamtam-fitness.docs/ja/docs/deployment/docker.md. PR #10073 by @tamtam-fitness.docs/uk/docs/fastapi-people.md. PR #10059 by @rostik1410.docs/uk/docs/tutorial/cookie-params.md. PR #10032 by @rostik1410.docs/ru/docs/deployment/docker.md. PR #9971 by @Xewus.docs/vi/docs/python-types.md. PR #10047 by @magiskboy.docs/ru/docs/tutorial/dependencies/global-dependencies.md. PR #9970 by @dudyaosuplayer.docs/ur/docs/benchmarks.md. PR #9974 by @AhsanSheraz.computed_field, better OpenAPI for response models, proper required attributes, better generated clients. PR #10011 by @tiangolo.jsonable_encoder. PR #9840 by @iudeen.docs/ru/docs/tutorial/security/index.md. PR #9963 by @eVery1337.MultHostUrl to AnyUrl for compatibility with older versions of Pydantic v1. PR #9852 by @Kludex.docs/uk/docs/tutorial/body.md. PR #4574 by @ss-o-furda.docs/vi/docs/features.md and docs/vi/docs/index.md. PR #3006 by @magiskboy.docs/ko/docs/async.md. PR #4179 by @NinaHwang.docs/zh/docs/tutorial/background-tasks.md. PR #9812 by @wdh99.docs/fr/docs/tutorial/query-params-str-validations.md. PR #4075 by @Smlep.docs/fr/docs/tutorial/index.md. PR #2234 by @JulianMaurin.docs/fr/docs/contributing.md. PR #2132 by @JulianMaurin.docs/fr/docs/benchmarks.md. PR #2155 by @clemsau.docs/ru/docs/tutorial/request-forms.md. PR #9841 by @dedkot01.docs/zh/docs/tutorial/handling-errors.md. PR #9485 by @Creat55.✨ Support for Pydantic v2 ✨
Pydantic version 2 has the core re-written in Rust and includes a lot of improvements and features, for example:
...all this while keeping the same Python API. In most of the cases, for simple models, you can simply upgrade the Pydantic version and get all the benefits. 🚀
In some cases, for pure data validation and processing, you can get performance improvements of 20x or more. This means 2,000% or more. 🤯
When you use FastAPI, there's a lot more going on, processing the request and response, handling dependencies, executing your own code, and particularly, waiting for the network. But you will probably still get some nice performance improvements just from the upgrade.
The focus of this release is compatibility with Pydantic v1 and v2, to make sure your current apps keep working. Later there will be more focus on refactors, correctness, code improvements, and then performance improvements. Some third-party early beta testers that ran benchmarks on the beta releases of FastAPI reported improvements of 2x - 3x. Which is not bad for just doing pip install --upgrade fastapi pydantic. This was not an official benchmark and I didn't check it myself, but it's a good sign.
Check out the Pydantic migration guide.
For the things that need changes in your Pydantic models, the Pydantic team built bump-pydantic.
A command line tool that will process your code and update most of the things automatically for you. Make sure you have your code in git first, and review each of the changes to make sure everything is correct before committing the changes.
This version of FastAPI still supports Pydantic v1. And although Pydantic v1 will be deprecated at some point, it will still be supported for a while.
This means that you can install the new Pydantic v2, and if something fails, you can install Pydantic v1 while you fix any problems you might have, but having the latest FastAPI.
There are tests for both Pydantic v1 and v2, and test coverage is kept at 100%.
There are new parameter fields supported by Pydantic Field() for:
Path()Query()Header()Cookie()Body()Form()File()The new parameter fields are:
default_factoryalias_priorityvalidation_aliasserialization_aliasdiscriminatorstrictmultiple_ofallow_inf_nanmax_digitsdecimal_placesjson_schema_extra...you can read about them in the Pydantic docs.
The parameter regex has been deprecated and replaced by pattern.
New Pydantic models use an improved and simplified attribute model_config that takes a simple dict instead of an internal class Config for their configuration.
The attribute schema_extra for the internal class Config has been replaced by the key json_schema_extra in the new model_config dict.
When you install "fastapi[all]" it now also includes:
pydantic-settings - for settings management.pydantic-extra-types - for extra types to be used with Pydantic.Now Pydantic Settings is an additional optional package (included in "fastapi[all]"). To use settings you should now import from pydantic_settings import BaseSettings instead of importing from pydantic directly.
PR #9816 by @tiangolo, included all the work done (in multiple PRs) on the beta branch (main-pv2).
additionalProperties: false. PR #9781 by @tiangolo.✨ Add support for OpenAPI 3.1.0. PR #9770 by @tiangolo.
examples field in Query(), Cookie(), Body(), etc. based on the latest JSON Schema and OpenAPI. Now it takes a list of examples and they are included directly in the JSON Schema, not outside. Read more about it (including the historical technical details) in the updated docs: Tutorial: Declare Request Example Data.✨ Add support for deque objects and children in jsonable_encoder. PR #9433 by @cranium.
docs/fa/docs/advanced/sub-applications.md. PR #9692 by @mojtabapaso.docs/ru/docs/tutorial/response-model.md. PR #9675 by @glsglsgls.docs/en/docs/tutorial/debugging.md. PR #9581 by @ivan-abc.docs/en/docs/tutorial/security/index.md. PR #9561 by @jyothish-mohan.Annotated notes in docs/en/docs/tutorial/schema-extra-example.md. PR #9620 by @Alexandrhub.Annotation -> Annotated in docs/en/docs/tutorial/query-params-str-validations.md. PR #9625 by @mccricardo.docs/ru/docs/tutorial/metadata.md. PR #9681 by @TabarakoAkula.docs/es/docs/tutorial/first-steps.md. PR #9571 by @lilidl-nft.docs/tutorial/path-operation-configuration.md. PR #9696 by @TabarakoAkula.docs/zh/docs/advanced/security/index.md. PR #9666 by @lordqyxz.docs/zh/docs/advanced/settings.md. PR #9652 by @ChoyeonChern.docs/zh/docs/advanced/websockets.md. PR #9651 by @ChoyeonChern.docs/zh/docs/tutorial/testing.md. PR #9641 by @wdh99.docs/tutorial/extra-models.md. PR #9619 by @ivan-abc.docs/tutorial/cors.md. PR #9608 by @ivan-abc.docs/pl/docs/features.md. PR #5348 by @mbroton.docs/ru/docs/tutorial/body-nested-models.md. PR #9605 by @Alexandrhub.dependencies in WebSocket routes. PR #4534 by @paulo-raca.WebSocketRequestValidationError (which also allows to override it). PR #6030 by @kristjanvalur.AsyncExitStackMiddleware as without Python 3.6 AsyncExitStack is always available. PR #9657 by @tiangolo.HTTPException header type annotations. PR #9648 by @tiangolo.gte to ge. PR #9635 by @tiangolo.media_type from ORJSONResponse as it's inherited from the parent class. PR #5805 by @Kludex.HTTPException only when needed, optimization refactor. PR #5356 by @pawamoy.docs/id/docs/tutorial/index.md. PR #5635 by @purwowd.docs/ru/docs/tutorial/index.md. PR #5896 by @Wilidon.docs/zh/docs/advanced/response-change-status-code.md and docs/zh/docs/advanced/response-headers.md. PR #9544 by @ChoyeonChern.docs/ru/docs/tutorial/schema-extra-example.md. PR #9621 by @Alexandrhub.create_cloned_field to use a global cache and improve startup performance. PR #4645 by @madkinsz and previous original PR by @huonw.docs/tutorial/body.md. PR #3885 by @solomein-sv.docs/ru/docs/tutorial/static-files.md. PR #9580 by @Alexandrhub.docs/ru/docs/tutorial/query-params.md. PR #9584 by @Alexandrhub.docs/ru/docs/tutorial/first-steps.md. PR #9471 by @AGolicyn.docs/ru/docs/tutorial/debugging.md. PR #9579 by @Alexandrhub.docs/ru/docs/tutorial/path-params.md. PR #9519 by @AGolicyn.docs/zh/docs/tutorial/static-files.md. PR #9436 by @wdh99.docs/es/docs/async.md. PR #9483 by @andresbermeoq.docs/ru/docs/tutorial/path-params-numeric-validations.md. PR #9563 by @ivan-abc.docs/ru/docs/deployment/concepts.md. PR #9577 by @Xewus.docs/ru/docs/tutorial/body-multiple-params.md. PR #9586 by @Alexandrhub.>=0.27.0 for a security release. PR #9541 by @tiangolo. Details on Starlette's security advisory.docs/pt/docs/advanced/events.md. PR #9326 by @oandersonmagalhaes.docs/ru/docs/deployment/manually.md. PR #9417 by @Xewus.docs/ru/docs/tutorial/testing.md. PR #9403 by @Xewus.docs/ru/docs/deployment/https.md. PR #9428 by @Xewus.docs/fr/docs/advanced/response-directly.md. PR #9415 by @axel584.docs/pt/docs/index.md. PR #9337 by @lucasbalieiro.docs/ru/docs/tutorial/response-status-code.md. PR #9370 by @nadia3373.flask.escape warning for internal tests. PR #9468 by @samuelcolvin.Annotated in routers or path operations decorated multiple times. PR #9315 by @sharonyogev.Annotated. PR #9298 by @grdworkin.docs/en/docs/advanced/behind-a-proxy.md. PR #5681 by @Leommjr.docs/fa/docs/index.md. PR #6083 by @Kimiaattaei.docs/en/docs/help-fastapi.md. PR #9249 by @armgabrielyan.docs/en/docs/tutorial/query-params-str-validations.md. PR #9272 by @nicornk.docs/en/docs/tutorial/query-params-str-validations.md. PR #9273 by @tim-habitat.docs/en/docs/tutorial/path-params-numeric-validations.md. PR #9282 by @aadarsh977.docs/en/docs/tutorial/query-params-str-validations.md. PR #9380 by @dasstyxx.docs/fr/docs/advanced/index.md. PR #5673 by @axel584.docs/pt/docs/tutorial/body-nested-models.md. PR #4053 by @luccasmmg.docs/ru/docs/alternatives.md. PR #5994 by @Xewus.docs/pt/docs/tutorial/extra-models.md. PR #5912 by @LorhanSohaky.docs/pt/docs/tutorial/path-operation-configuration.md. PR #5936 by @LorhanSohaky.docs/ru/docs/contributing.md. PR #6002 by @stigsanek.docs/tutorial/dependencies/classes-as-dependencies.md. PR #9176 by @sehwan505.docs/ru/docs/project-generation.md. PR #9243 by @Xewus.docs/fr/docs/index.md. PR #9265 by @frabc.docs/ru/docs/tutorial/query-params-str-validations.md. PR #9267 by @dedkot01.docs/ru/docs/benchmarks.md. PR #9271 by @Xewus.This release adds support for dependencies and parameters using Annotated and recommends its usage. ✨
This has several benefits, one of the main ones is that now the parameters of your functions with Annotated would not be affected at all.
If you call those functions in other places in your code, the actual default values will be kept, your editor will help you notice missing required arguments, Python will require you to pass required arguments at runtime, you will be able to use the same functions for different things and with different libraries (e.g. Typer will soon support Annotated too, then you could use the same function for an API and a CLI), etc.
Because Annotated is standard Python, you still get all the benefits from editors and tools, like autocompletion, inline errors, etc.
One of the biggest benefits is that now you can create Annotated dependencies that are then shared by multiple path operation functions, this will allow you to reduce a lot of code duplication in your codebase, while keeping all the support from editors and tools.
For example, you could have code like this:
def get_current_user(token: str):
# authenticate user
return User()
@app.get("/items/")
def read_items(user: User = Depends(get_current_user)):
...
@app.post("/items/")
def create_item(*, user: User = Depends(get_current_user), item: Item):
...
@app.get("/items/{item_id}")
def read_item(*, user: User = Depends(get_current_user), item_id: int):
...
@app.delete("/items/{item_id}")
def delete_item(*, user: User = Depends(get_current_user), item_id: int):
...
There's a bit of code duplication for the dependency:
user: User = Depends(get_current_user)
...the bigger the codebase, the more noticeable it is.
Now you can create an annotated dependency once, like this:
CurrentUser = Annotated[User, Depends(get_current_user)]
And then you can reuse this Annotated dependency:
CurrentUser = Annotated[User, Depends(get_current_user)]
@app.get("/items/")
def read_items(user: CurrentUser):
...
@app.post("/items/")
def create_item(user: CurrentUser, item: Item):
...
@app.get("/items/{item_id}")
def read_item(user: CurrentUser, item_id: int):
...
@app.delete("/items/{item_id}")
def delete_item(user: CurrentUser, item_id: int):
...
...and CurrentUser has all the typing information as User, so your editor will work as expected (autocompletion and everything), and FastAPI will be able to understand the dependency defined in Annotated. 😎
Roughly all the docs have been rewritten to use Annotated as the main way to declare parameters and dependencies. All the examples in the docs now include a version with Annotated and a version without it, for each of the specific Python versions (when there are small differences/improvements in more recent versions). There were around 23K new lines added between docs, examples, and tests. 🚀
The key updated docs are:
Special thanks to @nzig for the core implementation and to @adriangb for the inspiration and idea with Xpresso! 🚀
Annotated in docs. PR #9270 by @tiangolo.Annotated as the main recommendation, with new examples and tests. PR #9268 by @tiangolo.lifespan with state. PR #9239 by @tiangolo.pydantic to PyPI classifiers. PR #5914 by @yezz123.lifespan async context managers (superseding startup and shutdown events). Initial PR #2944 by @uSpike.Now, instead of using independent startup and shutdown events, you can define that logic in a single function with yield decorated with @asynccontextmanager (an async context manager).
For example:
from contextlib import asynccontextmanager
from fastapi import FastAPI
def fake_answer_to_everything_ml_model(x: float):
return x * 42
ml_models = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load the ML model
ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model
yield
# Clean up the ML models and release the resources
ml_models.clear()
app = FastAPI(lifespan=lifespan)
@app.get("/predict")
async def predict(x: float):
result = ml_models["answer_to_everything"](x)
return {"result": result}
Note: This is the recommended way going forward, instead of using startup and shutdown events.
Read more about it in the new docs: Advanced User Guide: Lifespan Events.
docs/fr/docs/advanced/path-operation-advanced-configuration.md. PR #9221 by @axel584.docs/tutorial/debugging.md. PR #9175 by @frabc.deployment/manually.md. PR #3693 by @rjNemo.🚨 This is a security fix. Please upgrade as soon as possible.
0.24.0 and refactor internals for compatibility. PR #5985 by @tiangolo.
0.24.0, a new instance of each middleware class would be created when a new middleware was added. That normally was not a problem, unless the middleware class expected to be created only once, with only one instance, that happened in some cases. This upgrade would solve those cases (thanks @adriangb! Starlette PR #2017). Now the middleware class instances are created once, right before the first request (the first time the app is called).docs/en/docs/project-generation.md. PR #5930 by @chandra-deb.zip-docs.sh internal script, remove extra space. PR #5931 by @JuanPerdomo00.docs/ru/docs/tutorial/body-fields.md. PR #5898 by @simatheone.docs/ru/docs/help-fastapi.md. PR #5970 by @tiangolo.docs/pt/docs/tutorial/static-files.md. PR #5858 by @batlopes.docs/pt/docs/tutorial/encoder.md. PR #5525 by @felipebpl.docs/ru/docs/contributing.md. PR #5870 by @Xewus.docs/tr/docs/tutorial/first_steps.md. PR #5691 by @Kadermiyanyedi.response_model. Initial PR #1436 by @uriyyo.Now you can declare the return type / response_model in the function return type annotation:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.get("/items/")
async def read_items() -> list[Item]:
return [
Item(name="Portal Gun", price=42.0),
Item(name="Plumbus", price=32.0),
]
FastAPI will use the return type annotation to perform:
Before this version it was only supported via the response_model parameter.
Read more about it in the new docs: Response Model - Return Type.
docs/en/docs/async.md. PR #5785 by @Kingdageek.docs/en/docs/deployment/concepts.md. PR #5824 by @kelbyfaessler.docs/ru/docs/fastapi-people.md. PR #5577 by @Xewus.docs/zh/docs/benchmarks.md. PR #4269 by @15027668g.docs/tutorial/cors.md. PR #3764 by @NinaHwang.0.22.0 to fix bad encoding for query parameters in new TestClient. PR #5659 by @azogue.docs/en/docs/advanced/middleware.md. PR #5376 by @rifatrakib.setup-python action in tests to use new caching feature. PR #5680 by @madkinsz.Highlights of this release:
TestClient is based on HTTPX instead of Requests. 🚀TestClient usage, but @Kludex built bump-testclient to help you automatize migrating your tests. Make sure you are using Git and that you can undo any unnecessary changes (false positive changes, etc) before using bump-testclient.all (including new Uvicorn version), when you install "fastapi[all]".WebSocketException and add it to docs. PR #5629 by @tiangolo.0.21.0, including the new TestClient based on HTTPX. PR #5471 by @pawelrubin.docs/tutorial/query-params.md. PR #2969 by @ftnext.docs/fr/docs/advanced/additional-status-code.md. PR #5477 by @axel584.docs/pt/docs/tutorial/request-forms-and-files.md. PR #5579 by @batlopes.docs/ja/docs/advanced/websockets.md. PR #4983 by @xryuseix.docs/en/docs/tutorial/security/oauth2-jwt.md. PR #5584 by @vivekashok1221.docs/zh/docs/python-types.md. PR #5416 by @supercaizehua.docs/ru/docs/deployment/index.md. PR #5336 by @Xewus.docs/tutorial/security/oauth2-jwt.md. PR #3846 by @jaystone776.test_starlette_exception.py. PR #5379 by @iudeen.docs/en/docs/async.md. PR #5432 by @pamelafox.alternatives.md. PR #5455 by @su-shubham.pip in Zsh. PR #5523 by @zhangbo2012.docs/pt/docs/tutorial/request-forms.md. PR #4934 by @batlopes.docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md. PR #4971 by @Zssaer.deployment/deta.md. PR #3692 by @rjNemo.docs/zh/docs/tutorial/query-params-str-validations.md. PR #5255 by @hjlarry.docs/zh/docs/tutorial/sql-databases.md. PR #4999 by @Zssaer.docs/zh/docs/advanced/wsgi.md. PR #4505 by @ASpathfinder.docs/pt/docs/tutorial/body-multiple-params.md. PR #4111 by @lbmendes.docs/pt/docs/tutorial/path-params-numeric-validations.md. PR #4099 by @lbmendes.deployment/versions.md. PR #3690 by @rjNemo.docs/fr/docs/help-fastapi.md. PR #2233 by @JulianMaurin.docs/zh/docs/tutorial/security/first-steps.md. PR #5530 by @yuki1sntSnow.docs/pt/docs/tutorial/response-status-code.md. PR #4922 by @batlopes.mkdocs for languages as a subprocess to fix/enable MkDocs Material search plugin. PR #5501 by @tiangolo.default, 1XX, 2XX, 3XX, 4XX, 5XX. PR #5187 by @JarroVGIT.0.19.1 to 0.20.4. Initial PR #4820 by @Kludex.
>=0.12.0,<0.18.0 to >=0.12.0,<0.19.0. PR #5401 by @tiangolo.This version of FastAPI drops support for Python 3.6. 🔥 Please upgrade to a supported version of Python (3.7 or above), Python 3.6 reached the end-of-life a long time ago. 😅☠
🚨 This is probably the last release (or one of the last releases) to support Python 3.6. 🔥
Python 3.6 reached the end-of-life and is no longer supported by Python since around a year ago.
You hopefully updated to a supported version of Python a while ago. If you haven't, you really should.
RuntimeError raised when HTTPException has a status code with no content. PR #5365 by @iudeen.status_code is empty but the a Response parameter with response.status_code is set. PR #5360 by @tmeckel.🚨 This is probably the last release (or one of the last releases) to support Python 3.6. 🔥
Python 3.6 reached the end-of-life and is no longer supported by Python since around a year ago.
You hopefully updated to a supported version of Python a while ago. If you haven't, you really should.
WebSocketState in fastapi.websockets. PR #4376 by @matiuszka.ORJSONResponse to support non str keys and serializing Numpy arrays. PR #3892 by @baby5.yield to always execute, by removing capacity limiter for them, to e.g. allow closing DB connections without deadlocks. PR #5122 by @adriangb.docs/en/docs/advanced/dataclasses.md. PR #3698 by @pfackeldey.X | Y operator in explanation about Response Models. PR #5307 by @MendyLanda.ORJSONResponse with details about improving performance. PR #2615 by @falkben.docs/ru/docs/features.md. PR #5315 by @Xewus.docs/zh/docs/tutorial/request-files.md. PR #4529 by @ASpathfinder.docs/zh/docs/tutorial/encoder.md. PR #4969 by @Zssaer.background-task.md. PR #5242 by @ComicShrimp.operation_id parameter position in delete method for consistency with the code. PR #4474 by @hiel.<noscript> warning when JS is disabled. PR #5074 by @evroon.FrozenSet in parameters (e.g. query). PR #2938 by @juntatalor.HTTPExceptions and propagate them. PR #2036 by @ghandic.json.JSONDecodeError information when handling invalid JSON in request body, to support custom exception handlers that use its information. PR #4057 by @UKnowWhoIm.jsonable_encoder for dataclasses with pydantic-compatible fields. PR #3607 by @himbeles.openapi_extras with parameter lists. PR #4267 by @orilevari.docs/en/docs/python-types.md. PR #5193 by @GlitchingCore.tests/test_schema_extra_examples.py. PR #5126 by @supraaxdd.docs/en/docs/tutorial/path-params-numeric-validations.md. PR #5142 by @invisibleroads.docs/en/docs/contributing.md. PR #5181 by @edisnake.docs/en/docs/tutorial/body-nested-models.md. PR #5169 by @papb.docs/en/docs/features.md. PR #5206 by @OtherBarry.docs/en/docs/async.md. PR #5125 by @Ksenofanex.else. PR #4693 by @adriangb.docs/en/docs/python-types.md. PR #4886 by @MicaelJarniac.typo-fix-path-params-numeric-validations.md. PR #3219 by @ccrenfroe.secrets.compare_digest() to account for non-ASCII characters. PR #3536 by @lewoudar.docs/ru/docs/index.md. PR #5289 by @impocode.docs/ru/docs/deployment/versions.md. PR #4985 by @emp7yhead.docs/pt/docs/tutorial/header-params.md. PR #4921 by @batlopes.ko/mkdocs.yml for a missing link. PR #5020 by @dalinaum.tests/test_tutorial/test_sql_databases/test_sql_databases.py. PR #5040 by @raccoonyy.fastapi/utils.py. PR #5057 by @pylounge.auto_error which does not need to be Optional[bool]. PR #4933 by @DavidKimDY.strict = true instead of manual configs. PR #4605 by @michaeloliverx.dict() for {} in fastapi/utils.py. PR #3138 by @ShahriyarR.jsonable_encoder to put related code closer. PR #4560 by @GuilleQP.fastapi/dependencies/utils.py. PR #4597 by @cikay.flake8 >=3.8.3,<6.0.0. PR #4097 by @jamescurtin.If you are using response_model with some type that doesn't include None but the function is returning None, it will now raise an internal server error, because you are returning invalid data that violates the contract in response_model. Before this release it would allow breaking that contract returning None.
For example, if you have an app like this:
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: Optional[float] = None
owner_ids: Optional[List[int]] = None
app = FastAPI()
@app.get("/items/invalidnone", response_model=Item)
def get_invalid_none():
return None
...calling the path /items/invalidnone will raise an error, because None is not a valid type for the response_model declared with Item.
You could also be implicitly returning None without realizing, for example:
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: Optional[float] = None
owner_ids: Optional[List[int]] = None
app = FastAPI()
@app.get("/items/invalidnone", response_model=Item)
def get_invalid_none():
if flag:
return {"name": "foo"}
# if flag is False, at this point the function will implicitly return None
If you have path operations using response_model that need to be allowed to return None, make it explicit in response_model using Union[Something, None]:
from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: Optional[float] = None
owner_ids: Optional[List[int]] = None
app = FastAPI()
@app.get("/items/invalidnone", response_model=Union[Item, None])
def get_invalid_none():
return None
This way the data will be correctly validated, you won't have an internal server error, and the documentation will also reflect that this path operation could return None (or null in JSON).
oauth2-redirect.html to include fixes for flavors of authorization code flows in Swagger UI. PR #3439 initial PR by @koonpeng.Security() and other places (e.g. Depends()) with different OAuth2 scopes. PR #2945 by @laggardkernel.response_model, allow things like Union[str, None]. PR #5294 by @tiangolo.docs/de/docs/features.md. PR #4533 by @0xflotus.encoder.md in Korean translation. PR #5238 by @joonas-yoon.jsonable_encoder using include and exclude parameters for non-Pydantic objects. PR #2606 by @xaviml.python-types.md. PR #5116 by @Kludex.docs/en/docs/python-types.md. PR #5007 by @atiabbz.docs/pt/docs/tutorial/query-params.md. PR #4775 by @batlopes.docs/pt/docs/tutorial/security/first-steps.md. PR #4954 by @FLAIR7.docs/zh/docs/advanced/response-cookies.md. PR #4638 by @zhangbo2012.docs/fr/docs/deployment/index.md. PR #3689 by @rjNemo.tutorial/handling-errors.md. PR #4769 by @frnsimoes.docs/fr/docs/history-design-future.md. PR #3451 by @rjNemo.docs/ru/docs/tutorial/background-tasks.md. PR #4854 by @AdmiralDesu.docs/tutorial/security/first-steps.md. PR #3841 by @jaystone776.docs/ja/docs/advanced/nosql-databases.md. PR #4205 by @sUeharaE4.docs/id/docs/tutorial/index.md. PR #4705 by @bas-baskara.docs/fa/docs/index.md and tweak right-to-left CSS. PR #2395 by @mohsen-mahmoodi.status_code to 204, 304, or any code below 200 (1xx) will remove the body from the response.RuntimeError: Response content longer than Content-Length.fastapi.openapi.constants.STATUS_CODES_WITH_NO_BODY, it is replaced by a function in utils.docs/ja/docs/advanced/index.md. PR #5043 by @wakabame.docs/pl/docs/tutorial/first-steps.md. PR #5024 by @Valaraucoo.Optional[X] to Union[X, None] for internal utils. PR #5124 by @tiangolo.✨ Add support for omitting ... as default value when declaring required parameters with:
Path()
Query()
Header()
Cookie()
Body()
Form()
File()
New docs at Tutorial - Query Parameters and String Validations - Make it required. PR #4906 by @tiangolo.
Up to now, declaring a required parameter while adding additional validation or metadata needed using ... (Ellipsis).
For example:
from fastapi import Cookie, FastAPI, Header, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
def main(
item_id: int = Path(default=..., gt=0),
query: str = Query(default=..., max_length=10),
session: str = Cookie(default=..., min_length=3),
x_trace: str = Header(default=..., title="Tracing header"),
):
return {"message": "Hello World"}
...all these parameters are required because the default value is ... (Ellipsis).
But now it's possible and supported to just omit the default value, as would be done with Pydantic fields, and the parameters would still be required.
✨ For example, this is now supported:
from fastapi import Cookie, FastAPI, Header, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
def main(
item_id: int = Path(gt=0),
query: str = Query(max_length=10),
session: str = Cookie(min_length=3),
x_trace: str = Header(title="Tracing header"),
):
return {"message": "Hello World"}
To declare parameters as optional (not required), you can set a default value as always, for example using None:
from typing import Union
from fastapi import Cookie, FastAPI, Header, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
def main(
item_id: int = Path(gt=0),
query: Union[str, None] = Query(default=None, max_length=10),
session: Union[str, None] = Cookie(default=None, min_length=3),
x_trace: Union[str, None] = Header(default=None, title="Tracing header"),
):
return {"message": "Hello World"}
Union over Optional and migrate source examples. New docs at Python Types Intro - Using Union or Optional. PR #4908 by @tiangolo.docs/ja/docs/tutorial/testing.md. PR #4623 by @hirotoKirimaru.fastapi/utils.py. PR #3139 by @ShahriyarR.docs/en/docs/tutorial/security/first-steps.md. PR #4515 by @KikoIlievski.docs/pl/docs/tutorial/index.md. PR #4516 by @MKaczkow.docs/pt/docs/help-fastapi.md. PR #4583 by @mateusjs.JSONResponse the content argument is now required.TestClient. PR #4389 by @rgilton.docs/en/docs/tutorial/sql-databases.md. PR #4875 by @wpyoga.docs/en/docs/async.md. PR #4726 by @Prezu.docs/zh/docs/tutorial/query-params-str-validations.md. PR #4237 by @caimaoy.docs/pt/docs/tutorial/path-params.md. PR #4722 by @CleoMenezesJr.docs/pt/docs/tutorial/cookie-params.md. PR #4112 by @lbmendes.docs/tutorial/body.md. PR #4332 by @Smlep.docs/ja/docs/advanced/conditional-openapi.md. PR #2631 by @sh0nk.docs/ja/docs/tutorial/body.md. PR #3062 by @a-takahashi223.docs/pt/docs/tutorial/background-tasks.md. PR #2170 by @izaguerreiro.docs/deployment/deta.md. PR #4442 by @lsglucas.docs/async.md. PR #4036 by @Winand.docs/tutorial/body.md. PR #3960 by @leandrodesouzadev.tutorial/extra-data-types.md. PR #4077 by @luccasmmg.docs/features.md. PR #3905 by @jomue.This release includes upgrades to third-party packages that handle security issues. Although there's a chance these issues don't affect you in particular, please upgrade as soon as possible.
ValidationError JSON Schema. PR #4806 by @tiangolo.ValidationError at field loc. PR #3810 by @dconathan./docs) publicly to non-expert users. PR #4347 by @RAlanWright.generate_unique_id_function and docs for generating clients. New docs: Advanced - Generate Clients. PR #4650 by @tiangolo.Dependencies with yield can now catch HTTPException and custom exceptions. For example:
async def get_database():
with Session() as session:
try:
yield session
except HTTPException:
session.rollback()
raise
finally:
session.close()
After the dependency with yield handles the exception (or not) the exception is raised again. So that any exception handlers can catch it, or ultimately the default internal ServerErrorMiddleware.
If you depended on exceptions not being received by dependencies with yield, and receiving an exception breaks the code after yield, you can use a block with try and finally:
async def do_something():
try:
yield something
finally:
some_cleanup()
...that way the finally block is run regardless of any exception that might happen.
contextvars context for the code before and after yield. This was the main objective of that PR.This means that now, if you set a value in a context variable before yield, the value would still be available after yield (as you would intuitively expect). And it also means that you can reset the context variable with a token afterwards.
For example, this works correctly now:
from contextvars import ContextVar
from typing import Any, Dict, Optional
legacy_request_state_context_var: ContextVar[Optional[Dict[str, Any]]] = ContextVar(
"legacy_request_state_context_var", default=None
)
async def set_up_request_state_dependency():
request_state = {"user": "deadpond"}
contextvar_token = legacy_request_state_context_var.set(request_state)
yield request_state
legacy_request_state_context_var.reset(contextvar_token)
...before this change it would raise an error when resetting the context variable, because the contextvars context was different, because of the way it was implemented.
Note: You probably don't need contextvars, and you should probably avoid using them. But they are powerful and useful in some advanced scenarios, for example, migrating from code that used Flask's g semi-global variable.
Technical Details: If you want to know more of the technical details you can check out the PR description #4575.
UploadFile parameters without explicit File(). PR #4469 by @tiangolo. New docs: Request Files - File Parameters with UploadFile.Query, Cookie, Header, and Path parameters. PR #3144 by @astraldawn. New docs: Query Parameters and String Validations - Exclude from OpenAPI.jsonable_encoder. PR #2061 by @viveksunder.
docs/help-fastapi.md. PR #3847 by @jaystone776.docs/ko/docs/index.md. PR #4195 by @kty4119.docs/pl/docs/index.md. PR #4245 by @MicroPanda123.docs\tutorial\path-operation-configuration.md. PR #3312 by @jaystone776.There's nothing interesting in this particular FastAPI release. It is mainly to enable/unblock the release of the next version of Pydantic that comes packed with features and improvements. 🤩
docs/tutorial/request-forms-and-files.md. PR #3744 by @NinaHwang.docs/tutorial/request-files.md. PR #3743 by @NinaHwang.docs/tutorial/query-params-str-validations.md. PR #3965 by @leandrodesouzadev.docs/tutorial/response-status-code.md. PR #3742 by @NinaHwang.docs/ko/docs/deployment/versions.md. PR #4121 by @DevDae.docs/ko/docs/tutorial/index.md. PR #4193 by @kimjaeyoonn.docs/tutorial/dependencies/classes-as-dependencies: Add type of query parameters in a description of Classes as dependencies. PR #4015 by @0417taehyun.docs/tutorial/path-params.md. PR #3548 by @Smlep.docs/tutorial/query-params.md. PR #3556 by @Smlep.docs/python-types.md. PR #3926 by @BilalAlpaslan.This release just upgrades Starlette to the latest version, 0.16.0, which includes several bug fixes and some small breaking changes.
These last three consecutive releases are independent so that you can migrate gradually:
0.68.2, with no breaking changes, but upgrading all the sub-dependencies.0.69.0, which upgrades Starlette to 0.15.0, with AnyIO support, and a higher chance of having breaking changes in your code.0.70.0, just upgrading Starlette to the latest version 0.16.0 with additional bug fixes.This way, in case there was a breaking change for your code in one of the releases, you can still benefit from the previous upgrades. ✨
Also upgrades the ranges of optional dependencies:
"jinja2 >=2.11.2,<4.0.0""itsdangerous >=1.1.0,<3.0.0"This release adds support for Trio. ✨
It upgrades the version of Starlette to 0.15.0, now based on AnyIO, and the internal async components in FastAPI are now based on AnyIO as well, making it compatible with both asyncio and Trio.
You can read the docs about running FastAPI with Trio using Hypercorn.
This release also removes graphene as an optional dependency for GraphQL. If you need to work with GraphQL, the recommended library now is Strawberry. You can read the new FastAPI with GraphQL docs.
0.15.0. PR #3372 by @graingert.graphene as an optional dependency. PR #4007 by @tiangolo.docs/en/docs/contributing.md. PR #3752 by @NinaHwang.docs/en/docs/advanced/path-operation-advanced-configuration.md and docs/en/docs/release-notes.md. PR #3750 by @saintmalik.docs/en/docs/help-fastapi.md. PR #3760 by @jaystone776.docs/en/docs/tutorial/bigger-applications.md. PR #3285 by @HolyDorus.docs/en/docs/tutorial/testing.md. PR #3382 by @Bharat123rox.docs/en/docs/advanced/templates.md. PR #3211 by @oerpli.docs/en/docs/tutorial/request-files.md. PR #2803 by @gsganden.docs/tutorial/handling-errors.md. PR #2700 by @graue70.docs/fastapi-people.md. PR #3848 by @BilalAlpaslan.docs/ja/docs/deployment/docker.md. PR #3245 by @utamori.This release has no breaking changes. 🎉
It upgrades the version ranges of sub-dependencies to allow applications using FastAPI to easily upgrade them.
Soon there will be a new FastAPI release upgrading Starlette to take advantage of recent improvements, but as that has a higher chance of having breaking changes, it will be in a separate release.
docs/features.md. PR #1950 by @ycd.docs/benchmarks.md. PR #2729 by @Telomeraz.docs/index.md. PR #1908 by @ycd.docs/tutorial/body.md. PR #3671 by @Smlep.deployment/docker.md. PR #3694 by @rjNemo.docs/tutorial/path-params.md. PR #3664 by @FelipeSilva93.docs/deployment/https.md. PR #3754 by @lsglucas.docs/features.md. PR #3699 by @mawassk.autoflake, supporting multi-line imports. PR #3988 by @tiangolo.read_with_orm_mode, to support SQLModel relationship attributes. PR #3757 by @tiangolo.docs/fastapi-people.md. PR #3461 by @ComicShrimp.docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md. PR #3492 by @jaystone776.docs/tutorial/dependencies/sub-dependencies.md. PR #3491 by @jaystone776.docs/advanced/index.md. PR #3460 by @ComicShrimp.docs/async.md. PR #1330 by @Serrones.docs/async.md. PR #3416 by @Smlep.FastAPI class, shown on the automatic API docs UI. New docs: Metadata and Docs URLs. Initial PR #1812 by @dkreeft.description parameter to all the security scheme classes, e.g. APIKeyQuery(name="key", description="A very cool API key"). PR #1757 by @hylkepostma.fastapi.datastructures. Initial PR #1872 by @jamescurtin.docs/python-types.md. PR #3039 by @dukkee.docs/tutorial/dependencies/index.md. PR #3489 by @jaystone776.docs/external-links.md. PR #3036 by @dukkee.docs/tutorial/dependencies/global-dependencies.md. PR #3493 by @jaystone776.docs/deployment/versions.md. PR #3618 by @lsglucas.docs/tutorial/security/oauth2-jwt.md. PR #3526 by @sattosan.docs_src directory to test coverage and update tests. Initial PR #1904 by @Kludex.dataclasses in request bodies and response_model. New documentation: Advanced User Guide - Using Dataclasses. PR #3577 by @tiangolo.dataclasses in responses. PR #3576 by @tiangolo, continuation from initial PR #2722 by @amitlissack.body-nested-models.md. PR #3463 by @jaystone776.body-nested-models.md. PR #3462 by @jaystone776.docs/en/docs/tutorial/schema-extra-example.md. PR #3362 by @dbrakman.docs/tutorial/security/index.md. PR #3507 by @oandersonmagalhaes.docs/deployment/index.md. PR #3337 by @lsglucas.>=6.2.4,<7.0.0 and pytest-cov to >=2.12.0,<3.0.0. Initial PR #2790 by @graingert.>=3.3.0,<4.0.0 for tests. PR #3468 by @tiangolo.response_class to RedirectResponse or FileResponse and returning the URL from the function. New and updated docs are in the tutorial section Custom Response - HTML, Stream, File, others, in RedirectResponse and in FileResponse. PR #3457 by @tiangolo.jsonable_encoder. PR #2016 by @Rubikoid.tutorial/query-params.md. PR #2243 by @mariacamilagl.advanced/response-directly.md. PR #1253 by @jfunez.advanced/additional-status-codes.md. PR #1252 by @jfunez.advanced/path-operation-advanced-configuration.md. PR #1251 by @jfunez.Content-Type header. And there's still protection against CSRFs. PR #3456 by @tiangolo.typer-cli to >=0.0.12 to fix conflicts. PR #3429 by @tiangolo.This change fixes a CSRF security vulnerability when using cookies for authentication in path operations with JSON payloads sent by browsers.
In versions lower than 0.65.2, FastAPI would try to read the request payload as JSON even if the content-type header sent was not set to application/json or a compatible JSON media type (e.g. application/geo+json).
So, a request with a content type of text/plain containing JSON data would be accepted and the JSON data would be extracted.
But requests with content type text/plain are exempt from CORS preflights, for being considered Simple requests. So, the browser would execute them right away including cookies, and the text content could be a JSON string that would be parsed and accepted by the FastAPI application.
See CVE-2021-32677 for more details.
Thanks to Dima Boger for the security report! 🙇🔒
0.14.2, including internal UJSONResponse migrated from Starlette. This includes several bug fixes and features from Starlette. PR #2335 by @hanneskuettner.overrides boilerplate. PR #3202 by @tiangolo.examples in request bodies and path, query, cookie, and header params. New docs: Declare Request Example Data. Initial PR #1267 by @austinorr.fastapi[all] to the latest version including uvloop, the new range is uvicorn[standard] >=0.12.0,<0.14.0. PR #2548 by @tiangolo.callbacks parameters and when using the OAuth2 class.Up to now, for several options, the only way to apply them to a group of path operations was in include_router. That works well, but the call to app.include_router() or router.include_router() is normally done in another file.
That means that, for example, to apply authentication to all the path operations in a router it would end up being done in a different file, instead of keeping related logic together.
Setting options in include_router still makes sense in some cases, for example, to override or increase configurations from a third party router included in an app. But in a router that is part of a bigger application, it would probably make more sense to add those settings when creating the APIRouter.
In FastAPI
This allows setting the (mostly new) parameters (additionally to the already existing parameters):
default_response_class: updated to handle defaults in APIRouter and include_router.dependencies: to include ✨ top-level dependencies ✨ that apply to the whole application. E.g. to add global authentication.callbacks: OpenAPI callbacks that apply to all the path operations.deprecated: to mark all the path operations as deprecated. 🤷include_in_schema: to allow excluding all the path operations from the OpenAPI schema.responses: OpenAPI responses that apply to all the path operations.For example:
from fastapi import FastAPI, Depends
async def some_dependency():
return
app = FastAPI(dependencies=[Depends(some_dependency)])
In APIRouter
This allows setting the (mostly new) parameters (additionally to the already existing parameters):
default_response_class: updated to handle defaults in APIRouter and include_router. For example, it's not needed to set it explicitly when creating callbacks.dependencies: to include ✨ router-level dependencies ✨ that apply to all the path operations in a router. Up to now, this was only possible with include_router.callbacks: OpenAPI callbacks that apply to all the path operations in this router.deprecated: to mark all the path operations in a router as deprecated.include_in_schema: to allow excluding all the path operations in a router from the OpenAPI schema.responses: OpenAPI responses that apply to all the path operations in a router.prefix: to set the path prefix for a router. Up to now, this was only possible when calling include_router.tags: OpenAPI tags to apply to all the path operations in this router.For example:
from fastapi import APIRouter, Depends
async def some_dependency():
return
router = APIRouter(prefix="/users", dependencies=[Depends(some_dependency)])
In include_router
Most of these settings are now supported in APIRouter, which normally lives closer to the related code, so it is recommended to use APIRouter when possible.
But include_router is still useful to, for example, adding options (like dependencies, prefix, and tags) when including a third party router, or a generic router that is shared between several projects.
This PR allows setting the (mostly new) parameters (additionally to the already existing parameters):
default_response_class: updated to handle defaults in APIRouter and FastAPI.deprecated: to mark all the path operations in a router as deprecated in OpenAPI.include_in_schema: to allow disabling all the path operations from showing in the OpenAPI schema.callbacks: OpenAPI callbacks that apply to all the path operations in this router.Note: all the previous parameters are still there, so it's still possible to declare dependencies in include_router.
tags in include_router and path operations was updated for consistency, but it's a simple order change.route.response_class, or the router.default_response_class, or the app.default_response_class: the default value for response_class in APIRoute and for default_response_class in APIRouter and FastAPI is now a DefaultPlaceholder used internally to handle and solve default values and overrides. The actual response class inside the DefaultPlaceholder is available at route.response_class.value.PR #2434 (above) includes new or updated docs:
📝 Add FastAPI monitoring blog post to External Links. PR #2324 by @louisguitton.
content_type typo. PR #2135 by @TeoZosa.jsonable_encoder with SQLAlchemy models directly. PR #1987.HTTPConnection (as Request and WebSocket). Useful for sharing app state in dependencies. PR #1827 by @nsidnev.WebSocketDisconnect and add example handling WebSocket disconnections to docs. PR #1822 by @rkbeatss.1.0.0.
0.32.2. This improves maintainability and allows new features.FastAPI and APIRouter:
response_model_skip_defaults (use response_model_exclude_unset instead).response_model_exclude from set() to None (as is in Pydantic).encoders.jsonable_encoder:
skip_defaults, use instead exclude_unset.exclude from set() to None (as is in Pydantic).encoders.jsonable_encoder remove parameter sqlalchemy_safe.
orm_mode as described in the tutorial: SQL (Relational) Databases.Form, File) without having python-multipart installed.
python-multipart is installed instead of the incorrect multipart (both importable as multipart).json_encoders. PR #1769 by @henrybetts.jsonable_encoder. PR #1754 by @MashhadiNima.Optional parameters. PR #1731 by @MashhadiNima.**extra parameters in FastAPI. PR #1659 by @bharel.0.13.6 to handle a vulnerability when using static files in Windows. PR #1759 by @jamesag26.servers when there's a root_path instead of prefixing all the paths:
FastAPI classes: root_path_in_servers to disable the auto-generation of servers.root_path and servers in Additional Servers.tokenUrl="token" to make sure those examples keep working as-is even when behind a reverse proxy.openapi_prefix. PR #1611 by @bavaria95..gitignore for contributors using Vim. PR #1590 by @asheux.Optional in all the examples in the docs. Original PR #1574 by @chrisngyn, @kx-chen, @YKo20010. Updated and merged PR #1644.response_model_by_alias. PR #1642.not as a JSON Schema instead of a list. PR #1548 by @v-do.servers. PR #1547 by @mikaello.http.HTTPStatus in status_code parameters. PR #1534 by @retnikt.__root__, use the internal value in jsonable_encoder. PR #1524 by @patrickkwang.showCommonExtensions in Swagger UI to show additional validations like maxLength, etc. PR #1466 by @TiewKH.OAuth2PasswordRequestFormStrict importable directly from fastapi.security. PR #1462 by @RichardHoekstra.response_model_exclude_defaults and response_model_exclude_none in Response Model. PR #1427 by @wshayes.0.13.4. PR #1361 by @rushton.__repr__ for path operation function parameter helpers (like Query, Depends, etc) to simplify debugging. PR #1560 by @rkbeatss and @victorphoenix3.Optional. Original PR #1377 by @yaegassy.yield. PR #1365 by @mrosales.get_path_param_names(). PR #1243 by @heckad.*, from functions in docs where it's not needed. PR #1239 by @pankaj-giri.root_path:
root_path internally for mounted applications, so that OpenAPI and the docs UI works automatically without extra configurations and parameters.root_path parameter for FastAPI applications to provide it in cases where it can be set with the command line (e.g. for Uvicorn and Hypercorn, with the parameter --root-path).openapi_prefix parameter in favor of the new root_path parameter.openapi_prefix (as it is now handled automatically).root_path.openapi_prefix parameter passed (internally generated from root_path).max_age=600. PR #1301 by @derekbekoe.* in short features in the docs is consistent (after .) in all languages. PR #1424.get_db in SQLAlchemy tutorial. PR #1293 by @bcb.openapi_url=None. New example in docs: Advanced: Conditional OpenAPI. PR #1421.response_model_exclude_defaults and response_model_exclude_none:
env to .gitignore. PR #1212 by @cassiobotaro.Settings using a dependency with @lru_cache(). PR #1214.example in Field. Docs at Body - Fields: JSON Schema extras. PR #1106 by @JohnPaton.response_model. PR #1164 by @voegtlel.orjson to pip install fastapi[all]. PR #1161 by @michael0liver.GZipMiddleware. PR #1138 by @arimbr.OAuth2PasswordRequestFormStrict. PR #1126 by @adg-mh.by_alias or exclude_unset and returning data with Pydantic models. PR #1074 by @juhovh-aiven.127.0.0.1 to improve Windows support. PR #1169 by @mariacamilagl.orjson. New docs: Custom Response - HTML, Stream, File, others: ORJSONResponse. PR #1065.from fastapi.responses import JSONResponse instead of from starlette.responses import JSONResponse.Request, Response, WebSocket, status can be imported directly from fastapi as in from fastapi import Response. This is because those are frequently used, to use the request directly, to set headers and cookies, to get status codes, etc./."startup", and "shutdown".serialize_response parameter name to avoid confusion. PR #1031 by @patrickmckenna.List[int]. PR #1017 by @patrickmckenna.pathlib paths in jsonable_encoder. PR #978 by @patrickmckenna.yield. PR #986.yield and HTTPException. PR #985.callables in path operation functions, like functions modified with functools.partial. PR #977.email-validator only when used. PR #946.yield. PR #947.Any type for enums in OpenAPI. PR #906 by @songzhi.response_model, cloning sub-models. PR #889.username and password. PR #865 by @isaevpd.list, tuple, etc. PR #856 by @nsidnev.body to RequestValidationError, new docs: Use the RequestValidationError body. Initial PR #853 by @aviramha.fastapi topic. PR #850.contextvars handling in docs: SQL (Relational) Databases with Peewee. PR #879.OAuth2AuthorizationCodeBearer class. PR #797 by @kuwv.jsonable_encoder, e.g. asyncpg's UUIDs. PR #756 by @RmStorm.HttpUrl in docs. PR #832 by @Dustyposa.operationIds to be valid Python names (also valid variables in most languages).default_response_class parameter to APIRouter.body-schema to body-fields to keep in line with Pydantic. PR #746 by @prostomarkeloff.custom_encoder in jsonable_encoder. PR #715 by @matrixise.APIRouter docs. PR #698 by @marier-nico.1.0.0 and above, with temporary (deprecated) backwards compatibility for Pydantic 0.32.2. PR #646 by @dmontagu.operationId for all the path operations based on their function name. PR #642 by @SKalt.$ from Bash code blocks in docs for consistency. PR #613 by @nstapelbroek.black linting after upgrade. PR #682 by @frankie567.yield, a.k.a. exit steps, context managers, cleanup, teardown, ...
yield can be normal or async, FastAPI will run normal dependencies in a threadpool.yield and exit steps are handled in the correct order automatically.async-exit-stackasync-generatoryield.sitemap.xml in website. PR #598 by @samuelcolvin.0.12.9, the new range is >=0.12.9,<=0.12.9.
State to FastAPI apps at app.state.Requests and APIRoutes.
python-multipart when using forms. PR #574 by @sliptonic.DOCTYPE in HTML files generated for Swagger UI and ReDoc. PR #537 by @Trim21.4XX responses overriding default 422 validation error responses. PR #517 by @tsouvarev.swagger_ui_init_oauth. PR #499 by @zamiramir.None) and discard them instead of raising an error.
user_id: str = None that can be taken from a query parameter, but the same path operation can be included in a router with a path /users/{user_id}, in which case will be taken from the path and will be required.default_response_class in the FastAPI instance or in include_router. Initial PR #467 by @toppk.from __future__ import annotations. PR #451 by @dmontagu.Request class import. PR #493 by @kamalgill.0.12.8. The new range is >=0.11.1,<=0.12.8". PR #477 by @dmontagu.skip_defaults it could leak information. PR #485 by @dmontagu.response_model. PR #454 by @dconathan.media_type parameter in Body() params to set the media type in OpenAPI for requestBody. PR #439 by @divums.422 (validation error) response/schema in OpenAPI.
"default" extra response with status codes at the same time. PR #489.5XX and 4XX) and "default". PR #435 by @divums.skip_defaults when returning a Pydantic model. PR #422 by @dmontagu.include_router and a prefix.
assert. PR #419 by @pablogamboa.Union. PR #400 by @koxudaxi.Upgrade Starlette supported range to include the latest 0.12.7. The new range is 0.11.1,<=0.12.7. PR #367 by @dedsm.
Add test for OpenAPI schema with duplicate models from PR #333 by @dmontagu. PR #385.
Fix typo in docs for features. PR #380 by @MartinoMensio.
Fix source code limit for example in Query Parameters. PR #366 by @Smashman.
Update wording in docs about OAuth2 scopes. PR #371 by @cjw296.
Update docs for Enums to inherit from str and improve Swagger UI rendering. PR #351.
Fix regression, add Swagger UI deep linking again. PR #350.
Add test for having path templates in prefix of .include_router. PR #349.
Add note to docs: Include the same router multiple times with different prefix. PR #348.
Fix OpenAPI/JSON Schema generation for two functions with the same name (in different modules) with the same composite bodies.
.include_router() with the same APIRouter multiple times, with different prefixes, e.g. /api/v2 and /api/latest, and it will now work correctly.0.29.0.
"pydantic >=0.28,<=0.29.0".Add section in docs about External Links and Articles. PR #341.
Remove Pipfile.lock from the repository as it is only used by FastAPI contributors (developers of FastAPI itself). See the PR for more details. PR #340.
Update section about Help FastAPI - Get Help. PR #339.
Refine internal type declarations to improve/remove Mypy errors in users' code. PR #338.
Update and clarify SQL tutorial with SQLAlchemy. PR #331 by @mariacamilagl.
Add SQLite online viewers to the docs. PR #330 by @cyrilbois.
Add support for Pydantic's ORM mode:
@property decorators) and several other use cases.my_item.name instead of my_item["name"]) AND you use a response_model, make sure to update the Pydantic models with orm_mode = True as described in the docs (link above).dicts as request bodies: Bodies of arbitrary dicts.dicts in responses: Response with arbitrary dict.response_model it is used directly to generate the response content, from whatever was returned from the path operation function.jsonable_encoder to ensure it was a "jsonable" object, like a dict, instead of an arbitrary object with attributes (like an ORM model). That's why you should make sure to update your Pydantic models for objects with attributes to use orm_mode = True.response_model, the return object will still be passed through jsonable_encoder first.response_model is declared, the same response_model type declaration won't be used as is, it will be "cloned" to create an new one (a cloned Pydantic Field with all the submodels cloned as well).response_model (e.g. you return a UserInDB that inherits from User but contains extra fields, like hashed_password, and User is used in the response_model), it would still pass the validation (because UserInDB is a subclass of User) and the object would be returned as-is, including the hashed_password. To fix this, the declared response_model is cloned, if it is a Pydantic model class (or contains Pydantic model classes in it, e.g. in a List[Item]), the Pydantic model class(es) will be a different one (the "cloned" one). So, an object that is a subclass won't simply pass the validation and returned as-is, because it is no longer a sub-class of the cloned response_model. Instead, a new Pydantic model object will be created with the contents of the returned object. So, it will be a new object (made with the data from the returned one), and will be filtered by the cloned response_model, containing only the declared fields as normally.Remove/clean unused RegEx code in routing. PR #314 by @dmontagu.
Use default response status code descriptions for additional responses. PR #313 by @duxiaoyao.
Fix handling an empty-body request with a required body param. PR #311.
Fix broken link in docs: Return a Response directly. PR #306 by @dmontagu.
Fix docs discrepancy in docs for Response Model. PR #288 by @awiddersheim.
Response parameter:
dict, DB model, etc).response parameter pattern.Implement dependency cache per request.
.include_router()) and then it is declared again in a specific path operation, the dependency will be called only once.use_cache=False as in Depends(your_dependency, use_cache=False).Implement dependency overrides for testing.
dict as a valid type. It should be mapped to a body payload. PR #287. Updated docs at: Query parameter list / multiple values with defaults: Using list.Fix auto_error=False handling in HTTPBearer security scheme. Do not raise when there's an incorrect Authorization header if auto_error=False. PR #282.
Fix type declaration of HTTPException. PR #279.
Fix broken link in docs about OAuth 2.0 with scopes. PR #275 by @dmontagu.
Refactor param extraction using Pydantic Field:
Optional as in param: Optional[str] = None. New documentation: Optional type declarations.Separate error handling for validation errors.
RequestValidationError and WebSocketRequestValidationError (this last one will be useful once encode/starlette#527 or equivalent is merged).Fix support for paths in path parameters without needing explicit Path(...).
Update docs for testing FastAPI. Include using POST, sending JSON, testing headers, etc. New documentation: Testing. PR #271.
Fix type declaration of response_model to allow generic Python types as List[Model]. Mainly to fix mypy for users. PR #266.
Add support for Pydantic's include, exclude, by_alias.
skip_defaults.Add CONTRIBUTING.md file to GitHub, to help new contributors. PR #255 by @wshayes.
Add support for Pydantic's skip_defaults:
response_model_skip_defaults.
response_skip_defaults, model_skip_defaults or something similar.response_model_skip_defaults.Add support for WebSockets with dependencies and parameters.
DependsSecurityCookieHeaderPathQueryBody is not).Upgrade the compatible version of Pydantic to 0.26.0.
Upgrade the compatible version of Starlette to 0.12.0.
StreamingResponse with iterators, like file-like objects (as those returned by open()).iterate_in_threadpool from starlette.concurrency (for advanced scenarios).Add OAuth2 redirect page for Swagger UI. This allows having delegated authentication in the Swagger UI docs. For this to work, you need to add {your_origin}/docs/oauth2-redirect to the allowed callbacks in your OAuth2 provider (in Auth0, Facebook, Google, etc).
http://localhost:8000/docs/oauth2-redirect.https://yourdomain.com/login/callback.Make Swagger UI and ReDoc route handlers (path operations) be async functions instead of lambdas to improve performance. PR #241 by @Trim21.
Make Swagger UI and ReDoc URLs parameterizable, allowing to host and serve local versions of them and have offline docs. PR #112 by @euri10.
Add support for dependencies parameter:
.include_router() method of FastAPI applications and routers, to include dependencies that should be executed in each path operation in a router.
dependencies can be applied to different routers.dependencies are run before the normal parameter dependencies. And normal dependencies are run too. They can be combined.Security with scopes in those dependencies parameters, for more advanced OAuth 2.0 security scenarios with scopes.include_router() method.Fix OpenAPI documentation of Starlette URL convertors. Specially useful when using path convertors, to take a whole path as a parameter, like /some/url/{p:path}. PR #234 by @euri10.
Make default parameter utilities exported from fastapi be functions instead of classes (the new functions return instances of those classes). To be able to override the return types and fix mypy errors in FastAPI's users' code. Applies to Path, Query, Header, Cookie, Body, Form, File, Depends, and Security. PR #226 and PR #231.
Separate development scripts test.sh, lint.sh, and format.sh. PR #232.
Re-enable black formatting checks for Python 3.7. PR #229 by @zamiramir.
On body parsing errors, raise from previous exception, to allow better introspection in logging code. PR #192 by @ricardomomm.
Use Python logger named "fastapi" instead of root logger. PR #222 by @euri10.
Fix typo in routing. PR #221 by @djlambert.
Add typing information to package including file py.typed. PR #209 by @meadsteve.
Add FastAPI bot for Gitter. To automatically announce new releases. PR #189.
Upgrade OAuth2:
UNAUTHORIZED, with WWW-Authenticate headers.scope_str to SecurityScopes and update docs: OAuth2 scopes.Include Hypercorn as an alternative ASGI server in the docs. PR #187.
Add docs for Static Files and Templates. PR #186.
Add docs for handling Response Cookies and Response Headers. PR #185.
Rename path operation decorator parameter content_type to response_class. PR #183.
Add docs:
jsonable_encoder in JSON compatible encoder.Add docs for HTTP Basic Auth. PR #177.
Upgrade HTTP Basic Auth handling with automatic headers (automatic browser login prompt). PR #175.
Update dependencies for security. PR #174.
Add docs for Middleware. PR #173.
Make Flit publish from CI. PR #170.
Add documentation about handling CORS (Cross-Origin Resource Sharing). PR #169.
By default, encode by alias. This allows using Pydantic alias parameters working by default. PR #168.
Upgrade path operation docstring parsing to support proper Markdown descriptions. New documentation at Path Operation Configuration. PR #163.
Refactor internal usage of Pydantic to use correct data types. PR #164.
Fix typo in Tutorial about Extra Models. PR #159 by @danielmichaels.
Fix Query Parameters URL examples in docs. PR #157 by @hayata-yamamoto.
Add support for multiple file uploads (as a single form field). New docs at: Multiple file uploads. PR #158.
Add docs for: Additional Status Codes. PR #156.
Improve automatically generated names of path operations in OpenAPI (in API docs). A function read_items instead of having a generated name "Read Items Get" will have "Read Items". PR #155.
Add docs for: Testing FastAPI. PR #151.
Update /docs Swagger UI to enable deep linking. This allows sharing the URL pointing directly to the path operation documentation in the docs. PR #148 by @wshayes.
Update development dependencies, Pipfile.lock. PR #150.
Include Falcon and Hug in: Alternatives, Inspiration and Comparisons.
SecurityScopes:
SecurityScopes can be declared as a parameter like Request, to get the scopes of all super-dependencies/dependants.Security handling, merging scopes when declaring SecurityScopes.SecurityBase (like OAuth2) classes with Depends and still document them. Security now is needed only to declare scopes.Fix bug: handling additional responses in APIRouter.include_router(). PR #140.
Fix typo in SQL tutorial. PR #138 by @mostaphaRoudsari.
Fix typos in section about nested models and OAuth2 with JWT. PR #127 by @mmcloud.
responses parameter to path operation decorators to extend responses in OpenAPI (and API docs).
response_model, declare other media types (like images), etc.responses can also be added to .include_router(), the updated docs are here: Bigger Applications.scripts/test-cov-html.sh to allow passing extra parameters like -vv, for development.Add auto_error parameter to security utility functions. Allowing them to be optional. Also allowing to have multiple alternative security schemes that are then checked in a single dependency instead of each one verifying and returning the error to the client automatically when not satisfied. PR #134.
Update SQL Tutorial to close database sessions even when there are exceptions. PR #89 by @alexiri.
Fix duplicate dependency in pyproject.toml. PR #128 by @zxalif.
Add Gitter chat, badge, links, etc. https://gitter.im/tiangolo/fastapi . PR #117.
Add docs about Extending OpenAPI. PR #126.
Make Travis run Ubuntu Xenial (newer version) and Python 3.7 instead of Python 3.7-dev. PR #92 by @blueyed.
Fix duplicated param variable creation. PR #123 by @yihuang.
Add note in Response Model docs about why using a function parameter instead of a function return type annotation. PR #109 by @JHSaunders.
Fix event docs (startup/shutdown) function name. PR #105 by @stratosgear.
Fix OpenAPI (JSON Schema) for declarations of Python Union (JSON Schema additionalProperties). PR #121.
Update Background Tasks with a note on Celery.
Document response models using unions and lists, updated at: Extra Models. PR #108.
Add support for Background Tasks in path operation functions and dependencies. New documentation about Background Tasks is here. PR #103.
Add support for .websocket_route() in APIRouter. PR #100 by @euri10.
New docs section about Events: startup - shutdown. PR #99.
Upgrade compatible Pydantic version to 0.21.0. PR #90.
Add documentation for: Application Configuration.
Fix typo in docs. PR #76 by @matthewhegarty.
Fix link in "Deployment" to "Bigger Applications".
Add support for adding tags in app.include_router(). PR #55 by @euri10. Documentation updated in the section: Bigger Applications.
Update docs related to Uvicorn to use new --reload option from version 0.5.x. PR #74.
Update isort imports and scripts to be compatible with newer versions. PR #75.
Update technical details about async def handling with respect to previous frameworks. PR #64 by @haizaar.
Add deployment documentation for Docker in Raspberry Pi and other architectures.
Trigger Docker images build on Travis CI automatically. PR #65.
UploadFile in File parameter annotations.
File parameters with UploadFile.Form parameters mixed with File parameters, supporting bytes and UploadFile at the same time.Add technical details about async def handling to docs. PR #61.
Add docs for Debugging FastAPI applications in editors.
Fix typos in docs.
Add section about History, Design and Future.
Add docs for using WebSockets with FastAPI. PR #62.
Introduce new project generator based on FastAPI and PostgreSQL: https://github.com/tiangolo/full-stack-fastapi-postgresql. PR #52.
Update SQL tutorial with SQLAlchemy, using Depends to improve editor support and reduce code repetition. PR #52.
Improve middleware naming in tutorial for SQL with SQLAlchemy https://fastapi.tiangolo.com/tutorial/sql-databases/.
Update SQL with SQLAlchemy tutorial at https://fastapi.tiangolo.com/tutorial/sql-databases/ using the new official request.state. PR #45.
Upgrade Starlette to version 0.11.1 and add required compatibility changes. PR #44.
Add section about helping and getting help with FastAPI.
Add note about path operations order in docs.
Update section about error handling with more information and make relation with Starlette error handling utilities more explicit. PR #41.
Add new HTTPException with support for custom headers. With new documentation for handling errors at: https://fastapi.tiangolo.com/tutorial/handling-errors/. PR #35.
Add documentation to use Starlette Request object directly. Check #25 by @euri10.
Add issue templates to simplify reporting bugs, getting help, etc: #34.
Update example for the SQLAlchemy tutorial at https://fastapi.tiangolo.com/tutorial/sql-databases/ using middleware and database session attached to request.
Add openapi_prefix, support for reverse proxy and mounting sub-applications. See the docs at https://fastapi.tiangolo.com/advanced/sub-applications-proxy/: #26 by @kabirkhan.
Update docs/tutorial for SQLAlchemy including note about DB Browser for SQLite.
jsonable_encoder for Pydantic models with Config but without json_encoders: #29.