Skip to content

chore(deps): update dependency fastapi to v0.100.0

mrph-bot requested to merge renovate/fastapi-0.x into main

This MR contains the following updates:

Package Change Age Adoption Passing Confidence
fastapi ==0.71.0 -> ==0.100.0 age adoption passing confidence

Release Notes

tiangolo/fastapi (fastapi)

v0.100.0

Compare Source

Support for Pydantic v2

Pydantic version 2 has the core re-written in Rust and includes a lot of improvements and features, for example:

  • Improved correctness in corner cases.
  • Safer types.
  • Better performance and less energy consumption.
  • Better extensibility.
  • etc.

...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.

Migration

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.

Pydantic v1

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%.

Changes
  • There are new parameter fields supported by Pydantic Field() for:

    • Path()
    • Query()
    • Header()
    • Cookie()
    • Body()
    • Form()
    • File()
  • The new parameter fields are:

    • default_factory
    • alias_priority
    • validation_alias
    • serialization_alias
    • discriminator
    • strict
    • multiple_of
    • allow_inf_nan
    • max_digits
    • decimal_places
    • json_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.

  • MR #​9816 by @​tiangolo, included all the work done (in multiple MRs) on the beta branch (main-pv2).

v0.99.1

Compare Source

Fixes
  • 🐛 Fix JSON Schema accepting bools as valid JSON Schemas, e.g. additionalProperties: false. MR #​9781 by @​tiangolo.
Docs

v0.99.0

Compare Source

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 🎉

Features
  • Add support for OpenAPI 3.1.0. MR #​9770 by @​tiangolo.

    • New support for documenting webhooks, read the new docs here: Advanced User Guide: OpenAPI Webhooks.
    • Upgrade OpenAPI 3.1.0, this uses JSON Schema 2020-12.
    • Upgrade Swagger UI to version 5.x.x, that supports OpenAPI 3.1.0.
    • Updated 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. MR #​9433 by @​cranium.

Docs
Translations
Internal

v0.98.0

Compare Source

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).

Features
Docs
Translations
Internal

v0.97.0

Compare Source

Features
Refactors
  • ️ Upgrade and fully migrate to Ruff, remove isort, includes a couple of tweaks suggested by the new version of Ruff. MR #​9660 by @​tiangolo.
  • ️ Update internal type annotations and upgrade mypy. MR #​9658 by @​tiangolo.
  • ️ Simplify AsyncExitStackMiddleware as without Python 3.6 AsyncExitStack is always available. MR #​9657 by @​tiangolo.
Upgrades
Internal
  • 💚 Update CI cache to fix installs when dependencies change. MR #​9659 by @​tiangolo.
  • ️ Separate requirements for development into their own requirements.txt files, they shouldn't be extras. MR #​9655 by @​tiangolo.

v0.96.1

Compare Source

Fixes
Upgrades
  • 📌 Update minimum version of Pydantic to >=1.7.4. This fixes an issue when trying to use an old version of Pydantic. MR #​9567 by @​Kludex.
Refactors
  • Remove media_type from ORJSONResponse as it's inherited from the parent class. MR #​5805 by @​Kludex.
  • Instantiate HTTPException only when needed, optimization refactor. MR #​5356 by @​pawamoy.
Docs
  • 🔥 Remove link to Pydantic's benchmark, as it was removed there. MR #​5811 by @​Kludex.
Translations
  • 🌐 Fix spelling in Indonesian translation of docs/id/docs/tutorial/index.md. MR #​5635 by @​purwowd.
  • 🌐 Add Russian translation for docs/ru/docs/tutorial/index.md. MR #​5896 by @​Wilidon.
  • 🌐 Add Chinese translations for docs/zh/docs/advanced/response-change-status-code.md and docs/zh/docs/advanced/response-headers.md. MR #​9544 by @​ChoyeonChern.
  • 🌐 Add Russian translation for docs/ru/docs/tutorial/schema-extra-example.md. MR #​9621 by @​Alexandrhub.
Internal

v0.96.0

Compare Source

Features
  • Update create_cloned_field to use a global cache and improve startup performance. MR #​4645 by @​madkinsz and previous original MR by @​huonw.
Docs
Translations
Internal

v0.95.2

Compare Source

Translations
Internal

v0.95.1

Compare Source

Fixes
Docs
  • 🌐 🔠 📄 🐢 Translate docs to Emoji 🥳 🎉 💥 🤯 🤯. MR #​5385 by @​LeeeeT.
  • 📝 Add notification message warning about old versions of FastAPI not supporting Annotated. MR #​9298 by @​grdworkin.
  • 📝 Fix typo in docs/en/docs/advanced/behind-a-proxy.md. MR #​5681 by @​Leommjr.
  • Fix wrong import from typing module in Persian translations for docs/fa/docs/index.md. MR #​6083 by @​Kimiaattaei.
  • ️ Fix format, remove unnecessary asterisks in docs/en/docs/help-fastapi.md. MR #​9249 by @​armgabrielyan.
  • Fix typo in docs/en/docs/tutorial/query-params-str-validations.md. MR #​9272 by @​nicornk.
  • Fix typo/bug in inline code example in docs/en/docs/tutorial/query-params-str-validations.md. MR #​9273 by @​tim-habitat.
  • Fix typo in docs/en/docs/tutorial/path-params-numeric-validations.md. MR #​9282 by @​aadarsh977.
  • Fix typo: 'wll' to 'will' in docs/en/docs/tutorial/query-params-str-validations.md. MR #​9380 by @​dasstyxx.
Translations
  • 🌐 Add French translation for docs/fr/docs/advanced/index.md. MR #​5673 by @​axel584.
  • 🌐 Add Portuguese translation for docs/pt/docs/tutorial/body-nested-models.md. MR #​4053 by @​luccasmmg.
  • 🌐 Add Russian translation for docs/ru/docs/alternatives.md. MR #​5994 by @​Xewus.
  • 🌐 Add Portuguese translation for docs/pt/docs/tutorial/extra-models.md. MR #​5912 by @​LorhanSohaky.
  • 🌐 Add Portuguese translation for docs/pt/docs/tutorial/path-operation-configuration.md. MR #​5936 by @​LorhanSohaky.
  • 🌐 Add Russian translation for docs/ru/docs/contributing.md. MR #​6002 by @​stigsanek.
  • 🌐 Add Korean translation for docs/tutorial/dependencies/classes-as-dependencies.md. MR #​9176 by @​sehwan505.
  • 🌐 Add Russian translation for docs/ru/docs/project-generation.md. MR #​9243 by @​Xewus.
  • 🌐 Add French translation for docs/fr/docs/index.md. MR #​9265 by @​frabc.
  • 🌐 Add Russian translation for docs/ru/docs/tutorial/query-params-str-validations.md. MR #​9267 by @​dedkot01.
  • 🌐 Add Russian translation for docs/ru/docs/benchmarks.md. MR #​9271 by @​Xewus.
Internal

v0.95.0

Compare Source

Highlights

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! 🚀

Features
  • Add support for PEP-593 Annotated for specifying dependencies and parameters. MR #​4871 by @​nzig.
Docs
  • 📝 Tweak tip recommending Annotated in docs. MR #​9270 by @​tiangolo.
  • 📝 Update order of examples, latest Python version first, and simplify version tab names. MR #​9269 by @​tiangolo.
  • 📝 Update all docs to use Annotated as the main recommendation, with new examples and tests. MR #​9268 by @​tiangolo.

v0.94.1

Compare Source

Fixes

v0.94.0

Compare Source

Upgrades
Docs
Translations
  • 🌐 Add Russian translation for docs/ru/docs/history-design-future.md. MR #​5986 by @​Xewus.
Internal

v0.93.0

Compare Source

Features
  • Add support for lifespan async context managers (superseding startup and shutdown events). Initial MR #​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
  • Fix formatting in docs/en/docs/tutorial/metadata.md for ReDoc. MR #​6005 by @​eykamp.
Translations
Internal

v0.92.0

Compare Source

🚨 This is a security fix. Please upgrade as soon as possible.

Upgrades
  • ️ Upgrade Starlette to 0.25.0. MR #​5996 by @​tiangolo.
    • This solves a vulnerability that could allow denial of service attacks by using many small multipart fields/files (parts), consuming high CPU and memory.
    • Only applications using forms (e.g. file uploads) could be affected.
    • For most cases, upgrading won't have any breaking changes.

v0.91.0

Compare Source

Upgrades
  • ️ Upgrade Starlette version to 0.24.0 and refactor internals for compatibility. MR #​5985 by @​tiangolo.
    • This can solve nuanced errors when using middlewares. Before Starlette 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 MR #​2017). Now the middleware class instances are created once, right before the first request (the first time the app is called).
    • If you depended on that previous behavior, you might need to update your code. As always, make sure your tests pass before merging the upgrade.

v0.90.1

Compare Source

Upgrades
Docs
Translations
  • 🌐 Add Russian translation for docs/ru/docs/tutorial/cookie-params.md. MR #​5890 by @​bnzone.
Internal

v0.90.0

Compare Source

Upgrades
Docs
Translations
Internal

v0.89.1

Compare Source

Fixes
  • 🐛 Ignore Response classes on return annotation. MR #​5855 by @​Kludex. See the new docs in the MR below.
Docs
Translations

v0.89.0

Compare Source

Features
  • Add support for function return type annotations to declare the response_model. Initial MR #​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:

  • Data validation
  • Automatic documentation
    • It could power automatic client generators
  • Data filtering

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
Translations
Internal

v0.88.0

Compare Source

Upgrades
  • Bump Starlette to version 0.22.0 to fix bad encoding for query parameters in new TestClient. MR #​5659 by @​azogue.
Docs
Translations
  • 🌐 Add Portuguese translation for docs/pt/docs/deployment/docker.md. MR #​5663 by @​ayr-ton.
Internal

v0.87.0

Compare Source

Highlights of this release:

  • Upgraded Starlette
    • Now the TestClient is based on HTTPX instead of Requests. 🚀
    • There are some possible breaking changes in the 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.
  • New WebSocketException (and docs), re-exported from Starlette.
  • Upgraded and relaxed dependencies for package extras all (including new Uvicorn version), when you install "fastapi[all]".
  • New docs about how to Help Maintain FastAPI.
Features
Docs
Translations
  • 🌐 Fix highlight lines for Japanese translation for docs/tutorial/query-params.md. MR #​2969 by @​ftnext.
  • 🌐 Add French translation for docs/fr/docs/advanced/additional-status-code.md. MR #​5477 by @​axel584.
  • 🌐 Add Portuguese translation for docs/pt/docs/tutorial/request-forms-and-files.md. MR #​5579 by @​batlopes.
  • 🌐 Add Japanese translation for docs/ja/docs/advanced/websockets.md. MR #​4983 by @​xryuseix.
Internal

v0.86.0

Compare Source

Features
Fixes
Docs
Translations
Internal

v0.85.2

Compare Source

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
Translations
  • 🌐 Add Portuguese translation for docs/pt/docs/tutorial/request-forms.md. MR #​4934 by @​batlopes.
  • 🌐 Add Chinese translation for docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md. MR #​4971 by @​Zssaer.
  • 🌐 Add French translation for deployment/deta.md. MR #​3692 by @​rjNemo.
  • 🌐 Update Chinese translation for docs/zh/docs/tutorial/query-params-str-validations.md. MR #​5255 by @​hjlarry.
  • 🌐 Add Chinese translation for docs/zh/docs/tutorial/sql-databases.md. MR #​4999 by @​Zssaer.
  • 🌐 Add Chinese translation for docs/zh/docs/advanced/wsgi.md. MR #​4505 by @​ASpathfinder.
  • 🌐 Add Portuguese translation for docs/pt/docs/tutorial/body-multiple-params.md. MR #​4111 by @​lbmendes.
  • 🌐 Add Portuguese translation for docs/pt/docs/tutorial/path-params-numeric-validations.md. MR #​4099 by @​lbmendes.
  • 🌐 Add French translation for deployment/versions.md. MR #​3690 by @​rjNemo.
  • 🌐 Add French translation for docs/fr/docs/help-fastapi.md. MR #​2233 by @​JulianMaurin.
  • 🌐 Fix typo in Chinese translation for docs/zh/docs/tutorial/security/first-steps.md. MR #​5530 by @​yuki1sntSnow.
  • 🌐 Add Portuguese translation for docs/pt/docs/tutorial/response-status-code.md. MR #​4922 by @​batlopes.
  • 🔧 Add config for Tamil translations. MR #​5563 by @​tiangolo.
Internal

v0.85.1

Compare Source

Fixes
  • 🐛 Fix support for strings in OpenAPI status codes: default, 1XX, 2XX, 3XX, 4XX, 5XX. MR #​5187 by @​JarroVGIT.
Docs
Internal

v0.85.0

Compare Source

Features
  • Upgrade version required of Starlette from 0.19.1 to 0.20.4. Initial MR #​4820 by @​Kludex.
    • This includes several bug fixes in Starlette.
  • ️ Upgrade Uvicorn max version in public extras: all. From >=0.12.0,<0.18.0 to >=0.12.0,<0.19.0. MR #​5401 by @​tiangolo.
Internal
  • ️ Upgrade dependencies for doc and dev internal extras: Typer, Uvicorn. MR #​5400 by @​tiangolo.
  • ️ Upgrade test dependencies: Black, HTTPX, databases, types-ujson. MR #​5399 by @​tiangolo.
  • ️ Upgrade mypy and tweak internal type annotations. MR #​5398 by @​tiangolo.
  • 🔧 Update test dependencies, upgrade Pytest, move dependencies from dev to test. MR #​5396 by @​tiangolo.

v0.84.0

Compare Source

Breaking Changes

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. 😅

  • 🔧 Update package metadata, drop support for Python 3.6, move build internals from Flit to Hatch. MR #​5240 by @​ofek.

v0.83.0

Compare Source

🚨 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.

Features
  • Add support in jsonable_encoder for include and exclude with dataclasses. MR #​4923 by @​DCsunset.
Fixes
  • 🐛 Fix RuntimeError raised when HTTPException has a status code with no content. MR #​5365 by @​iudeen.
  • 🐛 Fix empty reponse body when default status_code is empty but the a Response parameter with response.status_code is set. MR #​5360 by @​tmeckel.
Docs
Internal

v0.82.0

Compare Source

🚨 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.

Features
  • Export WebSocketState in fastapi.websockets. MR #​4376 by @​matiuszka.
  • Support Python internal description on Pydantic model's docstring. MR #​3032 by @​Kludex.
  • Update ORJSONResponse to support non str keys and serializing Numpy arrays. MR #​3892 by @​baby5.
Fixes
  • 🐛 Allow exit code for dependencies with yield to always execute, by removing capacity limiter for them, to e.g. allow closing DB connections without deadlocks. MR #​5122 by @​adriangb.
  • 🐛 Fix FastAPI People GitHub Action: set HTTPX timeout for GraphQL query request. MR #​5222 by @​iudeen.
  • 🐛 Make sure a parameter defined as required is kept required in OpenAPI even if defined as optional in another dependency. MR #​4319 by @​cd17822.
  • 🐛 Fix support for path parameters in WebSockets. MR #​3879 by @​davidbrochart.
Docs
Translations
Internal

v0.81.0

Compare Source

Features
  • Add ReDoc <noscript> warning when JS is disabled. MR #​5074 by @​evroon.
  • Add support for FrozenSet in parameters (e.g. query). MR #​2938 by @​juntatalor.
  • Allow custom middlewares to raise HTTPExceptions and propagate them. MR #​2036 by @​ghandic.
  • Preserve json.JSONDecodeError information when handling invalid JSON in request body, to support custom exception handlers that use its information. MR #​4057 by @​UKnowWhoIm.
Fixes
Docs
Translations
Internal

v0.80.0

Compare Source

Breaking Changes - Fixes

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()

@&#8203;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()

@&#8203;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()

@&#8203;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).

Fixes
  • Upgrade Swagger UI copy of oauth2-redirect.html to include fixes for flavors of authorization code flows in Swagger UI. MR #​3439 initial MR by @​koonpeng.
  • Strip empty whitespace from description extracted from docstrings. MR #​2821 by @​and-semakin.
  • 🐛 Fix cached dependencies when using a dependency in Security() and other places (e.g. Depends()) with different OAuth2 scopes. MR #​2945 by @​laggardkernel.
  • 🎨 Update type annotations for response_model, allow things like Union[str, None]. MR #​5294 by @​tiangolo.
Translations

v0.79.1

Compare Source

Fixes
  • 🐛 Fix jsonable_encoder using include and exclude parameters for non-Pydantic objects. MR #​2606 by @​xaviml.
  • 🐛 Fix edge case with repeated aliases names not shown in OpenAPI. MR #​2351 by @​klaa97.
  • 📝 Add misc dependency installs to tutorial docs. MR #​2126 by @​TeoZosa.
Docs
Translations
Internal

v0.79.0

Compare Source

Fixes - Breaking Changes
  • 🐛 Fix removing body from status codes that do not support it. MR #​5145 by @​tiangolo.
    • Setting status_code to 204, 304, or any code below 200 (1xx) will remove the body from the response.
    • This fixes an error in Uvicorn that otherwise would be thrown: RuntimeError: Response content longer than Content-Length.
    • This removes fastapi.openapi.constants.STATUS_CODES_WITH_NO_BODY, it is replaced by a function in utils.
Translations
Internal

v0.78.0

Compare Source

Features
  • 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. MR #​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()

@&#8203;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()

@&#8203;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()

@&#8203;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"}
Docs
Translations
Internal

v0.77.1

Compare Source

Upgrades
Docs
Translations
Internal

v0.77.0

Compare Source

Upgrades
  • Upgrade Starlette from 0.18.0 to 0.19.0. MR #​4488 by @​Kludex.
    • When creating an explicit JSONResponse the content argument is now required.
Docs
Translations

v0.76.0

Compare Source

Upgrades
Internal

v0.75.2

Compare Source

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.

Fixes
Upgrades
  • ️ Update ujson ranges for CVE-2021-45958. MR #​4804 by @​tiangolo.
  • ️ Upgrade dependencies upper range for extras "all". MR #​4803 by @​tiangolo.
  • Upgrade Swagger UI - swagger-ui-dist@4. This handles a security issue in Swagger UI itself where it could be possible to inject HTML into Swagger UI. Please upgrade as soon as you can, in particular if you expose your Swagger UI (/docs) publicly to non-expert users. MR #​4347 by @​RAlanWright.
Internal
  • 🔧 Update sponsors, add: ExoFlare, Ines Course; remove: Dropbase, Vim.so, Calmcode; update: Striveworks, TalkPython and TestDriven.io. MR #​4805 by @​tiangolo.
  • ️ Upgrade Codecov GitHub Action. MR #​4801 by @​tiangolo.

v0.75.1

Compare Source

Translations
Internal

v0.75.0

Compare Source

Features

v0.74.1

Compare Source

Features
  • Include route in scope to allow middleware and other tools to extract its information. MR #​4603 by @​tiangolo.

v0.74.0

Compare Source

Breaking Changes
  • Update internal AsyncExitStack to fix context for dependencies with yield. MR #​4575 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.

Features
  • The same MR #​4575 from above also fixes the contextvars context for the code before and after yield. This was the main objective of that MR.

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 MR description #​4575.

Internal

v0.73.0

Compare Source

Features
Docs
Fixes
Internal

v0.72.0

Compare Source

Features
Docs
Translations
Internal

Configuration

📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

Rebasing: Whenever MR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 Ignore: Close this MR and you won't be reminded about this update again.


  • If you want to rebase/retry this MR, check this box

This MR has been generated by Renovate Bot.

Edited by mrph-bot

Merge request reports