NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI, #65 most downloaded on PyPI
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Latest stable
0.165.0
Last release 2 days ago
18 Nov 2026
Release timing varies
gaps range from 8 days to 2 months
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
8 years old
371 releases · first in 2018
Drag across the ruler to compare, or tap a release to open it.
This is a breaking change (and only slightly) if you used dependencies with yield, used except in those dependencies, and didn't raise again.
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.Your coding agent can read these notes before it upgrades. Set up the MCP server →
⬆️ Upgrade version of Starlette to >= 0.36.3. PR #11086 by @tiangolo.
⬆️ Upgrade minimum version of 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 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.✨ Add support for Python 3.12. PR #10666 by @Jamim.
>=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.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.⬆️ Upgrade Starlette to >=0.29.0,<0.33.0, update docs and usage of templates with new Starlette arguments. PR #10846 by @tiangolo.
⬆️ Upgrade Starlette to 0.28.0. PR #9636 by @adriangb.
Using resources from dependencies with yield in background tasks is no longer supported.
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"Onwer 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 the diagram in the Release Notes for FastAPI 0.106.0.
The new execution flow can be found in the docs: Execution of dependencies with yield.
Using resources from dependencies with yield in background tasks is no longer supported.
This change is what supports the new features, read below. 🤓
Dependencies 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 .
✨ Add support for multiple Annotated annotations, e.g. Annotated[str, Field(), Query()]. PR #10773 by @tiangolo.
Annotated[str, Field(), Query()]. PR #10773 by @tiangolo.📌 Pin Swagger UI version to 5.9.0 temporarily to handle a bug crashing it in 5.9.1. PR #10529 by @alejandraklachquin.
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.✨ Add reference (code API) docs with PEP 727, add subclass with custom docstrings for BackgroundTasks, refactor docs structure. PR #10392 by @tiangolo
BackgroundTasks, refactor docs structure. PR #10392 by @tiangolo. New docs at FastAPI Reference - Code API.⬆️ Upgrade compatibility with Pydantic v2.4, new renamed functions and JSON Schema input/output models with default values. PR #10344 by @tiangolo.
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.📌 Pin AnyIO to < 4.0.0 to handle an incompatibility while upgrading to Starlette 0.31.1. PR #10194 by @tiangolo.
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.✨ Add support for openapi_examples in all FastAPI parameters. PR #10152 by @tiangolo.
openapi_examples in all FastAPI parameters. PR #10152 by @tiangolo.
✨ Add support for disabling the separation of input and output JSON Schemas in OpenAPI with Pydantic v2 with separate_input_output_schemas=False. PR #
separate_input_output_schemas=False. PR #10145 by @tiangolo.
✏️ Fix typo in deprecation warnings in fastapi/params.py. PR #9854 by @russbiggs.
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.✨ Enable Pydantic's serialization mode for responses, add support for Pydantic's computed_field, better OpenAPI for response models, proper required a
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.🐛 Replace MultHostUrl to AnyUrl for compatibility with older versions of Pydantic v1. PR #9852 by @Kludex.
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.This version of FastAPI still supports Pydantic v1. And although Pydantic v1 will be deprecated at some point, ti will still be supported for a while.
✨ 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, ti 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:
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).
`shell pip install --pre --upgrade fastapi pydantic `
Install with:
pip install --pre --upgrade fastapi pydantic
✨ Beta support for Pydantic version 2 and OpenAPI 3.1.0 ✨
This is probably the last beta before the final release, probably in one or two days. So, please, test it out! 🤓 🚀 (before it's too late 😅).
The same details as in the previous beta releases below.
This has many features:
Check out the Pydantic migration guide: https://docs.pydantic.dev/dev-v2/migration/
This version of FastAPI still supports Pydantic v1.
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.
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 and code improvements, and then performance improvements. Although you will probably get nice performance improvements already.
There are tests for both Pydantic v1 and v2, and test coverage is kept at 100%.
You will probably still want to test this version in your code even if you don't plan to migrate to Pydantic v2 yet, to ensure that the changes of FastAPI don't break your app in any way.
If you install the beta, please let me know if everything is working or if you are having issues in this discussion: https://github.com/tiangolo/fastapi/discussions/9709
`shell pip install --pre --upgrade fastapi pydantic `
Install with:
pip install --pre --upgrade fastapi pydantic
✨ Beta support for Pydantic version 2 ✨
Pydantic v2 was released a few hours ago. 🎉
The final (non-beta) release of Pydantic v2 had a few minor changes. This beta 2 of FastAPI fixes those minor changes in FastAPI (thanks @Lancetnik! PR https://github.com/tiangolo/fastapi/pull/9771).
This means you can install Pydantic v2 stable, and try it with FastAPI 0.100.0 beta 2. 🎉
The next (and probably final) beta will include the latest changes in the main FastAPI branch, including OpenAPI 3.1.0. But meanwhile, with this quick fix beta you can start/keep trying FastAPI with the new Pydantic.
The same details as in the previous beta release below.
This has many features:
Check out the Pydantic migration guide: https://docs.pydantic.dev/dev-v2/migration/
This version of FastAPI still supports Pydantic v1.
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.
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 and code improvements, and then performance improvements. Although you will probably get nice performance improvements already.
There are tests for both Pydantic v1 and v2, and test coverage is kept at 100%.
You will probably still want to test this version in your code even if you don't plan to migrate to Pydantic v2 yet, to ensure that the changes of FastAPI don't break your app in any way.
If you install the beta, please let me know if everything is working or if you are having issues in this discussion: https://github.com/tiangolo/fastapi/discussions/9709
`shell pip install --pre --upgrade fastapi pydantic `
Install with:
pip install --pre --upgrade fastapi pydantic
✨ Beta support for Pydantic version 2 ✨
The internals of Pydantic v2 were rewritten in Rust and it's currently available in beta.
This has many features:
Check out the Pydantic migration guide: https://docs.pydantic.dev/dev-v2/migration/
This version of FastAPI still supports Pydantic v1.
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.
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 and code improvements, and then performance improvements. Although you will probably get nice performance improvements already.
There are tests for both Pydantic v1 and v2, and test coverage is kept at 100%.
You will probably still want to test this version in your code even if you don't plan to migrate to Pydantic v2 yet, to ensure that the changes of FastAPI don't break your app in any way.
If you install the beta, please let me know if everything is working or if you are having issues in this discussion: https://github.com/tiangolo/fastapi/discussions/9709
🐛 Fix JSON Schema accepting bools as valid JSON Schemas, e.g. additionalProperties: false. PR #9781 by @tiangolo.
Note: this is the last release before supporting Pydantic v2. You can try out the beta with support for Pydantic v2 now, a new beta supporting Pydanti
Note: this is the last release before supporting Pydantic v2. You can try out the beta with support for Pydantic v2 now, a new beta supporting Pydantic v2 with these same changes from this release will be available in the next hours/days. And the final version (0.100.0) with support for Pydantic v2 will be released in the next days (next week).
Now, back to this release (this one doesn't include the beta support for Pydantic v2).
This release has ✨ OpenAPI 3.1.0 ✨ 🎉
✨ 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: <a href="https://fastapi.tiangolo.com/tutorial/schema-extra-example/" class="external-link" target="_blank">Tutorial: Declare Request Example Data</a>.✨ 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.Note: please also help me try out the beta with support for Pydantic v2: https://github.com/tiangolo/fastapi/releases/tag/0.100.0-beta1
Note: please also help me try out the beta with support for Pydantic v2: https://github.com/tiangolo/fastapi/releases/tag/0.100.0-beta1
Now, back to this release (this one doesn't include the beta support for Pydantic v2).
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.✨ Add support for dependencies in WebSocket routes. PR #4534 by @paulo-raca.
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.🐛 Fix HTTPException header type annotations. PR #9648 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.⚡ Update create_cloned_field to use a global cache and improve startup performance. PR #4645 by @madkinsz and previous original PR by @huonw.
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.⬆️ Upgrade Starlette version to >=0.27.0 for a security release. PR #9541 by @tiangolo. Details on Starlette's security advisory.
>=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.🐛 Fix using Annotated in routers or path operations decorated multiple times. PR #9315 by @sharonyogev.
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 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! 🚀
🎨 Fix types for lifespan, upgrade Starlette to 0.26.1. PR #9245 by @tiangolo.
⬆ Upgrade python-multipart to support 0.0.6. PR #9212 by @musicinmybrain.
lifespan with state. PR #9239 by @tiangolo.pydantic to PyPI classifiers. PR #5914 by @yezz123.✨ Add support for lifespan async context managers (superseding startup and shutdown events). Initial PR #2944 by @uSpike.
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.
🚨 This is a security fix. Please upgrade as soon as possible.
⬆️ Upgrade Starlette version to 0.24.0 and refactor internals for compatibility. PR #5985 by @tiangolo.
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).⬆️ Upgrade Starlette range to allow 0.23.1. PR #5980 by @tiangolo.
docs/en/docs/project-generation.md. PR #5930 by @chandra-deb.zip-docs.sh internal script, remove extra space. PR #5931 by @JuanPerdomo00.⬆️ Bump Starlette from 0.22.0 to 0.23.0. Initial PR #5739 by @Kludex.
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.🐛 Ignore Response classes on return annotation. PR #5855 by @Kludex. See the new docs in the PR below.
docs/tr/docs/tutorial/first_steps.md. PR #5691 by @Kadermiyanyedi.✨ Add support for function return type annotations to declare the response_model. Initial PR #1436 by @uriyyo.
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.⬆ Bump Starlette to version 0.22.0 to fix bad encoding for query parameters in new TestClient. PR #5659 by @azogue.
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.There are some possible breaking changes in the TestClient usage, but @Kludex built bump-testclient to help you automatize migrating your tests. Make…
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.⬆ Add Python 3.11 to the officially supported versions. PR #5587 by @tiangolo.
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.Note: this release doesn't affect final users, it's mainly internal. It unlocks Pydanitc work with the integration that runs FastAPI's tests in Pydant
Note: this release doesn't affect final users, it's mainly internal. It unlocks Pydanitc work with the integration that runs FastAPI's tests in Pydantic's CI.
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.🐛 Fix support for strings in OpenAPI status codes: default, 1XX, 2XX, 3XX, 4XX, 5XX. PR #5187 by @JarroVGIT.
default, 1XX, 2XX, 3XX, 4XX, 5XX. PR #5187 by @JarroVGIT.⬆ Upgrade version required of Starlette from 0.19.1 to 0.20.4. Initial PR #4820 by @Kludex.
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-
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. 🔥
🚨 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. 🔥
🚨 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.✨ Add ReDoc warning when JS is disabled. PR #5074 by @evroon.
<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.🐛 Fix response_model not invalidating None. PR #2725 by @hukkin.
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.🐛 Fix jsonable_encoder using include and exclude parameters for non-Pydantic objects. PR #2606 by @xaviml.
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.🐛 Fix removing body from status codes that do not support it. PR #5145 by @tiangolo.
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:
✨ 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.⬆ Upgrade Starlette from 0.19.0 to 0.19.1. PR #4819 by @Kludex.
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.⬆ Upgrade Starlette from 0.18.0 to 0.19.0. PR #4488 by @Kludex.
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.⬆ Upgrade Starlette from 0.17.1 to 0.18.0. PR #4483 by @Kludex.
⬆️ Update ujson ranges for CVE-2021-45958. PR #4804 by @tiangolo.
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.🌐 Start Dutch translations. PR #4703 by @tiangolo.
✨ Add support for custom generate_unique_id_function and docs for generating clients. New docs: Advanced - Generate Clients. PR #4650 by @tiangolo.
generate_unique_id_function and docs for generating clients. New docs: Advanced - Generate Clients. PR #4650 by @tiangolo.✨ Include route in scope to allow middleware and other tools to extract its information. PR #4603 by @tiangolo.
One column per quarter.