This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where comments have been removed, empty lines have been removed, content has been compressed (code blocks are separated by ⋮---- delimiter).

<file_summary>
This section contains a summary of this file.

<purpose>
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>

<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
  - File path as an attribute
  - Full contents of the file
</file_format>

<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
  original repository files, not this packed version.
- When processing this file, use the file path to distinguish
  between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
  the same level of security as you would the original repository.
</usage_guidelines>

<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: **/.git/**, **/.github/**, **/node_modules/**, **/vendor/**, **/third_party/**, **/external/**, **/libs/**, **/lib/**, **/bin/**, **/obj/**, **/build/**, **/dist/**, **/target/**, **/out/**, **/release/**, **/debug/**, **/wwwroot/**, **/public/**, **/assets/**, **/static/**, **/[tT]est/**, **/[tT]ests/**, **/__tests__/**, **/[lL]ogs/**, **/[mM]igrations/**, **/.vs/**, **/.vscode/**, **/.idea/**, **/.pnpm-store/**, **/.yarn/**, **/.npm/**, **/__pycache__/**, **/.pytest_cache/**, **/.mypy_cache/**, **/.gradle/**, **/.mvn/**, **/coverage/**, **/.coverage/**, **/reports/**, **/report/**, **/TestResults/**, **/tmp/**, **/temp/**, **/.tmp/**, **/.cache/**, **/.history/**, **/.DS_Store, **/Thumbs.db, **/*.log, **/*.out, **/*.err, **/*.trace, **/*.trc, **/*.tmp, **/*.cache, **/*.dmp, **/*.dump, **/*.core, **/*.binlog, **/*.ndjson, **/*.jsonl, **/*.csv, **/*.evtx, **/*.etl, **/*.access, **/*.error, **/*.exe, **/*.dll, **/*.so, **/*.dylib, **/*.bin, **/*.app, **/*.msi, **/*.apk, **/*.ipa, **/*.lib, **/*.a, **/*.o, **/*.obj, **/*.lo, **/*.lai, **/*.class, **/*.jar, **/*.war, **/*.ear, **/*.pdb, **/*.idb, **/*.ilk, **/*.nupkg, **/*.snupkg, **/*.gem, **/*.whl, **/*.egg, **/*.deb, **/*.rpm, **/*.zip, **/*.tar, **/*.gz, **/*.tgz, **/*.rar, **/*.bz2, **/*.xz, **/*.7z, **/*.lz, **/*.lzma, **/*.min.js, **/*.min.css, **/*.map, **/*.css, **/*.scss, **/*.sass, **/*.less, **/*.jpg, **/*.jpeg, **/*.png, **/*.gif, **/*.bmp, **/*.tif, **/*.tiff, **/*.webp, **/*.heif, **/*.heic, **/*.svg, **/*.eps, **/*.ai, **/*.raw, **/*.cr2, **/*.cr3, **/*.nef, **/*.arw, **/*.dng, **/*.orf, **/*.rw2, **/*.avif, **/*.apng, **/*.ico, **/*.psd, **/*.psb, **/*.xcf, **/*.hdr, **/*.exr, **/*.dcm, **/*.dicom, **/*.fits, **/*.ppm, **/*.pgm, **/*.pbm, **/*.j2k, **/*.jp2, **/*.pcx, **/*.tga, **/*.iff, **/*.sgi, **/*.ras, **/*.coverage, **/*.lcov, **/*.gcov, **/*.gcda, **/*.gcno, **/*.generated, **/*.g.cs, **/*.designer.cs, **/*.lock, **/*.lock.json, **/*.eot, **/*.ttf, **/*.woff, **/*.woff2, **/*.pfx, **/*.p12, **/*.cer, **/*.crt, **/*.key, **/*.editorconfig, **/*.tool-versions, **/*.onnx, **/*.pt, **/*.pth, **/*.h5, **/*.ckpt, **/*.sln, **/*.csproj, **/*.config, **/*.user, **/*.vsidx, **/*.v2, **/*.db*, **/.*ignore, **/.git*, **/*.config.*, **/BUILD, **/BUILD.bazel, **/*.bzl, **/pom.xml, **/build.gradle, **/settings.gradle, **/gradlew, **/gradlew.bat, **/CMakeLists.txt, **/Makefile, **/makefile, **/GNUmakefile, **/*.pdl, **/*.cddl, **/*.thrift, **/*.proto, **/*.avsc, **/*.smithy, .idea/, .vscode/, .eclipse/, .settings/, **/gen/**, **/generated/**, **/auto/**, **/out/**, **/build/**, **/dist/**, .github/, .gitlab/, .circleci/, .azure-pipelines/, **/fixtures/**, **/data/**, **/tests/**/statics/**, starlette/**, benchmarks/**, **/*.css, **/*.html, **/*.png, **/*.svg, **/*.lock, **/*.gitignore, **/*.cff, **/*.toml, **/*.txt
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Code comments have been removed from supported file types
- Empty lines have been removed from all files
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>

</file_summary>

<directory_structure>
docs/
  applications.md
  authentication.md
  background.md
  CNAME
  config.md
  contributing.md
  database.md
  early-hints.md
  endpoints.md
  exceptions.md
  graphql.md
  index.md
  lifespan.md
  middleware.md
  release-notes.md
  requests.md
  responses.md
  routing.md
  schemas.md
  server-push.md
  staticfiles.md
  templates.md
  testclient.md
  third-party-packages.md
  threadpool.md
  websockets.md
scripts/
  check
  docs
  install
  lint
  README.md
  sync-version
AGENTS.md
AI_POLICY.md
LICENSE.md
mkdocs.yml
README.md
</directory_structure>

<files>
This section contains the contents of the repository's files.

<file path="docs/applications.md">
??? abstract "API Reference"
    ::: starlette.applications.Starlette
        options:
            parameter_headings: false
            show_root_heading: true
            heading_level: 3
            filters:
                - "__init__"

Starlette includes an application class `Starlette` that nicely ties together all of
its other functionality.

```python
from contextlib import asynccontextmanager

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route, Mount, WebSocketRoute
from starlette.staticfiles import StaticFiles


def homepage(request):
    return PlainTextResponse('Hello, world!')

def user_me(request):
    username = "John Doe"
    return PlainTextResponse('Hello, %s!' % username)

def user(request):
    username = request.path_params['username']
    return PlainTextResponse('Hello, %s!' % username)

async def websocket_endpoint(websocket):
    await websocket.accept()
    await websocket.send_text('Hello, websocket!')
    await websocket.close()

@asynccontextmanager
async def lifespan(app):
    print('Startup')
    yield
    print('Shutdown')


routes = [
    Route('/', homepage),
    Route('/user/me', user_me),
    Route('/user/{username}', user),
    WebSocketRoute('/ws', websocket_endpoint),
    Mount('/static', StaticFiles(directory="static")),
]

app = Starlette(debug=True, routes=routes, lifespan=lifespan)
```

### Storing state on the app instance

You can store arbitrary extra state on the application instance, using the
generic `app.state` attribute.

For example:

```python
app.state.ADMIN_EMAIL = 'admin@example.org'
```

### Accessing the app instance

Where a `request` is available (i.e. endpoints and middleware), the app is available on `request.app`.
</file>

<file path="docs/authentication.md">
Starlette offers a simple but powerful interface for handling authentication
and permissions. Once you've installed `AuthenticationMiddleware` with an
appropriate authentication backend the `request.user` and `request.auth`
interfaces will be available in your endpoints.


```python
from starlette.applications import Starlette
from starlette.authentication import (
    AuthCredentials, AuthenticationBackend, AuthenticationError, SimpleUser
)
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.responses import PlainTextResponse
from starlette.routing import Route
import base64
import binascii


class BasicAuthBackend(AuthenticationBackend):
    async def authenticate(self, conn):
        if "Authorization" not in conn.headers:
            return

        auth = conn.headers["Authorization"]
        try:
            scheme, credentials = auth.split()
            if scheme.lower() != 'basic':
                return
            decoded = base64.b64decode(credentials).decode("ascii")
        except (ValueError, UnicodeDecodeError, binascii.Error) as exc:
            raise AuthenticationError('Invalid basic auth credentials')

        username, _, password = decoded.partition(":")
        # TODO: You'd want to verify the username and password here.
        return AuthCredentials(["authenticated"]), SimpleUser(username)


async def homepage(request):
    if request.user.is_authenticated:
        return PlainTextResponse('Hello, ' + request.user.display_name)
    return PlainTextResponse('Hello, you')

routes = [
    Route("/", endpoint=homepage)
]

middleware = [
    Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())
]

app = Starlette(routes=routes, middleware=middleware)
```

## Users

Once `AuthenticationMiddleware` is installed the `request.user` interface
will be available to endpoints or other middleware.

This interface should subclass `BaseUser`, which provides two properties,
as well as whatever other information your user model includes.

* `.is_authenticated`
* `.display_name`

Starlette provides two built-in user implementations: `UnauthenticatedUser()`,
and `SimpleUser(username)`.

## AuthCredentials

It is important that authentication credentials are treated as a separate concept
from users. An authentication scheme should be able to restrict or grant
particular privileges independently of the user identity.

The `AuthCredentials` class provides the basic interface that `request.auth`
exposes:

* `.scopes`

## Permissions

Permissions are implemented as an endpoint decorator, that enforces that the
incoming request includes the required authentication scopes.

```python
from starlette.authentication import requires


@requires('authenticated')
async def dashboard(request):
    ...
```

You can include either one or multiple required scopes:

```python
from starlette.authentication import requires


@requires(['authenticated', 'admin'])
async def dashboard(request):
    ...
```

By default 403 responses will be returned when permissions are not granted.
In some cases you might want to customize this, for example to hide information
about the URL layout from unauthenticated users.

```python
from starlette.authentication import requires


@requires(['authenticated', 'admin'], status_code=404)
async def dashboard(request):
    ...
```

!!! note
    The `status_code` parameter is not supported with WebSockets. The 403 (Forbidden)
    status code will always be used for those.

Alternatively you might want to redirect unauthenticated users to a different
page.

```python
from starlette.authentication import requires


async def homepage(request):
    ...


@requires('authenticated', redirect='homepage')
async def dashboard(request):
    ...
```

When redirecting users, the page you redirect them to will include the URL they originally requested at the `next` query param:

```python
from starlette.authentication import requires
from starlette.responses import RedirectResponse


@requires('authenticated', redirect='login')
async def admin(request):
    ...


async def login(request):
    if request.method == "POST":
        # Now that the user is authenticated,
        # we can send them to their original request destination
        if request.user.is_authenticated:
            next_url = request.query_params.get("next")
            if next_url:
                return RedirectResponse(next_url)
            return RedirectResponse("/")
```

For class-based endpoints, you should wrap the decorator
around a method on the class.

```python
from starlette.authentication import requires
from starlette.endpoints import HTTPEndpoint


class Dashboard(HTTPEndpoint):
    @requires("authenticated")
    async def get(self, request):
        ...
```

## Custom authentication error responses

You can customise the error response sent when a `AuthenticationError` is
raised by an auth backend:

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse


def on_auth_error(request: Request, exc: Exception):
    return JSONResponse({"error": str(exc)}, status_code=401)

app = Starlette(
    middleware=[
        Middleware(AuthenticationMiddleware, backend=BasicAuthBackend(), on_error=on_auth_error),
    ],
)
```
</file>

<file path="docs/background.md">
Starlette includes a `BackgroundTask` class for in-process background tasks.

A background task should be attached to a response, and will run only once
the response has been sent.

### Background Task

Used to add a single background task to a response.

Signature: `BackgroundTask(func, *args, **kwargs)`

```python
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.background import BackgroundTask


...

async def signup(request):
    data = await request.json()
    username = data['username']
    email = data['email']
    task = BackgroundTask(send_welcome_email, to_address=email)
    message = {'status': 'Signup successful'}
    return JSONResponse(message, background=task)

async def send_welcome_email(to_address):
    ...


routes = [
    Route('/user/signup', endpoint=signup, methods=['POST'])
]

app = Starlette(routes=routes)
```

### BackgroundTasks

Used to add multiple background tasks to a response.

Signature: `BackgroundTasks(tasks=[])`

```python
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.background import BackgroundTasks
from starlette.routing import Route

async def signup(request):
    data = await request.json()
    username = data['username']
    email = data['email']
    tasks = BackgroundTasks()
    tasks.add_task(send_welcome_email, to_address=email)
    tasks.add_task(send_admin_notification, username=username)
    message = {'status': 'Signup successful'}
    return JSONResponse(message, background=tasks)

async def send_welcome_email(to_address):
    ...

async def send_admin_notification(username):
    ...

routes = [
    Route('/user/signup', endpoint=signup, methods=['POST'])
]

app = Starlette(routes=routes)
```

!!! important
    The tasks are executed in order. In case one of the tasks raises
    an exception, the following tasks will not get the opportunity to be executed.
</file>

<file path="docs/CNAME">
www.starlette.io
</file>

<file path="docs/config.md">
Starlette encourages a strict separation of configuration from code,
following [the twelve-factor pattern][twelve-factor].

Configuration should be stored in environment variables, or in a `.env` file
that is not committed to source control.

```python title="main.py"
from sqlalchemy import create_engine
from starlette.applications import Starlette
from starlette.config import Config
from starlette.datastructures import CommaSeparatedStrings, Secret

# Config will be read from environment variables and/or ".env" files.
config = Config(".env")

DEBUG = config('DEBUG', cast=bool, default=False)
DATABASE_URL = config('DATABASE_URL')
SECRET_KEY = config('SECRET_KEY', cast=Secret)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=CommaSeparatedStrings)

app = Starlette(debug=DEBUG)
engine = create_engine(DATABASE_URL)
...
```

```shell title=".env"
# Don't commit this to source control.
# Eg. Include ".env" in your `.gitignore` file.
DEBUG=True
DATABASE_URL=postgresql://user:password@localhost:5432/database
SECRET_KEY=43n080musdfjt54t-09sdgr
ALLOWED_HOSTS=127.0.0.1, localhost
```

## Configuration precedence

The order in which configuration values are read is:

* From an environment variable.
* From the `.env` file.
* The default value given in `config`.

If none of those match, then `config(...)` will raise an error.

## Secrets

For sensitive keys, the `Secret` class is useful, since it helps minimize
occasions where the value it holds could leak out into tracebacks or
other code introspection.

To get the value of a `Secret` instance, you must explicitly cast it to a string.
You should only do this at the point at which the value is used.

```python
>>> from myproject import settings
>>> settings.SECRET_KEY
Secret('**********')
>>> str(settings.SECRET_KEY)
'98n349$%8b8-7yjn0n8y93T$23r'
```

!!! tip

    You can use `DatabaseURL` from `databases`
    package [here](https://github.com/encode/databases/blob/ab5eb718a78a27afe18775754e9c0fa2ad9cd211/databases/core.py#L420)
    to store database URLs and avoid leaking them in the logs.

## CommaSeparatedStrings

For holding multiple inside a single config key, the `CommaSeparatedStrings`
type is useful.

```python
>>> from myproject import settings
>>> print(settings.ALLOWED_HOSTS)
CommaSeparatedStrings(['127.0.0.1', 'localhost'])
>>> print(list(settings.ALLOWED_HOSTS))
['127.0.0.1', 'localhost']
>>> print(len(settings.ALLOWED_HOSTS))
2
>>> print(settings.ALLOWED_HOSTS[0])
'127.0.0.1'
```

## Reading or modifying the environment

In some cases you might want to read or modify the environment variables programmatically.
This is particularly useful in testing, where you may want to override particular
keys in the environment.

Rather than reading or writing from `os.environ`, you should use Starlette's
`environ` instance. This instance is a mapping onto the standard `os.environ`
that additionally protects you by raising an error if any environment variable
is set *after* the point that it has already been read by the configuration.

If you're using `pytest`, then you can setup any initial environment in
`tests/conftest.py`.

```python title="tests/conftest.py"
from starlette.config import environ

environ['DEBUG'] = 'TRUE'
```

## Reading prefixed environment variables

You can namespace the environment variables by setting `env_prefix` argument.

```python title="myproject/settings.py"
import os

from starlette.config import Config

os.environ['APP_DEBUG'] = 'yes'
os.environ['ENVIRONMENT'] = 'dev'

config = Config(env_prefix='APP_')

DEBUG = config('DEBUG') # lookups APP_DEBUG, returns "yes"
ENVIRONMENT = config('ENVIRONMENT') # lookups APP_ENVIRONMENT, raises KeyError as variable is not defined
```

## Custom encoding for environment files 

By default, Starlette reads environment files using UTF-8 encoding. 
You can specify a different encoding by setting `encoding` argument.

```python title="myproject/settings.py"
from starlette.config import Config

# Using custom encoding for .env file
config = Config(".env", encoding="latin-1")
```

## A full example

Structuring large applications can be complex. You need proper separation of
configuration and code, database isolation during tests, separate test and
production databases, etc...

Here we'll take a look at a complete example, that demonstrates how
we can start to structure an application.

First, let's keep our settings, our database table definitions, and our
application logic separated:

```python title="myproject/settings.py"
from starlette.config import Config
from starlette.datastructures import Secret

config = Config(".env")

DEBUG = config('DEBUG', cast=bool, default=False)
SECRET_KEY = config('SECRET_KEY', cast=Secret)

DATABASE_URL = config('DATABASE_URL')
```

```python title="myproject/tables.py"
import sqlalchemy

# Database table definitions.
metadata = sqlalchemy.MetaData()

organisations = sqlalchemy.Table(
    ...
)
```

```python title="myproject/app.py"
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.routing import Route

from myproject import settings


async def homepage(request):
    ...

routes = [
    Route("/", endpoint=homepage)
]

middleware = [
    Middleware(
        SessionMiddleware,
        secret_key=settings.SECRET_KEY,
    )
]

app = Starlette(debug=settings.DEBUG, routes=routes, middleware=middleware)
```

Now let's deal with our test configuration.
We'd like to create a new test database every time the test suite runs,
and drop it once the tests complete. We'd also like to ensure

```python title="tests/conftest.py"
from starlette.config import environ
from starlette.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy_utils import create_database, database_exists, drop_database

# This line would raise an error if we use it after 'settings' has been imported.
environ['DEBUG'] = 'TRUE'

from myproject import settings
from myproject.app import app
from myproject.tables import metadata


@pytest.fixture(autouse=True, scope="session")
def setup_test_database():
    """
    Create a clean test database every time the tests are run.
    """
    url = settings.DATABASE_URL
    engine = create_engine(url)
    assert not database_exists(url), 'Test database already exists. Aborting tests.'
    create_database(url)             # Create the test database.
    metadata.create_all(engine)      # Create the tables.
    yield                            # Run the tests.
    drop_database(url)               # Drop the test database.


@pytest.fixture()
def client():
    """
    Make a 'client' fixture available to test cases.
    """
    # Our fixture is created within a context manager. This ensures that
    # application lifespan runs for every test case.
    with TestClient(app) as test_client:
        yield test_client
```

[twelve-factor]: https://12factor.net/config
</file>

<file path="docs/contributing.md">
# Contributing

Thank you for being interested in contributing to Starlette.
There are many ways you can contribute to the project:

- Try Starlette and [report bugs/issues you find](https://github.com/Kludex/starlette/issues/new)
- [Implement new features](https://github.com/Kludex/starlette/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)
- [Review Pull Requests of others](https://github.com/Kludex/starlette/pulls)
- Write documentation
- Participate in discussions

## Reporting Bugs or Other Issues

Found something that Starlette should support?
Stumbled upon some unexpected behaviour?

Contributions should generally start out with [a discussion](https://github.com/Kludex/starlette/discussions).
Possible bugs may be raised as a "Potential Issue" discussion, feature requests may
be raised as an "Ideas" discussion. We can then determine if the discussion needs
to be escalated into an "Issue" or not, or if we'd consider a pull request.

Try to be as descriptive as you can and, in the case of a bug report,
provide as much information as possible like:

- OS platform
- Python version
- Installed dependencies and versions (`python -m pip freeze`)
- Code snippet
- Error traceback

You should always try to reduce any examples to the *simplest possible case*
that demonstrates the issue.

## Development

To start developing Starlette, create a **fork** of the
[Starlette repository](https://github.com/Kludex/starlette) on GitHub.

Then clone your fork with the following command replacing `YOUR-USERNAME` with
your GitHub username:

```shell
$ git clone https://github.com/YOUR-USERNAME/starlette
```

You can now install the project and its dependencies using:

```shell
$ cd starlette
$ scripts/install
```

## Testing and Linting

We use custom shell scripts to automate testing, linting,
and documentation building workflow.

To run the tests, use:

```shell
$ scripts/test
```

Any additional arguments will be passed to `pytest`. See the [pytest documentation](https://docs.pytest.org/en/latest/how-to/usage.html) for more information.

For example, to run a single test script:

```shell
$ scripts/test tests/test_application.py
```

To run the code auto-formatting:

```shell
$ scripts/lint
```

Lastly, to run code checks separately (they are also run as part of `scripts/test`), run:

```shell
$ scripts/check
```

## Documenting

Documentation pages are located under the `docs/` folder.

To run the documentation site locally (useful for previewing changes), use:

```shell
$ scripts/docs
```

## Resolving Build / CI Failures

Once you've submitted your pull request, the test suite will automatically run, and the results will show up in GitHub.
If the test suite fails, you'll want to click through to the "Details" link, and try to identify why the test suite failed.

<p align="center" style="margin: 0 0 10px">
  <img src="https://raw.githubusercontent.com/Kludex/starlette/main/docs/img/gh-actions-fail.png" alt='Failing PR commit status'>
</p>

Here are some common ways the test suite can fail:

### Check Job Failed

<p align="center" style="margin: 0 0 10px">
  <img src="https://raw.githubusercontent.com/Kludex/starlette/main/docs/img/gh-actions-fail-check.png" alt='Failing GitHub action lint job'>
</p>

This job failing means there is either a code formatting issue or a type-annotation issue.
You can look at the job output to figure out why it failed, or run the following within a shell:

```shell
$ scripts/check
```

It may be worth it to run `$ scripts/lint` to attempt auto-formatting the code
and if that job succeeds commit the changes.

### Docs Job Failed

This job failing means the documentation failed to build. This can happen for
a variety of reasons like invalid markdown or missing configuration within `mkdocs.yml`.

### Python 3.X Job Failed

<p align="center" style="margin: 0 0 10px">
  <img src="https://raw.githubusercontent.com/Kludex/starlette/main/docs/img/gh-actions-fail-test.png" alt='Failing GitHub action test job'>
</p>

This job failing means the unit tests failed or not all code paths are covered by unit tests.

If tests are failing you will see this message under the coverage report:

`=== 1 failed, 435 passed, 1 skipped, 1 xfailed in 11.09s ===`

If tests succeed but coverage doesn't reach our current threshold, you will see this
message under the coverage report:

`FAIL Required test coverage of 100% not reached. Total coverage: 99.00%`

## Releasing

*This section is targeted at Starlette maintainers.*

Before releasing a new version, create a pull request that includes:

- **An update to the changelog**:
    - We follow the format from [keepachangelog](https://keepachangelog.com/en/1.0.0/).
    - [Compare](https://github.com/Kludex/starlette/compare/) `main` with the tag of the latest release, and list all entries that are of interest to our users:
        - Things that **must** go in the changelog: added, changed, deprecated or removed features, and bug fixes.
        - Things that **should not** go in the changelog: changes to documentation, tests or tooling.
        - Try sorting entries in descending order of impact / importance.
        - Keep it concise and to-the-point. 🎯
- **A version bump**: see `__version__.py`.

For an example, see [#1600](https://github.com/Kludex/starlette/pull/1600).

Once the release PR is merged, create a
[new release](https://github.com/Kludex/starlette/releases/new) including:

- Tag version like `0.13.3`.
- Release title `Version 0.13.3`
- Description copied from the changelog.

Once created this release will be automatically uploaded to PyPI.
</file>

<file path="docs/database.md">
Starlette is not strictly tied to any particular database implementation.

You are free to use any async database library that you prefer. Some popular options include:

- [SQLAlchemy](https://www.sqlalchemy.org/) - The Python SQL toolkit with native async support (2.0+).
- [SQLModel](https://sqlmodel.tiangolo.com/) - SQL databases in Python, designed for simplicity, built on top of SQLAlchemy and Pydantic.
- [Tortoise ORM](https://tortoise.github.io/) - An easy-to-use asyncio ORM inspired by Django.
- [Piccolo](https://piccolo-orm.com/) - A fast, user-friendly ORM and query builder.

Refer to your chosen database library's documentation for specific connection and query patterns.
</file>

<file path="docs/early-hints.md">
Starlette supports [HTTP 103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103)
through the ASGI [`http.response.early_hint`](https://asgi.readthedocs.io/en/latest/extensions.html#early-hints)
extension. Early Hints let a client start loading resources while the endpoint prepares the final response.

### `Request.send_early_hints`

Used to send one or more `Link` header values before the final response. If the ASGI server does not support
Early Hints, this method does nothing.

Signature: `send_early_hints(link, *additional_links)`

* `link` - An [RFC 8288](https://www.rfc-editor.org/rfc/rfc8288.html) `Link` header value.
* `additional_links` - Additional `Link` header values.

```python
from __future__ import annotations

import anyio

from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import HTMLResponse, Response
from starlette.routing import Route


async def homepage(request: Request) -> HTMLResponse:
    await request.send_early_hints(
        "</static/style.css>; rel=preload; as=style",
        "</static/app.js>; rel=modulepreload",
    )

    await anyio.sleep(1)
    return HTMLResponse("""
        <!doctype html>
        <html lang="en">
            <head>
                <title>Early Hints</title>
                <link rel="stylesheet" href="/static/style.css">
                <script type="module" src="/static/app.js"></script>
            </head>
            <body><h1>Hello!</h1></body>
        </html>
    """)


async def stylesheet(request: Request) -> Response:
    return Response("body { font-family: sans-serif; }", media_type="text/css")


async def javascript(request: Request) -> Response:
    return Response(
        'document.querySelector("h1").textContent = "Hello from Starlette!";',
        media_type="text/javascript",
    )


app = Starlette(
    routes=[
        Route("/", endpoint=homepage),
        Route("/static/style.css", endpoint=stylesheet),
        Route("/static/app.js", endpoint=javascript),
    ]
)
```

The one-second sleep simulates slow work, such as a database query. You send the hints before this work so
the client can load the stylesheet and script while it waits. This example serves both assets through routes,
so you do not need to create separate static files.

The ASGI server is responsible for sending Early Hints to the client. For example, Hypercorn supports the
extension over HTTP/2 and HTTP/3. Browsers may ignore Early Hints, so the resources must still be referenced by
the final response.
</file>

<file path="docs/endpoints.md">
Starlette includes the classes `HTTPEndpoint` and `WebSocketEndpoint` that provide a class-based view pattern for
handling HTTP method dispatching and WebSocket sessions.

### HTTPEndpoint

The `HTTPEndpoint` class can be used as an ASGI application:

```python
from starlette.responses import PlainTextResponse
from starlette.endpoints import HTTPEndpoint


class App(HTTPEndpoint):
    async def get(self, request):
        return PlainTextResponse("Hello, world!")
```

If you're using a Starlette application instance to handle routing, you can
dispatch to an `HTTPEndpoint` class. Make sure to dispatch to the class itself,
rather than to an instance of the class:

```python
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.endpoints import HTTPEndpoint
from starlette.routing import Route


class Homepage(HTTPEndpoint):
    async def get(self, request):
        return PlainTextResponse("Hello, world!")

    async def query(self, request):
        return PlainTextResponse("Hello, query!")

class User(HTTPEndpoint):
    async def get(self, request):
        username = request.path_params['username']
        return PlainTextResponse(f"Hello, {username}")

routes = [
    Route("/", Homepage),
    Route("/{username}", User)
]

app = Starlette(routes=routes)
```

HTTP endpoint classes will respond with "405 Method not allowed" responses for any
request methods which do not map to a corresponding handler. A `get` handler also serves
`HEAD` requests, unless the endpoint defines its own `head` handler, so `HEAD` appears in the
`Allow` header of those 405 responses.

### WebSocketEndpoint

The `WebSocketEndpoint` class is an ASGI application that presents a wrapper around
the functionality of a `WebSocket` instance.

The ASGI connection scope is accessible on the endpoint instance via `.scope` and
has an attribute `encoding` which may optionally be set, in order to validate the expected websocket data in the `on_receive` method.

The encoding types are:

* `'json'`
* `'bytes'`
* `'text'`

There are three overridable methods for handling specific ASGI websocket message types:

* `async def on_connect(websocket, **kwargs)`
* `async def on_receive(websocket, data)`
* `async def on_disconnect(websocket, close_code)`

```python
from starlette.endpoints import WebSocketEndpoint


class App(WebSocketEndpoint):
    encoding = 'bytes'

    async def on_connect(self, websocket):
        await websocket.accept()

    async def on_receive(self, websocket, data):
        await websocket.send_bytes(b"Message: " + data)

    async def on_disconnect(self, websocket, close_code):
        pass
```

The `WebSocketEndpoint` can also be used with the `Starlette` application class:

```python
import uvicorn
from starlette.applications import Starlette
from starlette.endpoints import WebSocketEndpoint, HTTPEndpoint
from starlette.responses import HTMLResponse
from starlette.routing import Route, WebSocketRoute


html = """
<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
    </head>
    <body>
        <h1>WebSocket Chat</h1>
        <form action="" onsubmit="sendMessage(event)">
            <input type="text" id="messageText" autocomplete="off"/>
            <button>Send</button>
        </form>
        <ul id='messages'>
        </ul>
        <script>
            var ws = new WebSocket("ws://localhost:8000/ws");
            ws.onmessage = function(event) {
                var messages = document.getElementById('messages')
                var message = document.createElement('li')
                var content = document.createTextNode(event.data)
                message.appendChild(content)
                messages.appendChild(message)
            };
            function sendMessage(event) {
                var input = document.getElementById("messageText")
                ws.send(input.value)
                input.value = ''
                event.preventDefault()
            }
        </script>
    </body>
</html>
"""

class Homepage(HTTPEndpoint):
    async def get(self, request):
        return HTMLResponse(html)

class Echo(WebSocketEndpoint):
    encoding = "text"

    async def on_receive(self, websocket, data):
        await websocket.send_text(f"Message text was: {data}")

routes = [
    Route("/", Homepage),
    WebSocketRoute("/ws", Echo)
]

app = Starlette(routes=routes)
```
</file>

<file path="docs/exceptions.md">
Starlette allows you to install custom exception handlers to deal with
how you return responses when errors or handled exceptions occur.

```python
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import HTMLResponse


HTML_404_PAGE = ...
HTML_500_PAGE = ...


async def not_found(request: Request, exc: HTTPException):
    return HTMLResponse(content=HTML_404_PAGE, status_code=exc.status_code)

async def server_error(request: Request, exc: HTTPException):
    return HTMLResponse(content=HTML_500_PAGE, status_code=exc.status_code)


exception_handlers = {
    404: not_found,
    500: server_error
}

app = Starlette(routes=routes, exception_handlers=exception_handlers)
```

If `debug` is enabled and an error occurs, then instead of using the installed
500 handler, Starlette will respond with a traceback response.

```python
app = Starlette(debug=True, routes=routes, exception_handlers=exception_handlers)
```

As well as registering handlers for specific status codes, you can also
register handlers for classes of exceptions.

In particular you might want to override how the built-in `HTTPException` class
is handled. For example, to use JSON style responses:

```python
async def http_exception(request: Request, exc: HTTPException):
    return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)

exception_handlers = {
    HTTPException: http_exception
}
```

The `HTTPException` is also equipped with the `headers` argument. Which allows the propagation
of the headers to the response class:

```python
async def http_exception(request: Request, exc: HTTPException):
    return JSONResponse(
        {"detail": exc.detail},
        status_code=exc.status_code,
        headers=exc.headers
    )
```

You might also want to override how `WebSocketException` is handled:

```python
async def websocket_exception(websocket: WebSocket, exc: WebSocketException):
    await websocket.close(code=1008)

exception_handlers = {
    WebSocketException: websocket_exception
}
```

## Errors and handled exceptions

It is important to differentiate between handled exceptions and errors.

Handled exceptions do not represent error cases. They are coerced into appropriate
HTTP responses, which are then sent through the standard middleware stack. By default
the `HTTPException` class is used to manage any handled exceptions.

Errors are any other exception that occurs within the application. These cases
should bubble through the entire middleware stack as exceptions. Any error
logging middleware should ensure that it re-raises the exception all the
way up to the server.

In practical terms, the error handled used is `exception_handler[500]` or `exception_handler[Exception]`.
Both keys `500` and `Exception` can be used. See below:

```python
async def handle_error(request: Request, exc: HTTPException):
    # Perform some logic
    return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)

exception_handlers = {
    Exception: handle_error  # or "500: handle_error"
}
```

It's important to notice that in case a [`BackgroundTask`](background.md) raises an exception,
it will be handled by the `handle_error` function, but at that point, the response was already sent. In other words,
the response created by `handle_error` will be discarded. In case the error happens before the response was sent, then
it will use the response object - in the above example, the returned `JSONResponse`.

In order to deal with this behaviour correctly, the middleware stack of a
`Starlette` application is configured like this:

* `ServerErrorMiddleware` - Returns 500 responses when server errors occur.
* Installed middleware
* `ExceptionMiddleware` - Deals with handled exceptions, and returns responses.
* Router
* Endpoints

## HTTPException

The `HTTPException` class provides a base class that you can use for any handled exceptions.
The `ExceptionMiddleware` implementation defaults to returning plain-text HTTP responses for any `HTTPException`.

* `HTTPException(status_code, detail=None, headers=None)`

When `detail` is not provided, it defaults to the standard phrase for the status code. If no standard phrase exists,
it defaults to an empty string.

You should only raise `HTTPException` inside routing or endpoints.
Middleware classes should instead just return appropriate responses directly.

You can use an `HTTPException` on a WebSocket endpoint. In case it's raised before `websocket.accept()`
the connection is not upgraded to a WebSocket connection, and the proper HTTP response is returned.

```python
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.routing import WebSocketRoute
from starlette.websockets import WebSocket


async def websocket_endpoint(websocket: WebSocket):
    raise HTTPException(status_code=400, detail="Bad request")


app = Starlette(routes=[WebSocketRoute("/ws", websocket_endpoint)])
```

## WebSocketException

You can use the `WebSocketException` class to raise errors inside of WebSocket endpoints.

* `WebSocketException(code, reason=None)`

You can set any code valid as defined [in the specification](https://tools.ietf.org/html/rfc6455#section-7.4.1).
</file>

<file path="docs/graphql.md">
GraphQL support in Starlette was deprecated in version 0.15.0, and removed in version 0.17.0.

Although GraphQL support is no longer built in to Starlette, you can still use GraphQL with Starlette via 3rd party libraries. These libraries all have Starlette-specific guides to help you do just that:

- [Ariadne](https://ariadnegraphql.org/server/Integrations/starlette-integration)
- [`starlette-graphene3`](https://github.com/ciscorn/starlette-graphene3#example)
- [Strawberry](https://strawberry.rocks/docs/integrations/starlette)
- [`tartiflette-asgi`](https://tartiflette.github.io/tartiflette-asgi/usage/#starlette)
</file>

<file path="docs/index.md">
<p align="center">
  <img width="400px" src="/img/starlette.svg#only-light" alt="starlette"/>
  <img width="400px" src="/img/starlette_dark.svg#only-dark" alt="starlette"/>
</p>
<p align="center">
    <em>✨ The little ASGI framework that shines. ✨</em>
</p>
<p align="center">
<a href="https://github.com/Kludex/starlette/actions">
    <img src="https://github.com/Kludex/starlette/workflows/Test%20Suite/badge.svg" alt="Build Status">
</a>
<a href="https://pypi.org/project/starlette/">
    <img src="https://badge.fury.io/py/starlette.svg" alt="Package version">
</a>
<a href="https://pypi.org/project/starlette" target="_blank">
    <img src="https://img.shields.io/pypi/pyversions/starlette.svg?color=%2334D058" alt="Supported Python versions">
</a>
<a href="https://discord.gg/RxKUF5JuHs">
    <img src="https://img.shields.io/discord/1051468649518616576?logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2" alt="Discord">
</a>
</p>

---

**Documentation**: <a href="https://starlette.dev/" target="_blank">https://starlette.dev</a>

**Source Code**: <a href="https://github.com/Kludex/starlette" target="_blank">https://github.com/Kludex/starlette</a>

---

# Introduction

Starlette is a lightweight [ASGI][asgi] framework/toolkit,
which is ideal for building async web services in Python.

It is production-ready, and gives you the following:

* A lightweight, low-complexity HTTP web framework.
* WebSocket support.
* In-process background tasks.
* Startup and shutdown events.
* Test client built on `httpx2`.
* CORS, GZip, Static Files, Streaming responses.
* Session and Cookie support.
* 100% test coverage.
* 100% type annotated codebase.
* Few hard dependencies.
* Compatible with `asyncio` and `trio` backends.
* Great overall performance [against independent benchmarks][techempower].


## Sponsorship

Help us keep Starlette maintained and sustainable by [becoming a sponsor](https://github.com/sponsors/Kludex).

**Current sponsors:**

<div style="display: flex; flex-wrap: wrap; gap: 2rem; align-items: center; margin: 1rem 0;">
    <a href="https://fastapi.tiangolo.com">
        <img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI" style="height: 80px;">
    </a>
</div>

## Installation

```shell
pip install starlette
```

You'll also want to install an ASGI server, such as [uvicorn](https://uvicorn.dev) or any of the [other ASGI server implementations](https://asgi.readthedocs.io/en/latest/implementations.html#servers).

```shell
pip install uvicorn
```

## Example

```python title="main.py"
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route


async def homepage(request):
    return JSONResponse({'hello': 'world'})


app = Starlette(debug=True, routes=[
    Route('/', homepage),
])
```

Then run the application...

```shell
uvicorn main:app
```

## Dependencies

Starlette only requires `anyio`, and the following dependencies are optional:

* [`httpx2`][httpx2] - Required if you want to use the `TestClient`.
* [`jinja2`][jinja2] - Required if you want to use `Jinja2Templates`.
* [`opentelemetry-api`][opentelemetry-api] - Required for `OpenTelemetryMiddleware`.
* [`python-multipart`][python-multipart] - Required if you want to support form parsing, with `request.form()`.
* [`itsdangerous`][itsdangerous] - Required for `SessionMiddleware` support.
* [`pyyaml`][pyyaml] - Required for `SchemaGenerator` support.

You can install all of these with `pip install starlette[full]`.

## Framework or Toolkit

Starlette is designed to be used either as a complete framework, or as
an ASGI toolkit. You can use any of its components independently.

```python title="main.py"
from starlette.responses import PlainTextResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)
```

Run the `app` application in `main.py`:

```shell
$ uvicorn main:app
INFO: Started server process [11509]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```

Run uvicorn with `--reload` to enable auto-reloading on code changes.

## Modularity

The modularity that Starlette is designed on promotes building reusable
components that can be shared between any ASGI framework. This should enable
an ecosystem of shared middleware and mountable applications.

The clean API separation also means it's easier to understand each component
in isolation.

---

<p align="center"><i>Starlette is <a href="https://github.com/Kludex/starlette/blob/main/LICENSE.md">BSD licensed</a> code.<br/>Designed & crafted with care.</i></br>&mdash; ⭐️ &mdash;</p>

[asgi]: https://asgi.readthedocs.io/en/latest/
[httpx2]: https://pypi.org/project/httpx2/
[jinja2]: https://jinja.palletsprojects.com/
[opentelemetry-api]: https://opentelemetry.io/docs/languages/python/api/
[python-multipart]: https://multipart.fastapiexpert.com/
[itsdangerous]: https://itsdangerous.palletsprojects.com/
[sqlalchemy]: https://www.sqlalchemy.org
[pyyaml]: https://pyyaml.org/wiki/PyYAMLDocumentation
[techempower]: https://github.com/TechEmpower/FrameworkBenchmarks
</file>

<file path="docs/lifespan.md">
Starlette applications can register a lifespan handler for dealing with
code that needs to run before the application starts up, or when the application
is shutting down.

```python
import contextlib

from starlette.applications import Starlette


@contextlib.asynccontextmanager
async def lifespan(app):
    async with some_async_resource():
        print("Run at startup!")
        yield
        print("Run on shutdown!")


routes = [
    ...
]

app = Starlette(routes=routes, lifespan=lifespan)
```

Starlette will not start serving any incoming requests until the lifespan has been run.

The lifespan teardown will run once all connections have been closed, and
any in-process background tasks have completed.

Consider using [`anyio.create_task_group()`](https://anyio.readthedocs.io/en/stable/tasks.html)
for managing asynchronous tasks.

## Lifespan State

The lifespan has the concept of `state`, which is a dictionary that
can be used to share the objects between the lifespan, and the requests.

```python
import contextlib
from typing import AsyncIterator, TypedDict

import httpx
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import PlainTextResponse
from starlette.routing import Route


class State(TypedDict):
    http_client: httpx.AsyncClient


@contextlib.asynccontextmanager
async def lifespan(app: Starlette) -> AsyncIterator[State]:
    async with httpx.AsyncClient() as client:
        yield {"http_client": client}


async def homepage(request: Request) -> PlainTextResponse:
    client = request.state.http_client
    response = await client.get("https://www.example.com")
    return PlainTextResponse(response.text)


app = Starlette(
    lifespan=lifespan,
    routes=[Route("/", homepage)]
)
```

The `state` received on the requests is a **shallow** copy of the state received on the
lifespan handler.

## Accessing State

The state can be accessed using either attribute-style or dictionary-style syntax.

The dictionary-style syntax was introduced in Starlette 0.52.0 (January 2026), with the idea of
improving type safety when using the lifespan state, given that `Request` became a generic over
the state type.

```python
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import TypedDict

import httpx
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import PlainTextResponse
from starlette.routing import Route


class State(TypedDict):
    http_client: httpx.AsyncClient


@asynccontextmanager
async def lifespan(app: Starlette) -> AsyncIterator[State]:
    async with httpx.AsyncClient() as client:
        yield {"http_client": client}


async def homepage(request: Request[State]) -> PlainTextResponse:
    client = request.state["http_client"]

    reveal_type(client)  # Revealed type is 'httpx.AsyncClient'

    response = await client.get("https://www.example.com")
    return PlainTextResponse(response.text)

app = Starlette(lifespan=lifespan, routes=[Route("/", homepage)])
```

This also works with WebSockets:

```python
async def websocket_endpoint(websocket: WebSocket[State]) -> None:
    await websocket.accept()
    client = websocket.state["http_client"]
    response = await client.get("https://www.example.com")
    await websocket.send_text(response.text)
    await websocket.close()


app = Starlette(lifespan=lifespan, routes=[WebSocketRoute("/ws", websocket_endpoint)])
```

!!! note
    There were many attempts to make this work with attribute-style access instead of
    dictionary-style access, but none were satisfactory, given they would have been
    breaking changes, or there were typing limitations.

    For more details, see:

    - [@Kludex/starlette#issues/3005](https://github.com/Kludex/starlette/issues/3005)
    - [@python/typing#discussions/1457](https://github.com/python/typing/discussions/1457)
    - [@Kludex/starlette#pull/3036](https://github.com/Kludex/starlette/pull/3036)

## Running lifespan in tests

You should use `TestClient` as a context manager, to ensure that the lifespan is called.

```python
from example import app
from starlette.testclient import TestClient


def test_homepage():
    with TestClient(app) as client:
        # Application's lifespan is called on entering the block.
        response = client.get("/")
        assert response.status_code == 200

    # And the lifespan's teardown is run when exiting the block.
```
</file>

<file path="docs/middleware.md">
Starlette includes several middleware classes for adding behavior that is applied across
your entire application. These are all implemented as standard ASGI
middleware classes, and can be applied either to Starlette or to any other ASGI application.

## Using middleware

The Starlette application class allows you to include the ASGI middleware
in a way that ensures that it remains wrapped by the exception handler.

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware

routes = ...

# Ensure that all requests include an 'example.com' or
# '*.example.com' host header, and strictly enforce https-only access.
middleware = [
    Middleware(
        TrustedHostMiddleware,
        allowed_hosts=['example.com', '*.example.com'],
    ),
    Middleware(HTTPSRedirectMiddleware)
]

app = Starlette(routes=routes, middleware=middleware)
```

Every Starlette application automatically includes two pieces of middleware by default:

* `ServerErrorMiddleware` - Ensures that application exceptions may return a custom 500 page, or display an application traceback in DEBUG mode. This is *always* the outermost middleware layer.
* `ExceptionMiddleware` - Adds exception handlers, so that particular types of expected exception cases can be associated with handler functions. For example raising `HTTPException(status_code=404)` within an endpoint will end up rendering a custom 404 page.

Middleware is evaluated from top-to-bottom, so the flow of execution in our example
application would look like this:

* Middleware
    * `ServerErrorMiddleware`
    * `TrustedHostMiddleware`
    * `HTTPSRedirectMiddleware`
    * `ExceptionMiddleware`
* Routing
* Endpoint

The following middleware implementations are available in the Starlette package:

## OpenTelemetry

Creates an OpenTelemetry server span for every incoming HTTP request. The span follows the
OpenTelemetry HTTP semantic conventions, extracts distributed trace context from the request
headers, and uses the matched route template for its name and `http.route` attribute.

!!! warning "Experimental API"
    `OpenTelemetryMiddleware` is experimental. Its API and emitted telemetry may change in minor
    releases without a deprecation period.

Install the optional API dependency with `pip install opentelemetry-api`, or as part of
`pip install "starlette[full]"`. Starlette only uses the OpenTelemetry API. Your application
chooses and configures the SDK and exporter. If no tracer provider is configured, the middleware
skips tracing.

**Pydantic Logfire** configures a global OpenTelemetry provider. Add the middleware to enable
Starlette tracing:

```python
import logfire

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.opentelemetry import OpenTelemetryMiddleware

logfire.configure()

app = Starlette(middleware=[Middleware(OpenTelemetryMiddleware)])
```

The same applies to any standard OpenTelemetry SDK configuration:

```python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.opentelemetry import OpenTelemetryMiddleware

tracer_provider = TracerProvider()
tracer_provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(tracer_provider)

app = Starlette(middleware=[Middleware(OpenTelemetryMiddleware)])
```

You can create the app before you configure the global provider.

You can also wrap any ASGI application directly:

```python
from starlette.applications import Starlette
from starlette.middleware.opentelemetry import OpenTelemetryMiddleware

app = OpenTelemetryMiddleware(Starlette())
```

Multiple native middleware instances on the same request create only one span.

### Exclude URLs

Pass a comma-separated string or a sequence of regular expressions in `excluded_urls`. If any
expression matches the full request URL, the middleware does not create a span. This is useful for
health checks, readiness probes, and other high-volume endpoints that you do not need to trace.

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.opentelemetry import OpenTelemetryMiddleware
from starlette.requests import Request
from starlette.responses import PlainTextResponse
from starlette.routing import Route


async def homepage(request: Request) -> PlainTextResponse:
    return PlainTextResponse("Hello, world!")


app = Starlette(
    routes=[Route("/", homepage), Route("/health", homepage)],
    middleware=[
        Middleware(
            OpenTelemetryMiddleware,
            excluded_urls=r"/health$,/readiness$",
        )
    ],
)
```

## CORSMiddleware

Adds appropriate [CORS headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) to outgoing responses in order to allow cross-origin requests from browsers.

The default parameters used by the CORSMiddleware implementation are restrictive by default,
so you'll need to explicitly enable particular origins, methods, or headers, in order
for browsers to be permitted to use them in a Cross-Domain context.

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware

routes = ...

middleware = [
    Middleware(CORSMiddleware, allow_origins=['*'])
]

app = Starlette(routes=routes, middleware=middleware)
```

The following arguments are supported:

* `allow_origins` - A list of origins that should be permitted to make cross-origin requests. eg. `['https://example.org', 'https://www.example.org']`. You can use `['*']` to allow any origin.
* `allow_origin_regex` - A regex string to match against origins that should be permitted to make cross-origin requests. eg. `'https://[a-zA-Z0-9-]+\.example\.org'`. Avoid using `.*` or `.+` as they match URL special characters (`/`, `@`, `#`, `?`) and may result in overly permissive origin matching. Use specific character classes like `[a-zA-Z0-9-]+` instead.
* `allow_methods` - A list of HTTP methods that should be allowed for cross-origin requests. Defaults to `['GET']`. You can use `['*']` to allow all standard methods.
* `allow_headers` - A list of HTTP request headers that should be supported for cross-origin requests. Defaults to `[]`. You can use `['*']` to allow all headers. The `Accept`, `Accept-Language`, `Content-Language` and `Content-Type` headers are always allowed for CORS requests.
* `allow_credentials` - Indicate that cookies should be supported for cross-origin requests. Defaults to `False`. Also, `allow_origins`, `allow_methods` and `allow_headers` cannot be set to `['*']` for credentials to be allowed, all of them must be explicitly specified.
* `allow_private_network` - Indicates whether to accept cross-origin requests over a private network. Defaults to `False`.
* `expose_headers` - Indicate any response headers that should be made accessible to the browser. Defaults to `[]`.
* `max_age` - Sets a maximum time in seconds for browsers to cache CORS responses. Defaults to `600`.

The middleware responds to two particular types of HTTP request...

#### CORS preflight requests

These are any `OPTIONS` request with `Origin` and `Access-Control-Request-Method` headers.
In this case the middleware will intercept the incoming request and respond with
appropriate CORS headers, and either a 200 or 400 response for informational purposes.

#### Simple requests

Any request with an `Origin` header. In this case the middleware will pass the
request through as normal, but will include appropriate CORS headers on the response.

#### Private Network Access (PNA)

Private Network Access is a browser security feature that restricts websites from public networks from accessing servers on private networks.

When a website attempts to make such a cross-network request, the browser will send a `Access-Control-Request-Private-Network: true` header in the
pre-flight request. If the `allow_private_network` flag is set to `True`, the middleware will include the `Access-Control-Allow-Private-Network: true`
header in the response, allowing the request. If set to `False`, the middleware will return a 400 response, blocking the request.

### CORSMiddleware Global Enforcement

When using CORSMiddleware with your Starlette application, it's important to ensure that CORS headers are applied even to error responses generated by unhandled exceptions. The recommended solution is to wrap the entire Starlette application with CORSMiddleware. This approach guarantees that even if an exception is caught by ServerErrorMiddleware (or other outer error-handling middleware), the response will still include the proper `Access-Control-Allow-Origin` header.

For example, instead of adding CORSMiddleware as an inner `middleware` via the Starlette middleware parameter, you can wrap your application as follows:

```python
from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware

import uvicorn

app = Starlette()
app = CORSMiddleware(app=app, allow_origins=["*"])

# ... your routes and middleware configuration ...

if __name__ == '__main__':
    uvicorn.run(
        app,
        host='0.0.0.0',
        port=8000
    )
```

## SessionMiddleware

Adds signed cookie-based HTTP sessions. Session information is readable but not modifiable.

The session cookie is always set with the `"HttpOnly"` flag, preventing client-side JavaScript from accessing it.

Access or modify the session data using the `request.session` dictionary interface.

Changes to nested values are not tracked automatically. For example, `request.session["cart"].append(item)` does not mark the session as modified. Assign the updated value back to the session, such as `request.session["cart"] = cart`, to ensure the changes are saved.

The following arguments are supported:

* `secret_key` - Should be a random string.
* `session_cookie` - Defaults to "session".
* `max_age` - Session expiry time in seconds. Defaults to 2 weeks. If set to `None` then the cookie will last as long as the browser session.
* `same_site` - SameSite flag prevents the browser from sending session cookie along with cross-site requests. Defaults to `'lax'`.
* `path` - The path set for the session cookie. Defaults to `'/'`.
* `https_only` - Indicate that the `"Secure"` flag should be set (can be used with HTTPS only). Defaults to `False`. Set this to `True` in production to ensure the session cookie is only sent over HTTPS.
* `domain` - Domain of the cookie used to share cookie between subdomains or cross-domains. The browser defaults the domain to the same host that set the cookie, excluding subdomains ([reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#domain_attribute)).
* `partitioned` - Set the `Partitioned` flag when you write or clear the session cookie. Defaults to `False`. Set `https_only=True` when you enable it. For cross-site embeds, also set `same_site="none"`. This gives your embedded app a separate session for each top-level site ([reference](https://developer.mozilla.org/en-US/docs/Web/Privacy/Guides/Third-party_cookies/Partitioned_cookies)).


```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.sessions import SessionMiddleware

routes = ...

middleware = [
    Middleware(SessionMiddleware, secret_key=..., https_only=True)
]

app = Starlette(routes=routes, middleware=middleware)
```

## HTTPSRedirectMiddleware

Enforces that all incoming requests must either be `https` or `wss`. Any incoming
requests to `http` or `ws` will be redirected to the secure scheme instead.

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware

routes = ...

middleware = [
    Middleware(HTTPSRedirectMiddleware)
]

app = Starlette(routes=routes, middleware=middleware)
```

There are no configuration options for this middleware class.

## TrustedHostMiddleware

Enforces that all incoming requests have a correctly set `Host` header, in order
to guard against HTTP Host Header attacks.

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.trustedhost import TrustedHostMiddleware

routes = ...

middleware = [
    Middleware(TrustedHostMiddleware, allowed_hosts=['example.com', '*.example.com'])
]

app = Starlette(routes=routes, middleware=middleware)
```

The following arguments are supported:

* `allowed_hosts` - A list of domain names that should be allowed as hostnames. Wildcard
domains such as `*.example.com` are supported for matching subdomains. Use bracketed
notation for IPv6 addresses, such as `allowed_hosts=["[::1]"]`. To allow any hostname,
use `allowed_hosts=["*"]` or omit the middleware.
* `www_redirect` - If set to True, requests to non-www versions of the allowed hosts will be redirected to their www counterparts. Defaults to `True`.

If an incoming request does not validate correctly then a 400 response will be sent.

## RequestBodyLimitMiddleware

Limits the total size of incoming HTTP request bodies. The limit applies to the
raw body bytes, including multipart file data and multipart encoding overhead.
Requests that exceed the limit receive a `413 Content Too Large` response.

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.body_limit import RequestBodyLimitMiddleware


routes = ...

middleware = [
    Middleware(RequestBodyLimitMiddleware, max_body_size=10 * 1024 * 1024)
]

app = Starlette(routes=routes, middleware=middleware)
```

The following argument is supported:

* `max_body_size` - The non-negative maximum request body size in bytes.

The middleware uses `Content-Length` to reject an oversized body before reading
it when possible, and always counts the body bytes received from the ASGI server.
This also supports requests without `Content-Length` and prevents an understated
header from bypassing the limit.

## GZipMiddleware

Handles GZip responses for any request that includes `"gzip"` in the `Accept-Encoding` header.

The middleware will handle both standard and streaming responses.

??? info "Compression of streaming responses"
    On streaming responses, the middleware compresses and emits output for every chunk the application sends,
    so chunks reach the client as they are produced instead of waiting for the compressor's buffer to fill.

    This favors timely delivery over compression ratio: many small chunks compress less effectively than a few
    large ones. Batch the chunks you yield if you want to maximize compression.

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.gzip import GZipMiddleware


routes = ...

middleware = [
    Middleware(GZipMiddleware, minimum_size=1000, compresslevel=9)
]

app = Starlette(routes=routes, middleware=middleware)
```

The following arguments are supported:

* `minimum_size` - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to `500`.
* `compresslevel` - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to `9`. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes.
* `thread_minimum_size` - Compress body chunks at least this large in a worker thread, keeping the event loop responsive. Defaults to `131072` (128 KiB). Chunks below this size compress inline in at most a couple of milliseconds, while the fixed cost of dispatching to a worker thread would dominate.
* `exclude_content_types` - Content types that are never compressed. A response is excluded when its `Content-Type` media type equals one of these values, or matches a `type/*` entry like `"image/*"` - matching is case-insensitive and ignores parameters like `charset`. Defaults to `DEFAULT_EXCLUDED_CONTENT_TYPES` (importable, to extend rather than replace): `text/event-stream`, native gRPC (`application/grpc`, which also covers `application/grpc+proto` and other `application/grpc+...` subtypes), plus already-compressed formats - zip and gzip archives, common raster image types, `video/*`, `audio/*`, and WOFF fonts. `image/svg+xml` is deliberately not excluded, since SVG is text and compresses well.

The middleware won't GZip responses that already have a `Content-Encoding` set, to prevent them from being
encoded twice, partial content responses (status `206`), to keep range semantics
intact, or responses with a `Content-Type` in `exclude_content_types` - by default `text/event-stream`, to
avoid compressing server-sent events, and already-compressed formats, where compression wastes CPU for no
gain.

## BaseHTTPMiddleware

An abstract class that allows you to write ASGI middleware against a request/response
interface.

### Usage

To implement a middleware class using `BaseHTTPMiddleware`, you must override the
`async def dispatch(request, call_next)` method.

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware


class CustomHeaderMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        response.headers['Custom'] = 'Example'
        return response

routes = ...

middleware = [
    Middleware(CustomHeaderMiddleware)
]

app = Starlette(routes=routes, middleware=middleware)
```

If you want to provide configuration options to the middleware class you should
override the `__init__` method, ensuring that the first argument is `app`, and
any remaining arguments are optional keyword arguments. Make sure to set the `app`
attribute on the instance if you do this.

```python
class CustomHeaderMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, header_value='Example'):
        super().__init__(app)
        self.header_value = header_value

    async def dispatch(self, request, call_next):
        response = await call_next(request)
        response.headers['Custom'] = self.header_value
        return response


middleware = [
    Middleware(CustomHeaderMiddleware, header_value='Customized')
]

app = Starlette(routes=routes, middleware=middleware)
```

Middleware classes should not modify their state outside of the `__init__` method.
Instead you should keep any state local to the `dispatch` method, or pass it
around explicitly, rather than mutating the middleware instance.

### Limitations

Currently, the `BaseHTTPMiddleware` has some known limitations:

- Using `BaseHTTPMiddleware` will prevent changes to [`contextvars.ContextVar`](https://docs.python.org/3/library/contextvars.html#contextvars.ContextVar)s from propagating upwards. That is, if you set a value for a `ContextVar` in your endpoint and try to read it from a middleware you will find that the value is not the same value you set in your endpoint (see [this test](https://github.com/Kludex/starlette/blob/621abc747a6604825190b93467918a0ec6456a24/tests/middleware/test_base.py#L192-L223) for an example of this behavior). Importantly, this also means that if a `BaseHTTPMiddleware` is positioned earlier in the middleware stack, it will disrupt `contextvars` propagation for any subsequent Pure ASGI Middleware that relies on them.

To overcome these limitations, use [pure ASGI middleware](#pure-asgi-middleware), as shown below.

## Pure ASGI Middleware

The [ASGI spec](https://asgi.readthedocs.io/en/latest/) makes it possible to implement ASGI middleware using the ASGI interface directly, as a chain of ASGI applications that call into the next one. In fact, this is how middleware classes shipped with Starlette are implemented.

This lower-level approach provides greater control over behavior and enhanced interoperability across frameworks and servers. It also overcomes the [limitations of `BaseHTTPMiddleware`](#limitations).

### Writing pure ASGI middleware

The most common way to create an ASGI middleware is with a class.

```python
class ASGIMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        await self.app(scope, receive, send)
```

The middleware above is the most basic ASGI middleware. It receives a parent ASGI application as an argument for its constructor, and implements an `async __call__` method which calls into that parent application.

Some implementations such as [`asgi-cors`](https://github.com/simonw/asgi-cors/blob/10ef64bfcc6cd8d16f3014077f20a0fb8544ec39/asgi_cors.py) use an alternative style, using functions:

```python
import functools

def asgi_middleware():
    def asgi_decorator(app):

        @functools.wraps(app)
        async def wrapped_app(scope, receive, send):
            await app(scope, receive, send)

        return wrapped_app

    return asgi_decorator
```

In any case, ASGI middleware must be callables that accept three arguments: `scope`, `receive`, and `send`.

* `scope` is a dict holding information about the connection, where `scope["type"]` may be:
    * [`"http"`](https://asgi.readthedocs.io/en/latest/specs/www.html#http-connection-scope): for HTTP requests.
    * [`"websocket"`](https://asgi.readthedocs.io/en/latest/specs/www.html#websocket-connection-scope): for WebSocket connections.
    * [`"lifespan"`](https://asgi.readthedocs.io/en/latest/specs/lifespan.html#scope): for ASGI lifespan messages.
* `receive` and `send` can be used to exchange ASGI event messages with the ASGI server — more on this below. The type and contents of these messages depend on the scope type. Learn more in the [ASGI specification](https://asgi.readthedocs.io/en/latest/specs/index.html).

### Using pure ASGI middleware

Pure ASGI middleware can be used like any other middleware:

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware

from .middleware import ASGIMiddleware

routes = ...

middleware = [
    Middleware(ASGIMiddleware),
]

app = Starlette(..., middleware=middleware)
```

See also [Using middleware](#using-middleware).

### Type annotations

There are two ways of annotating a middleware: using Starlette itself or [`asgiref`](https://github.com/django/asgiref).

* Using Starlette: for most common use cases.

```python
from starlette.types import ASGIApp, Message, Scope, Receive, Send


class ASGIMiddleware:
    def __init__(self, app: ASGIApp) -> None:
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            return await self.app(scope, receive, send)

        async def send_wrapper(message: Message) -> None:
            # ... Do something
            await send(message)

        await self.app(scope, receive, send_wrapper)
```

* Using [`asgiref`](https://github.com/django/asgiref): for more rigorous type hinting.

```python
from asgiref.typing import ASGI3Application, ASGIReceiveCallable, ASGISendCallable, Scope
from asgiref.typing import ASGIReceiveEvent, ASGISendEvent


class ASGIMiddleware:
    def __init__(self, app: ASGI3Application) -> None:
        self.app = app

    async def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        async def send_wrapper(message: ASGISendEvent) -> None:
            # ... Do something
            await send(message)

        return await self.app(scope, receive, send_wrapper)
```

### Common patterns

#### Processing certain requests only

ASGI middleware can apply specific behavior according to the contents of `scope`.

For example, to only process HTTP requests, write this...

```python
class ASGIMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        ...  # Do something here!

        await self.app(scope, receive, send)
```

Likewise, WebSocket-only middleware would guard on `scope["type"] != "websocket"`.

The middleware may also act differently based on the request method, URL, headers, etc.

#### Reusing Starlette components

Starlette provides several data structures that accept the ASGI `scope`, `receive` and/or `send` arguments, allowing you to work at a higher level of abstraction. Such data structures include [`Request`](requests.md#request), [`Headers`](requests.md#headers), [`QueryParams`](requests.md#query-parameters), [`URL`](requests.md#url), etc.

For example, you can instantiate a `Request` to more easily inspect an HTTP request:

```python
from starlette.requests import Request

class ASGIMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] == "http":
            request = Request(scope)
            ... # Use `request.method`, `request.url`, `request.headers`, etc.

        await self.app(scope, receive, send)
```

You can also reuse [responses](responses.md), which are ASGI applications as well.

#### Sending eager responses

Inspecting the connection `scope` allows you to conditionally call into a different ASGI app. One use case might be sending a response without calling into the app.

As an example, this middleware uses a dictionary to perform permanent redirects based on the requested path. This could be used to implement ongoing support of legacy URLs in case you need to refactor route URL patterns.

```python
from starlette.datastructures import URL
from starlette.responses import RedirectResponse

class RedirectsMiddleware:
    def __init__(self, app, path_mapping: dict):
        self.app = app
        self.path_mapping = path_mapping

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        url = URL(scope=scope)

        if url.path in self.path_mapping:
            url = url.replace(path=self.path_mapping[url.path])
            response = RedirectResponse(url, status_code=301)
            await response(scope, receive, send)
            return

        await self.app(scope, receive, send)
```

Example usage would look like this:

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware

routes = ...

redirections = {
    "/v1/resource/": "/v2/resource/",
    # ...
}

middleware = [
    Middleware(RedirectsMiddleware, path_mapping=redirections),
]

app = Starlette(routes=routes, middleware=middleware)
```


#### Inspecting or modifying the request

Request information can be accessed or changed by manipulating the `scope`. For a full example of this pattern, see Uvicorn's [`ProxyHeadersMiddleware`](https://github.com/encode/uvicorn/blob/fd4386fefb8fe8a4568831a7d8b2930d5fb61455/uvicorn/middleware/proxy_headers.py) which inspects and tweaks the `scope` when serving behind a frontend proxy.

Besides, wrapping the `receive` ASGI callable allows you to access or modify the HTTP request body by manipulating [`http.request`](https://asgi.readthedocs.io/en/latest/specs/www.html#request-receive-event) ASGI event messages.

As an example, this middleware computes and logs the size of the incoming request body...

```python
class LoggedRequestBodySizeMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        body_size = 0

        async def receive_logging_request_body_size():
            nonlocal body_size

            message = await receive()
            assert message["type"] == "http.request"

            body_size += len(message.get("body", b""))

            if not message.get("more_body", False):
                print(f"Size of request body was: {body_size} bytes")

            return message

        await self.app(scope, receive_logging_request_body_size, send)
```

Likewise, WebSocket middleware may manipulate [`websocket.receive`](https://asgi.readthedocs.io/en/latest/specs/www.html#receive-receive-event) ASGI event messages to inspect or alter incoming WebSocket data.

For an example that changes the HTTP request body, see [`msgpack-asgi`](https://github.com/florimondmanca/msgpack-asgi).

#### Inspecting or modifying the response

Wrapping the `send` ASGI callable allows you to inspect or modify the HTTP response sent by the underlying application. To do so, react to [`http.response.start`](https://asgi.readthedocs.io/en/latest/specs/www.html#response-start-send-event) or [`http.response.body`](https://asgi.readthedocs.io/en/latest/specs/www.html#response-body-send-event) ASGI event messages.

As an example, this middleware adds some fixed extra response headers:

```python
from starlette.datastructures import MutableHeaders

class ExtraResponseHeadersMiddleware:
    def __init__(self, app, headers):
        self.app = app
        self.headers = headers

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            return await self.app(scope, receive, send)

        async def send_with_extra_headers(message):
            if message["type"] == "http.response.start":
                headers = MutableHeaders(scope=message)
                for key, value in self.headers:
                    headers.append(key, value)

            await send(message)

        await self.app(scope, receive, send_with_extra_headers)
```

See also [`asgi-logger`](https://github.com/Kludex/asgi-logger/blob/main/asgi_logger/middleware.py) for an example that inspects the HTTP response and logs a configurable HTTP access log line.

Likewise, WebSocket middleware may manipulate [`websocket.send`](https://asgi.readthedocs.io/en/latest/specs/www.html#send-send-event) ASGI event messages to inspect or alter outgoing WebSocket data.

Note that if you change the response body, you will need to update the response `Content-Length` header to match the new response body length. See [`brotli-asgi`](https://github.com/fullonic/brotli-asgi) for a complete example.

#### Passing information to endpoints

If you need to share information with the underlying app or endpoints, you may store it into the `scope` dictionary. Note that this is a convention -- for example, Starlette uses this to share routing information with endpoints -- but it is not part of the ASGI specification. If you do so, be sure to avoid conflicts by using keys that have low chances of being used by other middleware or applications.

For example, when including the middleware below, endpoints would be able to access `request.scope["asgi_transaction_id"]`.

```python
import uuid

class TransactionIDMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        scope["asgi_transaction_id"] = uuid.uuid4()
        await self.app(scope, receive, send)
```

#### Cleanup and error handling

You can wrap the application in a `try/except/finally` block or a context manager to perform cleanup operations or do error handling.

For example, the following middleware might collect metrics and process application exceptions...

```python
import time

class MonitoringMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        start = time.time()
        try:
            await self.app(scope, receive, send)
        except Exception as exc:
            ...  # Process the exception
            raise
        finally:
            end = time.time()
            elapsed = end - start
            ...  # Submit `elapsed` as a metric to a monitoring backend
```

See also [`timing-asgi`](https://github.com/steinnes/timing-asgi) for a full example of this pattern.

### Gotchas

#### ASGI middleware should be stateless

Because ASGI is designed to handle concurrent requests, any connection-specific state should be scoped to the `__call__` implementation. Not doing so would typically lead to conflicting variable reads/writes across requests, and most likely bugs.

As an example, this would conditionally replace the response body, if an `X-Mock` header is present in the response...

=== "✅ Do"

    ```python
    from starlette.datastructures import Headers

    class MockResponseBodyMiddleware:
        def __init__(self, app, content):
            self.app = app
            self.content = content

        async def __call__(self, scope, receive, send):
            if scope["type"] != "http":
                await self.app(scope, receive, send)
                return

            # A flag that we will turn `True` if the HTTP response
            # has the 'X-Mock' header.
            # ✅: Scoped to this function.
            should_mock = False

            async def maybe_send_with_mock_content(message):
                nonlocal should_mock

                if message["type"] == "http.response.start":
                    headers = Headers(raw=message["headers"])
                    should_mock = headers.get("X-Mock") == "1"
                    await send(message)

                elif message["type"] == "http.response.body":
                    if should_mock:
                        message = {"type": "http.response.body", "body": self.content}
                    await send(message)

            await self.app(scope, receive, maybe_send_with_mock_content)
    ```

=== "❌ Don't"

    ```python hl_lines="7-8"
    from starlette.datastructures import Headers

    class MockResponseBodyMiddleware:
        def __init__(self, app, content):
            self.app = app
            self.content = content
            # ❌: This variable would be read and written across requests!
            self.should_mock = False

        async def __call__(self, scope, receive, send):
            if scope["type"] != "http":
                await self.app(scope, receive, send)
                return

            async def maybe_send_with_mock_content(message):
                if message["type"] == "http.response.start":
                    headers = Headers(raw=message["headers"])
                    self.should_mock = headers.get("X-Mock") == "1"
                    await send(message)

                elif message["type"] == "http.response.body":
                    if self.should_mock:
                        message = {"type": "http.response.body", "body": self.content}
                    await send(message)

            await self.app(scope, receive, maybe_send_with_mock_content)
    ```

See also [`GZipMiddleware`](https://github.com/Kludex/starlette/blob/9ef1b91c9c043197da6c3f38aa153fd874b95527/starlette/middleware/gzip.py) for a full example implementation that navigates this potential gotcha.

### Further reading

This documentation should be enough to have a good basis on how to create an ASGI middleware.

Nonetheless, there are great articles about the subject:

- [Introduction to ASGI: Emergence of an Async Python Web Ecosystem](https://florimond.dev/en/posts/2019/08/introduction-to-asgi-async-python-web/)
- [How to write ASGI middleware](https://pgjones.dev/blog/how-to-write-asgi-middleware-2021/)

## Using middleware in other frameworks

To wrap ASGI middleware around other ASGI applications, you should use the
more general pattern of wrapping the application instance:

```python
app = TrustedHostMiddleware(app, allowed_hosts=['example.com'])
```

You can do this with a Starlette application instance too, but it is preferable
to use the `middleware=<List of Middleware instances>` style, as it will:

* Ensure that everything remains wrapped in a single outermost `ServerErrorMiddleware`.
* Preserves the top-level `app` instance.

## Applying middleware to groups of routes

Middleware can also be added to `Mount` instances, which allows you to apply middleware to a group of routes or a sub-application:

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.gzip import GZipMiddleware
from starlette.routing import Mount, Route


routes = [
    Mount(
        "/",
        routes=[
            Route(
                "/example",
                endpoint=...,
            )
        ],
        middleware=[Middleware(GZipMiddleware)]
    )
]

app = Starlette(routes=routes)
```

Note that middleware used in this way is *not* wrapped in exception handling middleware like the middleware applied to the `Starlette` application is.
This is often not a problem because it only applies to middleware that inspect or modify the `Response`, and even then you probably don't want to apply this logic to error responses.
If you do want to apply the middleware logic to error responses only on some routes you have a couple of options:

* Add an `ExceptionMiddleware` onto the `Mount`
* Add a `try/except` block to your middleware and return an error response from there
* Split up marking and processing into two middlewares, one that gets put on `Mount` which marks the response as needing processing (for example by setting `scope["log-response"] = True`) and another applied to the `Starlette` application that does the heavy lifting.

The `Route`/`WebSocket` class also accepts a `middleware` argument, which allows you to apply middleware to a single route:

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.gzip import GZipMiddleware
from starlette.routing import Route


routes = [
    Route(
        "/example",
        endpoint=...,
        middleware=[Middleware(GZipMiddleware)]
    )
]

app = Starlette(routes=routes)
```

You can also apply middleware to the `Router` class, which allows you to apply middleware to a group of routes:

```python
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.gzip import GZipMiddleware
from starlette.routing import Route, Router


routes = [
    Route("/example", endpoint=...),
    Route("/another", endpoint=...),
]

router = Router(routes=routes, middleware=[Middleware(GZipMiddleware)])
```

## Third party middleware

#### [asgi-auth-github](https://github.com/simonw/asgi-auth-github)

This middleware adds authentication to any ASGI application, requiring users to sign in
using their GitHub account (via [OAuth](https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/)).
Access can be restricted to specific users or to members of specific GitHub organizations or teams.

#### [asgi-csrf](https://github.com/simonw/asgi-csrf)

Middleware for protecting against CSRF attacks. This middleware implements the Double Submit Cookie pattern, where a cookie is set, then it is compared to a csrftoken hidden form field or an `x-csrftoken` HTTP header.

#### [AuthlibMiddleware](https://github.com/aogier/starlette-authlib)

A drop-in replacement for Starlette session middleware, using [authlib's jwt](https://docs.authlib.org/en/latest/jose/jwt.html)
module.

#### [BugsnagMiddleware](https://github.com/ashinabraham/starlette-bugsnag)

A middleware class for logging exceptions to [Bugsnag](https://www.bugsnag.com/).

#### [CSRFMiddleware](https://github.com/frankie567/starlette-csrf)

Middleware for protecting against CSRF attacks. This middleware implements the Double Submit Cookie pattern, where a cookie is set, then it is compared to an `x-csrftoken` HTTP header.

#### [EarlyDataMiddleware](https://github.com/HarrySky/starlette-early-data)

Middleware and decorator for detecting and denying [TLSv1.3 early data](https://tools.ietf.org/html/rfc8470) requests.

#### [PrometheusMiddleware](https://github.com/perdy/starlette-prometheus)

A middleware class for capturing Prometheus metrics related to requests and responses, including in progress requests, timing...

#### [ProxyHeadersMiddleware](https://github.com/encode/uvicorn/blob/main/uvicorn/middleware/proxy_headers.py)

Uvicorn includes a middleware class for determining the client IP address,
when proxy servers are being used, based on the `X-Forwarded-Proto` and `X-Forwarded-For` headers. For more complex proxy configurations, you might want to adapt this middleware.

#### [RateLimitMiddleware](https://github.com/abersheeran/asgi-ratelimit)

A rate limit middleware. Regular expression matches url; flexible rules; highly customizable. Very easy to use.

#### [RequestIdMiddleware](https://github.com/snok/asgi-correlation-id)

A middleware class for reading/generating request IDs and attaching them to application logs.

#### [RollbarMiddleware](https://docs.rollbar.com/docs/starlette)

A middleware class for logging exceptions, errors, and log messages to [Rollbar](https://www.rollbar.com).

#### [StarletteOpentracing](https://github.com/acidjunk/starlette-opentracing)

A middleware class that emits tracing info to [OpenTracing.io](https://opentracing.io/) compatible tracers and
can be used to profile and monitor distributed applications.

#### [SecureCookiesMiddleware](https://github.com/thearchitector/starlette-securecookies)

Customizable middleware for adding automatic cookie encryption and decryption to Starlette applications, with
extra support for existing cookie-based middleware.

#### [TimingMiddleware](https://github.com/steinnes/timing-asgi)

A middleware class to emit timing information (cpu and wall time) for each request which
passes through it.  Includes examples for how to emit these timings as statsd metrics.

#### [WSGIMiddleware](https://github.com/abersheeran/a2wsgi)

A middleware class in charge of converting a WSGI application into an ASGI one.
</file>

<file path="docs/release-notes.md">
---
toc_depth: 2
---

## 1.10.0 (October 24, 2026)

#### Changed

* Compare multidicts such as `FormData` and `QueryParams` by key while keeping the order of values under a repeated key, so `FormData` with repeated uploads no longer raises `TypeError`. `QueryParams("a=1&a=2")` and `QueryParams("a=2&a=1")` are no longer equal [#3619](https://github.com/Kludex/starlette/pull/3619).
* Build URL-encoded form fields in the parser callbacks, lowering memory and CPU usage for forms with many fields [#3724](https://github.com/Kludex/starlette/pull/3724).
* Compare `Match` members by identity during routing [#3665](https://github.com/Kludex/starlette/pull/3665) and [#3722](https://github.com/Kludex/starlette/pull/3722).

#### Deprecated

* Deprecate `starlette.formparsers.FormMessage`, which is no longer used [#3724](https://github.com/Kludex/starlette/pull/3724).

#### Fixed

* Parse the last URL-encoded form field when the request stream ends without an empty chunk [#3599](https://github.com/Kludex/starlette/pull/3599).
* Keep path parameter values that look like another placeholder in `url_path_for()` [#3725](https://github.com/Kludex/starlette/pull/3725).
* Default omitted `http.response.start` headers in `BaseHTTPMiddleware`, `GZipMiddleware` and `SessionMiddleware` instead of raising `KeyError` [#3721](https://github.com/Kludex/starlette/pull/3721).
* Clear the traceback of handled exceptions, so reused exception instances no longer keep per-request objects alive [#3205](https://github.com/Kludex/starlette/pull/3205).
* Strip only one pair of matching outer quotes from `Config` env file values [#3720](https://github.com/Kludex/starlette/pull/3720).
* Strip `root_path` from `PATH_INFO` only at a path segment boundary in `WSGIMiddleware` [#3718](https://github.com/Kludex/starlette/pull/3718).
* Report NaN and infinity correctly in `FloatConvertor.to_string()` [#3716](https://github.com/Kludex/starlette/pull/3716).
* Ignore `Range` on requests other than `GET` and `HEAD` in `FileResponse` [#3679](https://github.com/Kludex/starlette/pull/3679).

## 1.9.0 (October 18, 2026)

#### Changed

* Stream `TestClient` response bodies, so `client.stream()` returns before the application finishes. Closing an unfinished streamed response now cancels the application [#3491](https://github.com/Kludex/starlette/pull/3491).

#### Fixed

* Percent-encode `?`, `#`, `\` and a leading `//` in the request path when building `request.url`, and `\` and a leading `//` in `url_path_for` [#3671](https://github.com/Kludex/starlette/pull/3671).
* Use the byte length for `Content-Length` when the response body is a typed or multidimensional `memoryview` [#3622](https://github.com/Kludex/starlette/pull/3622).
* Include `HEAD` in the `Allow` header of `HTTPEndpoint` 405 responses when `GET` is defined [#3585](https://github.com/Kludex/starlette/pull/3585).
* Match host names case-insensitively in `Host` routing and `TrustedHostMiddleware` [#3542](https://github.com/Kludex/starlette/pull/3542).
* Preserve every existing `Vary` header in `MutableHeaders.add_vary_header()`, used by `GZipMiddleware` and `SessionMiddleware` [#3675](https://github.com/Kludex/starlette/pull/3675).

## 1.8.0 (October 13, 2026)

This release drops Python 3.10 support and adds HTTP 103 Early Hints.

#### Added

* Add `Request.send_early_hints()` for HTTP 103 Early Hints through the ASGI `http.response.early_hint` extension [#3435](https://github.com/Kludex/starlette/pull/3435).

#### Changed

* Require Python 3.11 or later, dropping support for Python 3.10 [#3592](https://github.com/Kludex/starlette/pull/3592).
* Exclude native gRPC media types (`application/grpc` and `application/grpc+...`) from `GZipMiddleware` compression by default [#3565](https://github.com/Kludex/starlette/pull/3565).
* Send `http.response.start` immediately in `GZipMiddleware` for responses with an existing `Content-Encoding`, status `206`, or an excluded content type, instead of waiting for the first body chunk [#3631](https://github.com/Kludex/starlette/pull/3631).
* Resolve the multipart charset once per request instead of once per field [#3618](https://github.com/Kludex/starlette/pull/3618).

#### Fixed

* Preserve response trailers through `GZipMiddleware` [#3565](https://github.com/Kludex/starlette/pull/3565).
* Stop `FileResponse` transfers when the client disconnects [#3523](https://github.com/Kludex/starlette/pull/3523).
* Stop multipart range responses when the file ends before a range is complete, instead of looping forever [#3583](https://github.com/Kludex/starlette/pull/3583).
* Ignore `Range` when `If-Range` contains a weak ETag [#3567](https://github.com/Kludex/starlette/pull/3567).
* Include `Allow: GET, HEAD` in `StaticFiles` `405` responses [#3640](https://github.com/Kludex/starlette/pull/3640).
* Close `Request.stream()` generators deterministically, avoiding "Exception ignored" errors with stacked `BaseHTTPMiddleware` [#3628](https://github.com/Kludex/starlette/pull/3628).
* Add `Vary: Cookie` when `Session.pop()` removes an existing key [#3186](https://github.com/Kludex/starlette/pull/3186).
* Emit `Max-Age=0` on the session cookie when `SessionMiddleware` uses `max_age=0` [#3651](https://github.com/Kludex/starlette/pull/3651).
* Bracket IPv6 hostnames in `URL.replace()` [#3617](https://github.com/Kludex/starlette/pull/3617).

## 1.7.0 (September 23, 2026)

This release adds experimental OpenTelemetry tracing and requires AnyIO 4.

!!! warning "OpenTelemetryMiddleware is experimental"
    Its API and emitted telemetry may change in minor releases without a deprecation period
    [#3574](https://github.com/Kludex/starlette/pull/3574).

#### Added

* Add experimental `OpenTelemetryMiddleware` for HTTP server spans, with URL exclusions and custom tracer providers [#3438](https://github.com/Kludex/starlette/pull/3438), [#3463](https://github.com/Kludex/starlette/pull/3463), and [#3520](https://github.com/Kludex/starlette/pull/3520).
* Expose the matched route through `scope["route"]` [#3438](https://github.com/Kludex/starlette/pull/3438).
* Support the `QUERY` HTTP method in `HTTPEndpoint`, CORS, and OpenAPI 3.2 schema generation [#3489](https://github.com/Kludex/starlette/pull/3489).
* Capture HTTP response trailers in `TestClient` and expose them through `response.extensions["http.response.trailers"]` [#3563](https://github.com/Kludex/starlette/pull/3563).
* Support partitioned cookies in `SessionMiddleware` [#3510](https://github.com/Kludex/starlette/pull/3510).
* Add `partitioned` to `Response.delete_cookie()` on Python 3.14 and later [#3376](https://github.com/Kludex/starlette/pull/3376).
* Support IPv6 hosts in `TrustedHostMiddleware` and `TestClient` [#3471](https://github.com/Kludex/starlette/pull/3471).
* Support Python 3.15 [#3508](https://github.com/Kludex/starlette/pull/3508).

#### Changed

* Require `anyio>=4.0.0,<5`, dropping support for AnyIO 3 [#3512](https://github.com/Kludex/starlette/pull/3512).
* Raise `WebSocketDisconnected`, a `RuntimeError` subclass, for disconnected WebSocket operations [#2767](https://github.com/Kludex/starlette/pull/2767).
* Accept `Collection[str]` in `CORSMiddleware` configuration annotations, including sets and frozensets [#3518](https://github.com/Kludex/starlette/pull/3518).

#### Fixed

* Run background tasks only after the response is sent when using `BaseHTTPMiddleware` [#3476](https://github.com/Kludex/starlette/pull/3476).
* Return `400` for invalid multipart parser input [#3492](https://github.com/Kludex/starlette/pull/3492).
* Include `Vary: Origin` on all normal CORS responses and vary preflight responses by all request headers that affect them [#3516](https://github.com/Kludex/starlette/pull/3516) and [#3517](https://github.com/Kludex/starlette/pull/3517).
* Handle malformed `Host` headers and IPv6 authorities consistently across URL construction, host routing, and redirect middleware [#3472](https://github.com/Kludex/starlette/pull/3472).
* Ignore `Range` headers when `FileResponse` has a status other than `200`, preserving its status and full body [#3568](https://github.com/Kludex/starlette/pull/3568).
* Handle standalone `If-None-Match: *` in `StaticFiles` [#3201](https://github.com/Kludex/starlette/pull/3201).
* Reject WebSocket requests to `StaticFiles` without raising an assertion error [#3532](https://github.com/Kludex/starlette/pull/3532).
* Persist session mutations made with `popitem()` and `|=` [#3436](https://github.com/Kludex/starlette/pull/3436).
* Handle empty and absent payloads in `WebSocketEndpoint.decode()` [#3372](https://github.com/Kludex/starlette/pull/3372).
* Implement `identity` on `SimpleUser` and `UnauthenticatedUser` [#3271](https://github.com/Kludex/starlette/pull/3271).
* Allow `HTTPException` to use non-standard status codes without an explicit `detail` [#3545](https://github.com/Kludex/starlette/pull/3545).
* Avoid deprecated AnyIO imports in `TestClient` and add explicit imports in `WSGIMiddleware` for AnyIO 4.15 compatibility [#3498](https://github.com/Kludex/starlette/pull/3498) and [#3501](https://github.com/Kludex/starlette/pull/3501).
* Offload debug traceback rendering to a worker thread in `ServerErrorMiddleware` [#2858](https://github.com/Kludex/starlette/pull/2858).

## 1.6.0 (August 8, 2026)

#### Added

* Add `max_body_size` to `Starlette` and route classes [#3431](https://github.com/encode/starlette/pull/3431).
* Expose `http.response.debug` information via response extensions [#3130](https://github.com/encode/starlette/pull/3130).

## 1.5.1 (August 8, 2026)

#### Fixed

* Reject inverted single-byte ranges in `FileResponse` [#3389](https://github.com/encode/starlette/pull/3389).
* Limit `FileResponse` to 100 ranges [#3430](https://github.com/encode/starlette/pull/3430).

## 1.5.0 (August 8, 2026)

#### Added

* Add `exclude_content_types` parameter to `GZipMiddleware` [#3418](https://github.com/encode/starlette/pull/3418).

#### Changed

* Expand default excluded content types in `GZipMiddleware` [#3421](https://github.com/encode/starlette/pull/3421).

#### Fixed

* Flush GZip output for each streamed chunk [#3419](https://github.com/encode/starlette/pull/3419).
* Skip compression of partial responses in `GZipMiddleware` [#3420](https://github.com/encode/starlette/pull/3420).

## 1.4.1 (August 5, 2026)

#### Fixed

* Default `thread_minimum_size` to 128 KiB in `GZipResponder`, keeping it usable without the new keyword argument [#3415](https://github.com/encode/starlette/pull/3415).

## 1.4.0 (August 5, 2026)

#### Added

* Offload large GZip compression to a worker thread, keeping the event loop responsive. `GZipMiddleware` accepts a new `thread_minimum_size` parameter (default 128 KiB) controlling the minimum body chunk size compressed in a thread [#3410](https://github.com/encode/starlette/pull/3410).

#### Changed

* Use `zlib.compressobj` instead of `GzipFile` in `GZipMiddleware`, reducing memory usage during compression [#3411](https://github.com/encode/starlette/pull/3411).
* Lazily allocate `GZipMiddleware` compression resources, avoiding compressor allocation for responses that are never compressed [#3407](https://github.com/encode/starlette/pull/3407).

## 1.3.1 (June 12, 2026)

#### Fixed

* Enforce `max_fields` and `max_part_size` in `FormParser` [#3329](https://github.com/encode/starlette/pull/3329).
* Enforce `FormParser` limits in parser callbacks [#3331](https://github.com/encode/starlette/pull/3331).

## 1.3.0 (June 11, 2026)

#### Added

* Add `httpx2` to the `full` extra [#3323](https://github.com/encode/starlette/pull/3323).
* Annotate the `URLPath` `protocol` parameter with `Literal` [#3285](https://github.com/encode/starlette/pull/3285).

#### Fixed

* Build `request.url` from structured components [#3326](https://github.com/encode/starlette/pull/3326).
* Clamp oversized suffix ranges in `FileResponse` [#3307](https://github.com/encode/starlette/pull/3307).
* Catch `OSError` alongside `MultiPartException` when closing temp files [#3191](https://github.com/encode/starlette/pull/3191).
* Avoid collapsing exception groups raised from user code [#2830](https://github.com/encode/starlette/pull/2830).
* Use `removeprefix` to strip the weak `ETag` indicator in `is_not_modified` [#3193](https://github.com/encode/starlette/pull/3193).
* Fix `IndexError` in `URL.replace()` on a URL with no authority [#3317](https://github.com/encode/starlette/pull/3317).
* Adjust `testclient` typing and warnings [#3322](https://github.com/encode/starlette/pull/3322).

## 1.2.1 (May 31, 2026)

#### Fixed

* Use `httpx2` for type checking in the `testclient` module [#3304](https://github.com/encode/starlette/pull/3304).
* Add assert error for `requires()` when the request parameter is not a `Request` type [#3298](https://github.com/encode/starlette/pull/3298).

## 1.2.0 (May 28, 2026)

#### Added

* Support httpx2 in the test client [#3291](https://github.com/encode/starlette/pull/3291).

## 1.1.0 (May 23, 2026)

#### Added

* Use `"application/octet-stream"` as the `FileResponse` media type fallback [#3283](https://github.com/encode/starlette/pull/3283).

#### Fixed

* Only dispatch standard HTTP verbs in `HTTPEndpoint` [#3286](https://github.com/encode/starlette/pull/3286).
* Reject absolute paths in `StaticFiles.lookup_path` [#3287](https://github.com/encode/starlette/pull/3287).

## 1.0.1 (May 21, 2026)

#### Fixed

* Ignore malformed `Host` header when constructing `request.url` [#3279](https://github.com/encode/starlette/pull/3279).

## 1.0.0 (March 22, 2026)

Starlette 1.0 is here!

After nearly eight years since its creation, Starlette has reached its first stable release.
Thank you to everyone who tested the release candidate and reported issues.

You can read more on the [blog post](https://marcelotryle.com/blog/2026/03/22/starlette-10-is-here/).

#### Added

* Track session access and modification in `SessionMiddleware` [#3166](https://github.com/encode/starlette/pull/3166).

#### Fixed

* Handle websocket denial responses in `StreamingResponse` and `FileResponse` [#3189](https://github.com/encode/starlette/pull/3189).
* Use `bytearray` for field accumulation in `FormParser` [#3179](https://github.com/encode/starlette/pull/3179).
* Move `parser.finalize()` inside try/except in `MultiPartParser.parse()` [#3153](https://github.com/encode/starlette/pull/3153).

## 1.0.0rc1 (February 23, 2026)

We're ready! I'm thrilled to announce the first release candidate for Starlette 1.0.

Starlette was created in June 2018 by Tom Christie, and has been on ZeroVer for years. Today, it's downloaded
almost [10 million times a day](https://pypistats.org/packages/starlette), serves as the foundation for FastAPI,
and has inspired many other frameworks. In the age of AI, Starlette continues to play an important role as a
dependency of the Python MCP SDK.

This release focuses on removing deprecated features that were marked for removal in 1.0.0, along with some
last minute bug fixes. It's a release candidate, so we can gather feedback from the community before the final
1.0.0 release soon.

A huge thank you to all the contributors who have helped make Starlette what it is today.
In particular, I'd like to recognize:

* [Kim Christie](https://github.com/lovelydinosaur) - The original creator of Starlette, Uvicorn, and MkDocs, and the
  current maintainer of HTTPX. Kim's work helped lay the foundation for the modern async Python ecosystem.
* [Adrian Garcia Badaracco](https://github.com/adriangb) - One of the smartest people I know, whom I have the pleasure of working with at Pydantic.
* [Thomas Grainger](https://github.com/graingert) - My async teacher, always ready to help with questions.
* [Alex Grönholm](https://github.com/agronholm) - Another async mentor, always prompt to help with questions.
* [Florimond Manca](https://github.com/florimondmanca) - Always present in the early days of both Starlette and Uvicorn, and helped a lot in the ecosystem.
* [Amin Alaee](https://github.com/aminalaee) - Contributed a lot with file-related PRs.
* [Sebastián Ramírez](https://github.com/tiangolo) - Maintains FastAPI upstream, and always in contact to help with upstream issues.
* [Alex Oleshkevich](https://github.com/alex-oleshkevich) - Helped a lot on templates and many discussions.
* [abersheeran](https://github.com/abersheeran) - My go-to person when I need help on many subjects.

I'd also like to thank my sponsors for their support. A special thanks to
[@tiangolo](https://github.com/tiangolo), [@huggingface](https://github.com/huggingface),
and [@elevenlabs](https://github.com/elevenlabs) for their generous sponsorship, and to all my other sponsors:

[@roboflow](https://github.com/roboflow),
[@ogabrielluiz](https://github.com/ogabrielluiz),
[@SaboniAmine](https://github.com/SaboniAmine),
[@russbiggs](https://github.com/russbiggs),
[@BryceBeagle](https://github.com/BryceBeagle),
[@chdsbd](https://github.com/chdsbd),
[@TheR1D](https://github.com/TheR1D),
[@ddanier](https://github.com/ddanier),
[@larsyngvelundin](https://github.com/larsyngvelundin),
[@jpizquierdo](https://github.com/jpizquierdo),
[@alixlahuec](https://github.com/alixlahuec),
[@nathanchapman](https://github.com/nathanchapman),
[@devid8642](https://github.com/devid8642),
[@comet-ml](https://github.com/comet-ml),
[@Evil0ctal](https://github.com/Evil0ctal),
[@msehnout](https://github.com/msehnout),
and [@codingjoe](https://github.com/codingjoe).

#### Removed

* Remove `on_startup` and `on_shutdown` parameters from `Starlette` and `Router`.
  Use the `lifespan` parameter instead [#3117](https://github.com/encode/starlette/pull/3117).
* Remove `on_event()` decorator from `Starlette` and `Router`.
  Use the `lifespan` parameter instead [#3117](https://github.com/encode/starlette/pull/3117).
* Remove `add_event_handler()` method from `Starlette` and `Router`.
  Use the `lifespan` parameter instead [#3117](https://github.com/encode/starlette/pull/3117).
* Remove `startup()` and `shutdown()` methods from `Router`
  [#3117](https://github.com/encode/starlette/pull/3117).
* Remove `@app.route()` decorator from `Starlette` and `Router`.
  Use `Route` in the `routes` parameter instead [#3117](https://github.com/encode/starlette/pull/3117).
* Remove `@app.websocket_route()` decorator from `Starlette` and `Router`.
  Use `WebSocketRoute` in the `routes` parameter instead [#3117](https://github.com/encode/starlette/pull/3117).
* Remove `@app.exception_handler()` decorator from `Starlette`.
  Use `exception_handlers` parameter instead [#3117](https://github.com/encode/starlette/pull/3117).
* Remove `@app.middleware()` decorator from `Starlette`.
  Use `middleware` parameter instead [#3117](https://github.com/encode/starlette/pull/3117).
* Remove `iscoroutinefunction_or_partial()` from `starlette.routing` [#3117](https://github.com/encode/starlette/pull/3117).
* Remove `**env_options` parameter from `Jinja2Templates`.
  Use a preconfigured `jinja2.Environment` via the `env` parameter instead [#3118](https://github.com/encode/starlette/pull/3118).
* Remove deprecated `TemplateResponse(name, context)` signature from `Jinja2Templates`.
  Use `TemplateResponse(request, name, ...)` instead [#3118](https://github.com/encode/starlette/pull/3118).
* Remove deprecated `method` parameter from `FileResponse` [#3147](https://github.com/encode/starlette/pull/3147).

#### Added

* Add state generic to `WebSocket` [#3132](https://github.com/encode/starlette/pull/3132).

#### Fixed

* Include `bytes` unit in `Content-Range` header on 416 responses.
* Handle null bytes in `StaticFiles` path [#3139](https://github.com/encode/starlette/pull/3139).
* Use sort-based merge for `Range` header parsing [#3138](https://github.com/encode/starlette/pull/3138).
* Set `Content-Type` instead of `Content-Range` on multi-range responses [#3142](https://github.com/encode/starlette/pull/3142).
* Use CRLF line endings in multipart byterange boundaries [#3143](https://github.com/encode/starlette/pull/3143).
* Avoid mutating `FileResponse` headers on range requests [#3144](https://github.com/encode/starlette/pull/3144).
* Return explicit origin in CORS response when credentials are allowed [#3137](https://github.com/encode/starlette/pull/3137).
* Enable `autoescape` by default in `Jinja2Templates` [#3148](https://github.com/encode/starlette/pull/3148).

#### Changed

* `jinja2` must now be installed to import `Jinja2Templates`. Previously it would only
  fail when instantiating the class [#3118](https://github.com/encode/starlette/pull/3118).

## 0.52.1 (January 18, 2026)

#### Fixed

* Only use `typing_extensions` in older Python versions [#3109](https://github.com/Kludex/starlette/pull/3109).

## 0.52.0 (January 18, 2026)

In this release, `State` can be accessed using dictionary-style syntax for improved type
safety ([#3036](https://github.com/Kludex/starlette/pull/3036)).

```python
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import TypedDict

import httpx

from starlette.applications import Starlette
from starlette.requests import Request


class State(TypedDict):
    http_client: httpx.AsyncClient


@asynccontextmanager
async def lifespan(app: Starlette) -> AsyncIterator[State]:
    async with httpx.AsyncClient() as client:
        yield {"http_client": client}


async def homepage(request: Request[State]):
    client = request.state["http_client"]
    # If you run the below line with mypy or pyright, it will reveal the correct type.
    reveal_type(client)  # Revealed type is 'httpx.AsyncClient'
```

See [Accessing State](lifespan.md#accessing-state) for more details.

## 0.51.0 (January 10, 2026)

#### Added

* Add `allow_private_network` in `CORSMiddleware` [#3065](https://github.com/Kludex/starlette/pull/3065).

#### Changed

* Increase warning stacklevel on `DeprecationWarning` for wsgi module [#3082](https://github.com/Kludex/starlette/pull/3082).

## 0.50.0 (November 1, 2025)

#### Removed

* Drop Python 3.9 support [#3061](https://github.com/Kludex/starlette/pull/3061).

## 0.49.3 (November 1, 2025)

This is the last release that supports Python 3.9, which will be dropped in the next minor release.

#### Fixed

* Relax strictness on `Middleware` type [#3059](https://github.com/Kludex/starlette/pull/3059).

## 0.49.2 (November 1, 2025)

#### Fixed

* Ignore `if-modified-since` header if `if-none-match` is present in `StaticFiles` [#3044](https://github.com/Kludex/starlette/pull/3044).

## 0.49.1 (October 28, 2025)

This release fixes a security vulnerability in the parsing logic of the `Range` header in `FileResponse`.

You can view the full security advisory: [GHSA-7f5h-v6xp-fcq8](https://github.com/Kludex/starlette/security/advisories/GHSA-7f5h-v6xp-fcq8)

#### Fixed

* Optimize the HTTP ranges parsing logic [4ea6e22b489ec388d6004cfbca52dd5b147127c5](https://github.com/Kludex/starlette/commit/4ea6e22b489ec388d6004cfbca52dd5b147127c5)

## 0.49.0 (October 28, 2025)

#### Added

* Add `encoding` parameter to `Config` class [#2996](https://github.com/Kludex/starlette/pull/2996).
* Support multiple cookie headers in `Request.cookies` [#3029](https://github.com/Kludex/starlette/pull/3029).
* Use `Literal` type for `WebSocketEndpoint` encoding values [#3027](https://github.com/Kludex/starlette/pull/3027).

#### Changed

* Do not pollute exception context in `Middleware` when using `BaseHTTPMiddleware` [#2976](https://github.com/Kludex/starlette/pull/2976).

## 0.48.0 (September 13, 2025)

#### Added

* Add official Python 3.14 support [#3013](https://github.com/Kludex/starlette/pull/3013).

#### Changed

* Implement [RFC9110](https://www.rfc-editor.org/rfc/rfc9110) http status names [#2939](https://github.com/Kludex/starlette/pull/2939).

## 0.47.3 (August 24, 2025)

#### Fixed

* Use `asyncio.iscoroutinefunction` for Python 3.12 and older [#2984](https://github.com/Kludex/starlette/pull/2984).

## 0.47.2 (July 20, 2025)

#### Fixed

* Make `UploadFile` check for future rollover [#2962](https://github.com/Kludex/starlette/pull/2962).

## 0.47.1 (June 21, 2025)

#### Fixed

* Use `Self` in `TestClient.__enter__` [#2951](https://github.com/Kludex/starlette/pull/2951).
* Allow async exception handlers to type-check [#2949](https://github.com/Kludex/starlette/pull/2949).

## 0.47.0 (May 29, 2025)

#### Added

* Add support for ASGI `pathsend` extension [#2671](https://github.com/Kludex/starlette/pull/2671).
* Add `partitioned` attribute to `Response.set_cookie` [#2501](https://github.com/Kludex/starlette/pull/2501).

#### Changed

* Change `methods` parameter type from `list[str]` to `Collection[str]`
  [#2903](https://github.com/Kludex/starlette/pull/2903).
* Replace `import typing` by `from typing import ...` in the whole codebase
  [#2867](https://github.com/Kludex/starlette/pull/2867).

#### Fixed

* Mark `ExceptionMiddleware.http_exception` as async to prevent thread creation
  [#2922](https://github.com/Kludex/starlette/pull/2922).

## 0.46.2 (April 13, 2025)

#### Fixed

* Prevents reraising of exception from BaseHttpMiddleware [#2911](https://github.com/Kludex/starlette/pull/2911).
* Use correct index on backwards compatible logic in `TemplateResponse` [#2909](https://github.com/Kludex/starlette/pull/2909).

## 0.46.1 (March 8, 2025)

#### Fixed

* Allow relative directory path when `follow_symlinks=True` [#2896](https://github.com/Kludex/starlette/pull/2896).

## 0.46.0 (February 22, 2025)

#### Added

* `GZipMiddleware`: Make sure `Vary` header is always added if a response can be compressed [#2865](https://github.com/Kludex/starlette/pull/2865).

#### Fixed

* Raise exception from background task on BaseHTTPMiddleware [#2812](https://github.com/Kludex/starlette/pull/2812).
* `GZipMiddleware`: Don't compress on server sent events [#2871](https://github.com/Kludex/starlette/pull/2871).

#### Changed

* `MultiPartParser`: Rename `max_file_size` to `spool_max_size` [#2780](https://github.com/Kludex/starlette/pull/2780).

#### Deprecated

* Add deprecated warning to `TestClient(timeout=...)` [#2840](https://github.com/Kludex/starlette/pull/2840).

## 0.45.3 (January 24, 2025)

#### Fixed

* Turn directory into string on `lookup_path` on commonpath comparison [#2851](https://github.com/Kludex/starlette/pull/2851).

## 0.45.2 (January 4, 2025)

#### Fixed

* Make `create_memory_object_stream` compatible with old anyio versions once again, and bump anyio minimum version to 3.6.2 [#2833](https://github.com/Kludex/starlette/pull/2833).

## 0.45.1 (December 30, 2024)

#### Fixed

* Close `MemoryObjectReceiveStream` left unclosed upon exception in `BaseHTTPMiddleware` children [#2813](https://github.com/Kludex/starlette/pull/2813).
* Collect errors more reliably from the WebSocket logic on the `TestClient` [#2814](https://github.com/Kludex/starlette/pull/2814).

#### Refactor

* Use a pair of memory object streams instead of two queues on the `TestClient` [#2829](https://github.com/Kludex/starlette/pull/2829).

## 0.45.0 (December 29, 2024)

#### Removed

* Drop Python 3.8 support [#2823](https://github.com/Kludex/starlette/pull/2823).
* Remove `ExceptionMiddleware` import proxy from `starlette.exceptions` module [#2826](https://github.com/Kludex/starlette/pull/2826).
* Remove deprecated `WS_1004_NO_STATUS_RCVD` and `WS_1005_ABNORMAL_CLOSURE` [#2827](https://github.com/Kludex/starlette/pull/2827).

## 0.44.0 (December 28, 2024)

#### Added

* Add `client` parameter to `TestClient` [#2810](https://github.com/Kludex/starlette/pull/2810).
* Add `max_part_size` parameter to `Request.form()` [#2815](https://github.com/Kludex/starlette/pull/2815).

## 0.43.0 (December 25, 2024)

#### Removed

* Remove deprecated `allow_redirects` argument from `TestClient` [#2808](https://github.com/Kludex/starlette/pull/2808).

#### Added

* Make UUID path parameter conversion more flexible [#2806](https://github.com/Kludex/starlette/pull/2806).

## 0.42.0 (December 14, 2024)

#### Added

* Raise `ClientDisconnect` on `StreamingResponse` [#2732](https://github.com/Kludex/starlette/pull/2732).

#### Fixed

* Use ETag from headers when parsing If-Range in FileResponse [#2761](https://github.com/Kludex/starlette/pull/2761).
* Follow directory symlinks in `StaticFiles` when `follow_symlinks=True` [#2711](https://github.com/Kludex/starlette/pull/2711).
* Bump minimum `python-multipart` version to `0.0.18` [0ba8395](https://github.com/Kludex/starlette/commit/0ba83959e609bbd460966f092287df1bbd564cc6).
* Bump minimum `httpx` version to `0.27.0` [#2773](https://github.com/Kludex/starlette/pull/2773).

## 0.41.3 (November 18, 2024)

#### Fixed

* Exclude the query parameters from the `scope[raw_path]` on the `TestClient` [#2716](https://github.com/Kludex/starlette/pull/2716).
* Replace `dict` by `Mapping` on `HTTPException.headers` [#2749](https://github.com/Kludex/starlette/pull/2749).
* Correct middleware argument passing and improve factory pattern [#2752](https://github.com/Kludex/starlette/pull/2752).

## 0.41.2 (October 27, 2024)

#### Fixed

* Revert bump on `python-multipart` on `starlette[full]` extras [#2737](https://github.com/Kludex/starlette/pull/2737).

## 0.41.1 (October 24, 2024)

#### Fixed

* Bump minimum `python-multipart` version to `0.0.13` [#2734](https://github.com/Kludex/starlette/pull/2734).
* Change `python-multipart` import to `python_multipart` [#2733](https://github.com/Kludex/starlette/pull/2733).

## 0.41.0 (October 15, 2024)

#### Added

- Allow to raise `HTTPException` before `websocket.accept()` [#2725](https://github.com/Kludex/starlette/pull/2725).

## 0.40.0 (October 15, 2024)

This release fixes a Denial of service (DoS) via `multipart/form-data` requests.

You can view the full security advisory:
[GHSA-f96h-pmfr-66vw](https://github.com/Kludex/starlette/security/advisories/GHSA-f96h-pmfr-66vw)

#### Fixed

- Add `max_part_size` to `MultiPartParser` to limit the size of parts in `multipart/form-data`
  requests [fd038f3](https://github.com/Kludex/starlette/commit/fd038f3070c302bff17ef7d173dbb0b007617733).

## 0.39.2 (September 29, 2024)

#### Fixed

- Allow use of `request.url_for` when only "app" scope is available [#2672](https://github.com/Kludex/starlette/pull/2672).
- Fix internal type hints to support `python-multipart==0.0.12` [#2708](https://github.com/Kludex/starlette/pull/2708).

## 0.39.1 (September 25, 2024)

#### Fixed

- Avoid regex re-compilation in `responses.py` and `schemas.py` [#2700](https://github.com/Kludex/starlette/pull/2700).
- Improve performance of `get_route_path` by removing regular expression usage
  [#2701](https://github.com/Kludex/starlette/pull/2701).
- Consider `FileResponse.chunk_size` when handling multiple ranges [#2703](https://github.com/Kludex/starlette/pull/2703).
- Use `token_hex` for generating multipart boundary strings [#2702](https://github.com/Kludex/starlette/pull/2702).

## 0.39.0 (September 23, 2024)

#### Added

* Add support for [HTTP Range](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests) to
  `FileResponse` [#2697](https://github.com/Kludex/starlette/pull/2697).

## 0.38.6 (September 22, 2024)

#### Fixed

* Close unclosed `MemoryObjectReceiveStream` in `TestClient` [#2693](https://github.com/Kludex/starlette/pull/2693).

## 0.38.5 (September 7, 2024)

#### Fixed

* Schedule `BackgroundTasks` from within `BaseHTTPMiddleware` [#2688](https://github.com/Kludex/starlette/pull/2688).
  This behavior was removed in 0.38.3, and is now restored.

## 0.38.4 (September 1, 2024)

#### Fixed

* Ensure accurate `root_path` removal in `get_route_path` function [#2600](https://github.com/Kludex/starlette/pull/2600).

## 0.38.3 (September 1, 2024)

#### Added

* Support for Python 3.13 [#2662](https://github.com/Kludex/starlette/pull/2662).

#### Fixed

* Don't poll for disconnects in `BaseHTTPMiddleware` via `StreamingResponse` [#2620](https://github.com/Kludex/starlette/pull/2620).

## 0.38.2 (July 27, 2024)

#### Fixed

* Not assume all routines have `__name__` on `routing.get_name()` [#2648](https://github.com/Kludex/starlette/pull/2648).

## 0.38.1 (July 23, 2024)

#### Removed

* Revert "Add support for ASGI pathsend extension" [#2649](https://github.com/Kludex/starlette/pull/2649).

## 0.38.0 (July 20, 2024)

#### Added

* Allow use of `memoryview` in `StreamingResponse` and `Response` [#2576](https://github.com/Kludex/starlette/pull/2576)
  and [#2577](https://github.com/Kludex/starlette/pull/2577).
* Send 404 instead of 500 when filename requested is too long on `StaticFiles` [#2583](https://github.com/Kludex/starlette/pull/2583).

#### Changed

* Fail fast on invalid `Jinja2Template` instantiation parameters [#2568](https://github.com/Kludex/starlette/pull/2568).
* Check endpoint handler is async only once [#2536](https://github.com/Kludex/starlette/pull/2536).

#### Fixed

* Add proper synchronization to `WebSocketTestSession` [#2597](https://github.com/Kludex/starlette/pull/2597).

## 0.37.2 (March 5, 2024)

#### Added

* Add `bytes` to `_RequestData` type [#2510](https://github.com/Kludex/starlette/pull/2510).

#### Fixed

* Revert "Turn `scope["client"]` to `None` on `TestClient` (#2377)" [#2525](https://github.com/Kludex/starlette/pull/2525).
* Remove deprecated `app` argument passed to `httpx.Client` on the `TestClient` [#2526](https://github.com/Kludex/starlette/pull/2526).

## 0.37.1 (February 9, 2024)

#### Fixed

* Warn instead of raise for missing env file on `Config` [#2485](https://github.com/Kludex/starlette/pull/2485).

## 0.37.0 (February 5, 2024)

#### Added

* Support the WebSocket Denial Response ASGI extension [#2041](https://github.com/Kludex/starlette/pull/2041).

## 0.36.3 (February 4, 2024)

#### Fixed

* Create `anyio.Event` on async context [#2459](https://github.com/Kludex/starlette/pull/2459).

## 0.36.2 (February 3, 2024)

#### Fixed

* Upgrade `python-multipart` to `0.0.7` [13e5c26](http://github.com/Kludex/starlette/commit/13e5c26a27f4903924624736abd6131b2da80cc5).
* Avoid duplicate charset on `Content-Type` [#2443](https://github.com/Kludex/starlette/2443).

## 0.36.1 (January 23, 2024)

#### Fixed

* Check if "extensions" in scope before checking the extension [#2438](http://github.com/Kludex/starlette/pull/2438).

## 0.36.0 (January 22, 2024)

#### Added

* Add support for ASGI `pathsend` extension [#2435](http://github.com/Kludex/starlette/pull/2435).
* Cancel `WebSocketTestSession` on close [#2427](http://github.com/Kludex/starlette/pull/2427).
* Raise `WebSocketDisconnect` when `WebSocket.send()` excepts `IOError` [#2425](http://github.com/Kludex/starlette/pull/2425).
* Raise `FileNotFoundError` when the `env_file` parameter on `Config` is not valid [#2422](http://github.com/Kludex/starlette/pull/2422).

## 0.35.1 (January 11, 2024)

#### Fixed

* Stop using the deprecated "method" parameter in `FileResponse` inside of `StaticFiles` [#2406](https://github.com/Kludex/starlette/pull/2406).
* Make `typing-extensions` optional again [#2409](https://github.com/Kludex/starlette/pull/2409).

## 0.35.0 (January 11, 2024)

#### Added

* Add `*args` to `Middleware` and improve its type hints [#2381](https://github.com/Kludex/starlette/pull/2381).

#### Fixed

* Use `Iterable` instead `Iterator` on `iterate_in_threadpool` [#2362](https://github.com/Kludex/starlette/pull/2362).

#### Changes

* Handle `root_path` to keep compatibility with mounted ASGI applications and WSGI [#2400](https://github.com/Kludex/starlette/pull/2400).
* Turn `scope["client"]` to `None` on `TestClient` [#2377](https://github.com/Kludex/starlette/pull/2377).

## 0.34.0 (December 16, 2023)

### Added

* Use `ParamSpec` for `run_in_threadpool` [#2375](https://github.com/Kludex/starlette/pull/2375).
* Add `UploadFile.__repr__` [#2360](https://github.com/Kludex/starlette/pull/2360).

### Fixed

* Merge URLs properly on `TestClient` [#2376](https://github.com/Kludex/starlette/pull/2376).
* Take weak ETags in consideration on `StaticFiles` [#2334](https://github.com/Kludex/starlette/pull/2334).

### Deprecated

* Deprecate `FileResponse(method=...)` parameter [#2366](https://github.com/Kludex/starlette/pull/2366).

## 0.33.0 (December 1, 2023)

### Added

* Add `middleware` per `Route`/`WebSocketRoute` [#2349](https://github.com/Kludex/starlette/pull/2349).
* Add `middleware` per `Router` [#2351](https://github.com/Kludex/starlette/pull/2351).

### Fixed

* Do not overwrite `"path"` and `"root_path"` scope keys [#2352](https://github.com/Kludex/starlette/pull/2352).
* Set `ensure_ascii=False` on `json.dumps()` for `WebSocket.send_json()` [#2341](https://github.com/Kludex/starlette/pull/2341).

## 0.32.0.post1 (November 5, 2023)

### Fixed

* Revert mkdocs-material from 9.1.17 to 9.4.7 [#2326](https://github.com/Kludex/starlette/pull/2326).

## 0.32.0 (November 4, 2023)

### Added

* Send `reason` on `WebSocketDisconnect` [#2309](https://github.com/Kludex/starlette/pull/2309).
* Add `domain` parameter to `SessionMiddleware` [#2280](https://github.com/Kludex/starlette/pull/2280).

### Changed

* Inherit from `HTMLResponse` instead of `Response` on `_TemplateResponse` [#2274](https://github.com/Kludex/starlette/pull/2274).
* Restore the `Response.render` type annotation to its pre-0.31.0 state [#2264](https://github.com/Kludex/starlette/pull/2264).

## 0.31.1 (August 26, 2023)

### Fixed

* Fix import error when `exceptiongroup` isn't available [#2231](https://github.com/Kludex/starlette/pull/2231).
* Set `url_for` global for custom Jinja environments [#2230](https://github.com/Kludex/starlette/pull/2230).

## 0.31.0 (July 24, 2023)

### Added

* Officially support Python 3.12 [#2214](https://github.com/Kludex/starlette/pull/2214).
* Support AnyIO 4.0 [#2211](https://github.com/Kludex/starlette/pull/2211).
* Strictly type annotate Starlette (strict mode on mypy) [#2180](https://github.com/Kludex/starlette/pull/2180).

### Fixed

* Don't group duplicated headers on a single string when using the `TestClient` [#2219](https://github.com/Kludex/starlette/pull/2219).

## 0.30.0 (July 13, 2023)

### Removed

* Drop Python 3.7 support [#2178](https://github.com/Kludex/starlette/pull/2178).

## 0.29.0 (July 13, 2023)

### Added

* Add `follow_redirects` parameter to `TestClient` [#2207](https://github.com/Kludex/starlette/pull/2207).
* Add `__str__` to `HTTPException` and `WebSocketException` [#2181](https://github.com/Kludex/starlette/pull/2181).
* Warn users when using `lifespan` together with `on_startup`/`on_shutdown` [#2193](https://github.com/Kludex/starlette/pull/2193).
* Collect routes from `Host` to generate the OpenAPI schema [#2183](https://github.com/Kludex/starlette/pull/2183).
* Add `request` argument to `TemplateResponse` [#2191](https://github.com/Kludex/starlette/pull/2191).

### Fixed

* Stop `body_stream` in case `more_body=False` on `BaseHTTPMiddleware` [#2194](https://github.com/Kludex/starlette/pull/2194).

## 0.28.0 (June 7, 2023)

### Changed
* Reuse `Request`'s body buffer for call_next in `BaseHTTPMiddleware` [#1692](https://github.com/Kludex/starlette/pull/1692).
* Move exception handling logic to `Route` [#2026](https://github.com/Kludex/starlette/pull/2026).

### Added
* Add `env` parameter to `Jinja2Templates`, and deprecate `**env_options` [#2159](https://github.com/Kludex/starlette/pull/2159).
* Add clear error message when `httpx` is not installed [#2177](https://github.com/Kludex/starlette/pull/2177).

### Fixed
* Allow "name" argument on `templates url_for()` [#2127](https://github.com/Kludex/starlette/pull/2127).

## 0.27.0 (May 16, 2023)

This release fixes a path traversal vulnerability in `StaticFiles`. You can view the full security advisory:
https://github.com/Kludex/starlette/security/advisories/GHSA-v5gw-mw7f-84px

### Added
* Minify JSON websocket data via `send_json` https://github.com/Kludex/starlette/pull/2128

### Fixed
* Replace `commonprefix` by `commonpath` on `StaticFiles` [1797de4](https://github.com/Kludex/starlette/commit/1797de464124b090f10cf570441e8292936d63e3).
* Convert ImportErrors into ModuleNotFoundError [#2135](https://github.com/Kludex/starlette/pull/2135).
* Correct the RuntimeError message content in websockets [#2141](https://github.com/Kludex/starlette/pull/2141).

## 0.26.1 (March 13, 2023)

### Fixed
* Fix typing of Lifespan to allow subclasses of Starlette [#2077](https://github.com/Kludex/starlette/pull/2077).

## 0.26.0.post1 (March 9, 2023)

### Fixed
* Replace reference from Events to Lifespan on the mkdocs.yml [#2072](https://github.com/Kludex/starlette/pull/2072).

## 0.26.0 (March 9, 2023)

### Added
* Support [lifespan state](lifespan.md) [#2060](https://github.com/Kludex/starlette/pull/2060),
  [#2065](https://github.com/Kludex/starlette/pull/2065) and [#2064](https://github.com/Kludex/starlette/pull/2064).

### Changed
* Change `url_for` signature to return a `URL` instance [#1385](https://github.com/Kludex/starlette/pull/1385).

### Fixed
* Allow "name" argument on `url_for()` and `url_path_for()` [#2050](https://github.com/Kludex/starlette/pull/2050).

### Deprecated
* Deprecate `on_startup` and `on_shutdown` events [#2070](https://github.com/Kludex/starlette/pull/2070).

## 0.25.0 (February 14, 2023)

### Fix
* Limit the number of fields and files when parsing `multipart/form-data` on the `MultipartParser` [8c74c2c](https://github.com/Kludex/starlette/commit/8c74c2c8dba7030154f8af18e016136bea1938fa) and [#2036](https://github.com/Kludex/starlette/pull/2036).

## 0.24.0 (February 6, 2023)

### Added
* Allow `StaticFiles` to follow symlinks [#1683](https://github.com/Kludex/starlette/pull/1683).
* Allow `Request.form()` as a context manager [#1903](https://github.com/Kludex/starlette/pull/1903).
* Add `size` attribute to `UploadFile` [#1405](https://github.com/Kludex/starlette/pull/1405).
* Add `env_prefix` argument to `Config` [#1990](https://github.com/Kludex/starlette/pull/1990).
* Add template context processors [#1904](https://github.com/Kludex/starlette/pull/1904).
* Support `str` and `datetime` on `expires` parameter on the `Response.set_cookie` method [#1908](https://github.com/Kludex/starlette/pull/1908).

### Changed
* Lazily build the middleware stack [#2017](https://github.com/Kludex/starlette/pull/2017).
* Make the `file` argument required on `UploadFile` [#1413](https://github.com/Kludex/starlette/pull/1413).
* Use debug extension instead of custom response template extension [#1991](https://github.com/Kludex/starlette/pull/1991).

### Fixed
* Fix url parsing of ipv6 urls on `URL.replace` [#1965](https://github.com/Kludex/starlette/pull/1965).

## 0.23.1 (December 9, 2022)

### Fixed
* Only stop receiving stream on `body_stream` if body is empty on the `BaseHTTPMiddleware` [#1940](https://github.com/Kludex/starlette/pull/1940).

## 0.23.0 (December 5, 2022)

### Added
* Add `headers` parameter to the `TestClient` [#1966](https://github.com/Kludex/starlette/pull/1966).

### Deprecated
* Deprecate `Starlette` and `Router` decorators [#1897](https://github.com/Kludex/starlette/pull/1897).

### Fixed
* Fix bug on `FloatConvertor` regex [#1973](https://github.com/Kludex/starlette/pull/1973).

## 0.22.0 (November 17, 2022)

### Changed
* Bypass `GZipMiddleware` when response includes `Content-Encoding` [#1901](https://github.com/Kludex/starlette/pull/1901).

### Fixed
* Remove unneeded `unquote()` from query parameters on the `TestClient` [#1953](https://github.com/Kludex/starlette/pull/1953).
* Make sure `MutableHeaders._list` is actually a `list` [#1917](https://github.com/Kludex/starlette/pull/1917).
* Import compatibility with the next version of `AnyIO` [#1936](https://github.com/Kludex/starlette/pull/1936).

## 0.21.0 (September 26, 2022)

This release replaces the underlying HTTP client used on the `TestClient` (`requests` :arrow_right: `httpx`), and as those clients [differ _a bit_ on their API](https://www.python-httpx.org/compatibility/), your test suite will likely break. To make the migration smoother, you can use the [`bump-testclient`](https://github.com/Kludex/bump-testclient) tool.

### Changed
* Replace `requests` with `httpx` in `TestClient` [#1376](https://github.com/Kludex/starlette/pull/1376).

### Added
* Add `WebSocketException` and support for WebSocket exception handlers [#1263](https://github.com/Kludex/starlette/pull/1263).
* Add `middleware` parameter to `Mount` class [#1649](https://github.com/Kludex/starlette/pull/1649).
* Officially support Python 3.11 [#1863](https://github.com/Kludex/starlette/pull/1863).
* Implement `__repr__` for route classes [#1864](https://github.com/Kludex/starlette/pull/1864).

### Fixed
* Fix bug on which `BackgroundTasks` were cancelled when using `BaseHTTPMiddleware` and client disconnected [#1715](https://github.com/Kludex/starlette/pull/1715).

## 0.20.4 (June 28, 2022)

### Fixed
* Remove converter from path when generating OpenAPI schema [#1648](https://github.com/Kludex/starlette/pull/1648).

## 0.20.3 (June 10, 2022)

### Fixed
* Revert "Allow `StaticFiles` to follow symlinks" [#1681](https://github.com/Kludex/starlette/pull/1681).

## 0.20.2 (June 7, 2022)

### Fixed
* Fix regression on route paths with colons [#1675](https://github.com/Kludex/starlette/pull/1675).
* Allow `StaticFiles` to follow symlinks [#1337](https://github.com/Kludex/starlette/pull/1377).

## 0.20.1 (May 28, 2022)

### Fixed
* Improve detection of async callables [#1444](https://github.com/Kludex/starlette/pull/1444).
* Send 400 (Bad Request) when `boundary` is missing [#1617](https://github.com/Kludex/starlette/pull/1617).
* Send 400 (Bad Request) when missing "name" field on `Content-Disposition` header [#1643](https://github.com/Kludex/starlette/pull/1643).
* Do not send empty data to `StreamingResponse` on `BaseHTTPMiddleware` [#1609](https://github.com/Kludex/starlette/pull/1609).
* Add `__bool__` dunder for `Secret` [#1625](https://github.com/Kludex/starlette/pull/1625).

## 0.20.0 (May 3, 2022)

### Removed
* Drop Python 3.6 support [#1357](https://github.com/Kludex/starlette/pull/1357) and [#1616](https://github.com/Kludex/starlette/pull/1616).


## 0.19.1 (April 22, 2022)

### Fixed
* Fix inference of `Route.name` when created from methods [#1553](https://github.com/Kludex/starlette/pull/1553).
* Avoid `TypeError` on `websocket.disconnect` when code is `None` [#1574](https://github.com/Kludex/starlette/pull/1574).

### Deprecated
* Deprecate `WS_1004_NO_STATUS_RCVD` and `WS_1005_ABNORMAL_CLOSURE` in favor of `WS_1005_NO_STATUS_RCVD` and `WS_1006_ABNORMAL_CLOSURE`, as the previous constants didn't match the [WebSockets specs](https://www.iana.org/assignments/websocket/websocket.xhtml) [#1580](https://github.com/Kludex/starlette/pull/1580).


## 0.19.0 (March 9, 2022)

### Added
* Error handler will always run, even if the error happens on a background task [#761](https://github.com/Kludex/starlette/pull/761).
* Add `headers` parameter to `HTTPException` [#1435](https://github.com/Kludex/starlette/pull/1435).
* Internal responses with `405` status code insert an `Allow` header, as described by [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.5) [#1436](https://github.com/Kludex/starlette/pull/1436).
* The `content` argument in `JSONResponse` is now required [#1431](https://github.com/Kludex/starlette/pull/1431).
* Add custom URL convertor register [#1437](https://github.com/Kludex/starlette/pull/1437).
* Add content disposition type parameter to `FileResponse` [#1266](https://github.com/Kludex/starlette/pull/1266).
* Add next query param with original request URL in requires decorator [#920](https://github.com/Kludex/starlette/pull/920).
* Add `raw_path` to `TestClient` scope [#1445](https://github.com/Kludex/starlette/pull/1445).
* Add union operators to `MutableHeaders` [#1240](https://github.com/Kludex/starlette/pull/1240).
* Display missing route details on debug page [#1363](https://github.com/Kludex/starlette/pull/1363).
* Change `anyio` required version range to `>=3.4.0,<5.0` [#1421](https://github.com/Kludex/starlette/pull/1421) and [#1460](https://github.com/Kludex/starlette/pull/1460).
* Add `typing-extensions>=3.10` requirement - used only on lower versions than Python 3.10 [#1475](https://github.com/Kludex/starlette/pull/1475).

### Fixed
* Prevent `BaseHTTPMiddleware` from hiding errors of `StreamingResponse` and mounted applications [#1459](https://github.com/Kludex/starlette/pull/1459).
* `SessionMiddleware` uses an explicit `path=...`, instead of defaulting to the ASGI 'root_path' [#1512](https://github.com/Kludex/starlette/pull/1512).
* `Request.client` is now compliant with the ASGI specifications [#1462](https://github.com/Kludex/starlette/pull/1462).
* Raise `KeyError` at early stage for missing boundary [#1349](https://github.com/Kludex/starlette/pull/1349).

### Deprecated
* Deprecate WSGIMiddleware in favor of a2wsgi [#1504](https://github.com/Kludex/starlette/pull/1504).
* Deprecate `run_until_first_complete` [#1443](https://github.com/Kludex/starlette/pull/1443).


## 0.18.0 (January 23, 2022)

### Added
* Change default chunk size from 4Kb to 64Kb on `FileResponse` [#1345](https://github.com/Kludex/starlette/pull/1345).
* Add support for `functools.partial` in `WebSocketRoute` [#1356](https://github.com/Kludex/starlette/pull/1356).
* Add `StaticFiles` packages with directory [#1350](https://github.com/Kludex/starlette/pull/1350).
* Allow environment options in `Jinja2Templates` [#1401](https://github.com/Kludex/starlette/pull/1401).
* Allow HEAD method on `HttpEndpoint` [#1346](https://github.com/Kludex/starlette/pull/1346).
* Accept additional headers on `websocket.accept` message [#1361](https://github.com/Kludex/starlette/pull/1361) and [#1422](https://github.com/Kludex/starlette/pull/1422).
* Add `reason` to `WebSocket` close ASGI event [#1417](https://github.com/Kludex/starlette/pull/1417).
* Add headers attribute to `UploadFile` [#1382](https://github.com/Kludex/starlette/pull/1382).
* Don't omit `Content-Length` header for `Content-Length: 0` cases [#1395](https://github.com/Kludex/starlette/pull/1395).
* Don't set headers for responses with 1xx, 204 and 304 status code [#1397](https://github.com/Kludex/starlette/pull/1397).
* `SessionMiddleware.max_age` now accepts `None`, so cookie can last as long as the browser session [#1387](https://github.com/Kludex/starlette/pull/1387).

### Fixed
* Tweak `hashlib.md5()` function on `FileResponse`s ETag generation. The parameter [`usedforsecurity`](https://bugs.python.org/issue9216) flag is set to `False`, if the flag is available on the system. This fixes an error raised on systems with [FIPS](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/FIPS_Mode_-_an_explanation) enabled [#1366](https://github.com/Kludex/starlette/pull/1366) and [#1410](https://github.com/Kludex/starlette/pull/1410).
* Fix `path_params` type on `url_path_for()` method i.e. turn `str` into `Any` [#1341](https://github.com/Kludex/starlette/pull/1341).
* `Host` now ignores `port` on routing [#1322](https://github.com/Kludex/starlette/pull/1322).

## 0.17.1 (November 17, 2021)

### Fixed
* Fix `IndexError` in authentication `requires` when wrapped function arguments are distributed between `*args` and `**kwargs` [#1335](https://github.com/Kludex/starlette/pull/1335).

## 0.17.0 (November 4, 2021)

### Added
* `Response.delete_cookie` now accepts the same parameters as `Response.set_cookie` [#1228](https://github.com/Kludex/starlette/pull/1228).
* Update the `Jinja2Templates` constructor to allow `PathLike` [#1292](https://github.com/Kludex/starlette/pull/1292).

### Fixed
* Fix BadSignature exception handling in SessionMiddleware [#1264](https://github.com/Kludex/starlette/pull/1264).
* Change `HTTPConnection.__getitem__` return type from `str` to `typing.Any` [#1118](https://github.com/Kludex/starlette/pull/1118).
* Change `ImmutableMultiDict.getlist` return type from `typing.List[str]` to `typing.List[typing.Any]` [#1235](https://github.com/Kludex/starlette/pull/1235).
* Handle `OSError` exceptions on `StaticFiles` [#1220](https://github.com/Kludex/starlette/pull/1220).
* Fix `StaticFiles` 404.html in HTML mode [#1314](https://github.com/Kludex/starlette/pull/1314).
* Prevent anyio.ExceptionGroup in error views under a BaseHTTPMiddleware [#1262](https://github.com/Kludex/starlette/pull/1262).

### Removed
* Remove GraphQL support [#1198](https://github.com/Kludex/starlette/pull/1198).

## 0.16.0 (July 19, 2021)

### Added
 * Added [Encode](https://github.com/sponsors/encode) funding option
   [#1219](https://github.com/Kludex/starlette/pull/1219)

### Fixed
 * `starlette.websockets.WebSocket` instances are now hashable and compare by identity
    [#1039](https://github.com/Kludex/starlette/pull/1039)
 * A number of fixes related to running task groups in lifespan
   [#1213](https://github.com/Kludex/starlette/pull/1213),
   [#1227](https://github.com/Kludex/starlette/pull/1227)

### Deprecated/removed
 * The method `starlette.templates.Jinja2Templates.get_env` was removed
   [#1218](https://github.com/Kludex/starlette/pull/1218)
 * The ClassVar `starlette.testclient.TestClient.async_backend` was removed,
   the backend is now configured using constructor kwargs
   [#1211](https://github.com/Kludex/starlette/pull/1211)
 * Passing an Async Generator Function or a Generator Function to `starlette.routing.Router(lifespan=)` is deprecated. You should wrap your lifespan in `@contextlib.asynccontextmanager`.
   [#1227](https://github.com/Kludex/starlette/pull/1227)
   [#1110](https://github.com/Kludex/starlette/pull/1110)

## 0.15.0 (June 23, 2021)

This release includes major changes to the low-level asynchronous parts of Starlette. As a result,
**Starlette now depends on [AnyIO](https://anyio.readthedocs.io/en/stable/)** and some minor API
changes have occurred. Another significant change with this release is the
**deprecation of built-in GraphQL support**.

### Added
* Starlette now supports [Trio](https://trio.readthedocs.io/en/stable/) as an async runtime via
  AnyIO - [#1157](https://github.com/Kludex/starlette/pull/1157).
* `TestClient.websocket_connect()` now must be used as a context manager.
* Initial support for Python 3.10 - [#1201](https://github.com/Kludex/starlette/pull/1201).
* The compression level used in `GZipMiddleware` is now adjustable -
  [#1128](https://github.com/Kludex/starlette/pull/1128).

### Fixed
* Several fixes to `CORSMiddleware`. See [#1111](https://github.com/Kludex/starlette/pull/1111),
  [#1112](https://github.com/Kludex/starlette/pull/1112),
  [#1113](https://github.com/Kludex/starlette/pull/1113),
  [#1199](https://github.com/Kludex/starlette/pull/1199).
* Improved exception messages in the case of duplicated path parameter names -
  [#1177](https://github.com/Kludex/starlette/pull/1177).
* `RedirectResponse` now uses `quote` instead of `quote_plus` encoding for the `Location` header
  to better match the behaviour in other frameworks such as Django -
  [#1164](https://github.com/Kludex/starlette/pull/1164).
* Exception causes are now preserved in more cases -
  [#1158](https://github.com/Kludex/starlette/pull/1158).
* Session cookies now use the ASGI root path in the case of mounted applications -
  [#1147](https://github.com/Kludex/starlette/pull/1147).
* Fixed a cache invalidation bug when static files were deleted in certain circumstances -
  [#1023](https://github.com/Kludex/starlette/pull/1023).
* Improved memory usage of `BaseHTTPMiddleware` when handling large responses -
  [#1012](https://github.com/Kludex/starlette/issues/1012) fixed via #1157

### Deprecated/removed

* Built-in GraphQL support via the `GraphQLApp` class has been deprecated and will be removed in a
  future release. Please see [#619](https://github.com/Kludex/starlette/issues/619). GraphQL is not
  supported on Python 3.10.
* The `executor` parameter to `GraphQLApp` was removed. Use `executor_class` instead.
* The `workers` parameter to `WSGIMiddleware` was removed. This hasn't had any effect since
  Starlette v0.6.3.

## 0.14.2 (February 2, 2021)

### Fixed

* Fixed `ServerErrorMiddleware` compatibility with Python 3.9.1/3.8.7 when debug mode is enabled -
  [#1132](https://github.com/Kludex/starlette/pull/1132).
* Fixed unclosed socket `ResourceWarning`s when using the `TestClient` with WebSocket endpoints -
  #1132.
* Improved detection of `async` endpoints wrapped in `functools.partial` on Python 3.8+ -
  [#1106](https://github.com/Kludex/starlette/pull/1106).


## 0.14.1 (November 9th, 2020)

### Removed

* `UJSONResponse` was removed (this change was intended to be included in 0.14.0). Please see the
  [documentation](https://starlette.dev/responses/#custom-json-serialization) for how to
  implement responses using custom JSON serialization -
  [#1074](https://github.com/Kludex/starlette/pull/1047).

## 0.14.0 (November 8th, 2020)

### Added

* Starlette now officially supports Python3.9.
* In `StreamingResponse`, allow custom async iterator such as objects from classes implementing `__aiter__`.
* Allow usage of `functools.partial` async handlers in Python versions 3.6 and 3.7.
* Add 418 I'm A Teapot status code.

### Changed

* Create tasks from handler coroutines before sending them to `asyncio.wait`.
* Use `format_exception` instead of `format_tb` in `ServerErrorMiddleware`'s `debug` responses.
* Be more lenient with handler arguments when using the `requires` decorator.

## 0.13.8

* Revert `Queue(maxsize=1)` fix for `BaseHTTPMiddleware` middleware classes and streaming responses.

* The `StaticFiles` constructor now allows `pathlib.Path` in addition to strings for its `directory` argument.

## 0.13.7

* Fix high memory usage when using `BaseHTTPMiddleware` middleware classes and streaming responses.

## 0.13.6

* Fix 404 errors with `StaticFiles`.

## 0.13.5

* Add support for `Starlette(lifespan=...)` functions.
* More robust path-traversal check in StaticFiles app.
* Fix WSGI PATH_INFO encoding.
* RedirectResponse now accepts optional background parameter
* Allow path routes to contain regex meta characters
* Treat ASGI HTTP 'body' as an optional key.
* Don't use thread pooling for writing to in-memory upload files.

## 0.13.0

* Switch to promoting application configuration on init style everywhere.
  This means dropping the decorator style in favour of declarative routing
  tables and middleware definitions.

## 0.12.12

* Fix `request.url_for()` for the Mount-within-a-Mount case.

## 0.12.11

* Fix `request.url_for()` when an ASGI `root_path` is being used.

## 0.12.1

* Add `URL.include_query_params(**kwargs)`
* Add `URL.replace_query_params(**kwargs)`
* Add `URL.remove_query_params(param_names)`
* `request.state` properly persisting across middleware.
* Added `request.scope` interface.

## 0.12.0

* Switch to ASGI 3.0.
* Fixes to CORS middleware.
* Add `StaticFiles(html=True)` support.
* Fix path quoting in redirect responses.

## 0.11.1

* Add `request.state` interface, for storing arbitrary additional information.
* Support disabling GraphiQL with `GraphQLApp(..., graphiql=False)`.

## 0.11.0

* `DatabaseMiddleware` is now dropped in favour of `databases`
* Templates are no longer configured on the application instance. Use `templates = Jinja2Templates(directory=...)` and `return templates.TemplateResponse('index.html', {"request": request})`
* Schema generation is no longer attached to the application instance. Use `schemas = SchemaGenerator(...)` and `return schemas.OpenAPIResponse(request=request)`
* `LifespanMiddleware` is dropped in favor of router-based lifespan handling.
* Application instances now accept a `routes` argument, `Starlette(routes=[...])`
* Schema generation now includes mounted routes.

## 0.10.6

* Add `Lifespan` routing component.

## 0.10.5

* Ensure `templating` does not strictly require `jinja2` to be installed.

## 0.10.4

* Templates are now configured independently from the application instance. `templates = Jinja2Templates(directory=...)`. Existing API remains in place, but is no longer documented,
and will be deprecated in due course. See the template documentation for more details.

## 0.10.3

* Move to independent `databases` package instead of `DatabaseMiddleware`. Existing API
remains in place, but is no longer documented, and will be deprecated in due course.

## 0.10.2

* Don't drop explicit port numbers on redirects from `HTTPSRedirectMiddleware`.

## 0.10.1

* Add MySQL database support.
* Add host-based routing.

## 0.10.0

* WebSockets now default to sending/receiving JSON over text data frames. Use `.send_json(data, mode="binary")` and `.receive_json(mode="binary")` for binary framing.
* `GraphQLApp` now takes an `executor_class` argument, which should be used in preference to the existing `executor` argument. Resolves an issue with async executors being instantiated before the event loop was setup. The `executor` argument is expected to be deprecated in the next median or major release.
* Authentication and the `@requires` decorator now support WebSocket endpoints.
* `MultiDict` and `ImmutableMultiDict` classes are available in `uvicorn.datastructures`.
* `QueryParams` is now instantiated with standard dict-style `*args, **kwargs` arguments.

## 0.9.11

* Session cookies now include browser 'expires', in addition to the existing signed expiry.
* `request.form()` now returns a multi-dict interface.
* The query parameter multi-dict implementation now mirrors `dict` more correctly for the
behavior of `.keys()`, `.values()`, and `.items()` when multiple same-key items occur.
* Use `urlsplit` throughout in favor of `urlparse`.

## 0.9.10

* Support `@requires(...)` on class methods.
* Apply URL escaping to form data.
* Support `HEAD` requests automatically.
* Add `await request.is_disconnected()`.
* Pass operationName to GraphQL executor.

## 0.9.9

* Add `TemplateResponse`.
* Add `CommaSeparatedStrings` datatype.
* Add `BackgroundTasks` for multiple tasks.
* Common subclass for `Request` and `WebSocket`, to eg. share `session` functionality.
* Expose remote address with `request.client`.

## 0.9.8

* Add `request.database.executemany`.

## 0.9.7

* Ensure that `AuthenticationMiddleware` handles lifespan messages correctly.

## 0.9.6

* Add `AuthenticationMiddleware`, and `@requires()` decorator.

## 0.9.5

* Support either `str` or `Secret` for `SessionMiddleware(secret_key=...)`.

## 0.9.4

* Add `config.environ`.
* Add `datastructures.Secret`.
* Add `datastructures.DatabaseURL`.

## 0.9.3

* Add `config.Config(".env")`

## 0.9.2

* Add optional database support.
* Add `request` to GraphQL context.
* Hide any password component in `URL.__repr__`.

## 0.9.1

* Handle startup/shutdown errors properly.

## 0.9.0

* `TestClient` can now be used as a context manager, instead of `LifespanContext`.
* Lifespan is now handled as middleware. Startup and Shutdown events are
visible throughout the middleware stack.

## 0.8.8

* Better support for third-party API schema generators.

## 0.8.7

* Support chunked requests with TestClient.
* Cleanup asyncio tasks properly with WSGIMiddleware.
* Support using TestClient within endpoints, for service mocking.

## 0.8.6

* Session cookies are now set on the root path.

## 0.8.5

* Support URL convertors.
* Support HTTP 304 cache responses from `StaticFiles`.
* Resolve character escaping issue with form data.

## 0.8.4

* Default to empty body on responses.

## 0.8.3

* Add 'name' argument to `@app.route()`.
* Use 'Host' header for URL reconstruction.

## 0.8.2

### StaticFiles

* StaticFiles no longer reads the file for responses to `HEAD` requests.

## 0.8.1

### Templating

* Add a default templating configuration with Jinja2.

Allows the following:

```python
app = Starlette(template_directory="templates")

@app.route('/')
async def homepage(request):
    # `url_for` is available inside the template.
    template = app.get_template('index.html')
    content = template.render(request=request)
    return HTMLResponse(content)
```

## 0.8.0

### Exceptions

* Add support for `@app.exception_handler(404)`.
* Ensure handled exceptions are not seen as errors by the middleware stack.

### SessionMiddleware

* Add `max_age`, and use timestamp-signed cookies. Defaults to two weeks.

### Cookies

* Ensure cookies are strictly HTTP correct.

### StaticFiles

* Check directory exists on instantiation.

## 0.7.4

### Concurrency

* Add `starlette.concurrency.run_in_threadpool`. Now handles `contextvar` support.

## 0.7.3

### Routing

* Add `name=` support to `app.mount()`. This allows eg: `app.mount('/static', StaticFiles(directory='static'), name='static')`.

## 0.7.2

### Middleware

* Add support for `@app.middleware("http")` decorator.

### Routing

* Add "endpoint" to ASGI scope.

## 0.7.1

### Debug tracebacks

* Improve debug traceback information & styling.

### URL routing

* Support mounted URL lookups with "path=", eg. `url_for('static', path=...)`.
* Support nested URL lookups, eg. `url_for('admin:user', username=...)`.
* Add redirect slashes support.
* Add www redirect support.

### Background tasks

* Add background task support to `FileResponse` and `StreamingResponse`.

## 0.7.0

### API Schema support

* Add `app.schema_generator = SchemaGenerator(...)`.
* Add `app.schema` property.
* Add `OpenAPIResponse(...)`.

### GraphQL routing

* Drop `app.add_graphql_route("/", ...)` in favor of more consistent `app.add_route("/", GraphQLApp(...))`.

## 0.6.3

### Routing API

* Support routing to methods.
* Ensure `url_path_for` works with Mount('/{some_path_params}').
* Fix Router(default=) argument.
* Support repeated paths, like: `@app.route("/", methods=["GET"])`, `@app.route("/", methods=["POST"])`
* Use the default ThreadPoolExecutor for all sync endpoints.

## 0.6.2

### SessionMiddleware

Added support for `request.session`, with `SessionMiddleware`.

## 0.6.1

### BaseHTTPMiddleware

Added support for `BaseHTTPMiddleware`, which provides a standard
request/response interface over a regular ASGI middleware.

This means you can write ASGI middleware while still working at
a request/response level, rather than handling ASGI messages directly.

```python
from starlette.applications import Starlette
from starlette.middleware.base import BaseHTTPMiddleware


class CustomMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        response.headers['Custom-Header'] = 'Example'
        return response


app = Starlette()
app.add_middleware(CustomMiddleware)
```

## 0.6.0

### request.path_params

The biggest change in 0.6 is that endpoint signatures are no longer:

```python
async def func(request: Request, **kwargs) -> Response
```

Instead we just use:

```python
async def func(request: Request) -> Response
```

The path parameters are available on the request as `request.path_params`.

This is different to most Python webframeworks, but I think it actually ends up
being much more nicely consistent all the way through.

### request.url_for()

Request and WebSocketSession now support URL reversing with `request.url_for(name, **path_params)`.
This method returns a fully qualified `URL` instance.
The URL instance is a string-like object.

### app.url_path_for()

Applications now support URL path reversing with `app.url_path_for(name, **path_params)`.
This method returns a `URL` instance with the path and scheme set.
The URL instance is a string-like object, and will return only the path if coerced to a string.

### app.routes

Applications now support a `.routes` parameter, which returns a list of `[Route|WebSocketRoute|Mount]`.

### Route, WebSocketRoute, Mount

The low level components to `Router` now match the `@app.route()`, `@app.websocket_route()`, and `app.mount()` signatures.
</file>

<file path="docs/requests.md">
Starlette includes a `Request` class that gives you a nicer interface onto
the incoming request, rather than accessing the ASGI scope and receive channel directly.

### Request

Signature: `Request(scope, receive, send)`

```python
from starlette.requests import Request
from starlette.responses import Response


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    request = Request(scope, receive)
    content = '%s %s' % (request.method, request.url.path)
    response = Response(content, media_type='text/plain')
    await response(scope, receive, send)
```

Requests present a mapping interface, so you can use them in the same
way as a `scope`.

For instance: `request['path']` will return the ASGI path.

Pass `receive` to read the request body or check for client disconnects.
Pass `send` only if you need [server push](server-push.md).

#### Method

The request method is accessed as `request.method`.

#### URL

The request URL is accessed as `request.url`.

The property is a string-like object that exposes all the
components that can be parsed out of the URL.

For example: `request.url.path`, `request.url.port`, `request.url.scheme`.

#### Headers

Headers are exposed as an immutable, case-insensitive, multi-dict.

For example: `request.headers['content-type']`

#### Query Parameters

Query parameters are exposed as an immutable multi-dict.

For example: `request.query_params['search']`

#### Path Parameters

Router path parameters are exposed as a dictionary interface.

For example: `request.path_params['username']`

#### Client Address

The client's remote address is exposed as a named two-tuple `request.client` (or `None`).

The hostname or IP address: `request.client.host`

The port number from which the client is connecting: `request.client.port`

#### Cookies

Cookies are exposed as a regular dictionary interface.

For example: `request.cookies.get('mycookie')`

Cookies are ignored in case of an invalid cookie. (RFC2109)

#### Body

There are a few different interfaces for returning the body of the request:

The request body as bytes: `await request.body()`

The request body, parsed as form data or multipart: `async with request.form() as form:`

The request body, parsed as JSON: `await request.json()`

You can also access the request body as a stream, using the `async for` syntax:

```python
from starlette.requests import Request
from starlette.responses import Response


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    request = Request(scope, receive)
    body = b''
    async for chunk in request.stream():
        body += chunk
    response = Response(body, media_type='text/plain')
    await response(scope, receive, send)
```

If you access `.stream()` then the byte chunks are provided without storing
the entire body to memory. Any subsequent calls to `.body()`, `.form()`, or `.json()`
will raise an error.

In some cases such as long-polling, or streaming responses you might need to
determine if the client has dropped the connection. You can determine this
state with `disconnected = await request.is_disconnected()`.

#### Request Files

Request files are normally sent as multipart form data (`multipart/form-data`).

Signature: `request.form(max_files=1000, max_fields=1000, max_part_size=1024*1024)`

You can configure the maximum number of fields or files with `max_files` and
`max_fields`. The `max_part_size` parameter limits the size of each non-file
field; uploaded files are spooled to temporary storage and are not limited by
`max_part_size`:

```python
async with request.form(max_files=1000, max_fields=1000, max_part_size=1024*1024):
    ...
```

!!! info
    These limits are for security reasons, allowing an unlimited number of fields or files could lead to a denial of service attack by consuming a lot of CPU and memory parsing too many empty fields.

To limit the complete request body, including uploaded files and multipart
encoding overhead, configure `max_body_size` on the application, router, mount,
or route, or use `RequestBodyLimitMiddleware`.

When you call `async with request.form() as form` you receive a `starlette.datastructures.FormData` which is an immutable
multidict, containing both file uploads and text input. File upload items are represented as instances of `starlette.datastructures.UploadFile`.

`UploadFile` has the following attributes:

* `filename`: An `str` with the original file name that was uploaded or `None` if it's not available (e.g. `myimage.jpg`).
* `content_type`: An `str` with the content type (MIME type / media type) or `None` if it's not available (e.g. `image/jpeg`).
* `file`: A <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" target="_blank">`SpooledTemporaryFile`</a> (a <a href="https://docs.python.org/3/glossary.html#term-file-like-object" target="_blank">file-like</a> object). This is the actual Python file that you can pass directly to other functions or libraries that expect a "file-like" object.
* `headers`: A `Headers` object. Often this will only be the `Content-Type` header, but if additional headers were included in the multipart field they will be included here. Note that these headers have no relationship with the headers in `Request.headers`.
* `size`: An `int` with uploaded file's size in bytes. This value is calculated from request's contents, making it better choice to find uploaded file's size than `Content-Length` header. `None` if not set.

`UploadFile` has the following `async` methods. They all call the corresponding file methods underneath (using the internal `SpooledTemporaryFile`).

* `async write(data)`: Writes `data` (`bytes`) to the file.
* `async read(size)`: Reads `size` (`int`) bytes of the file.
* `async seek(offset)`: Goes to the byte position `offset` (`int`) in the file.
    * E.g., `await myfile.seek(0)` would go to the start of the file.
* `async close()`: Closes the file.

As all these methods are `async` methods, you need to "await" them.

For example, you can get the file name and the contents with:

```python
async with request.form() as form:
    filename = form["upload_file"].filename
    contents = await form["upload_file"].read()
```

!!! info
    As settled in [RFC-7578: 4.2](https://www.ietf.org/rfc/rfc7578.txt), form-data content part that contains file
    assumed to have `name` and `filename` fields in `Content-Disposition` header: `Content-Disposition: form-data;
    name="user"; filename="somefile"`. Though `filename` field is optional according to RFC-7578, it helps
    Starlette to differentiate which data should be treated as file. If `filename` field was supplied, `UploadFile`
    object will be created to access underlying file, otherwise form-data part will be parsed and available as a raw
    string.

#### Application

The originating Starlette application can be accessed via `request.app`.

#### Other state

If you want to store additional information on the request you can do so
using `request.state`.

For example:

`request.state.time_started = time.time()`
</file>

<file path="docs/responses.md">
Starlette includes a few response classes that handle sending back the
appropriate ASGI messages on the `send` channel.

### Response

Signature: `Response(content, status_code=200, headers=None, media_type=None)`

* `content` - A string or bytestring.
* `status_code` - An integer HTTP status code.
* `headers` - A dictionary of strings.
* `media_type` - A string giving the media type. eg. "text/html"

Starlette will automatically include a Content-Length header. It will also
include a Content-Type header, based on the media_type and appending a charset
for text types, unless a charset has already been specified in the `media_type`.

Once you've instantiated a response, you can send it by calling it as an
ASGI application instance.

```python
from starlette.responses import Response


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = Response('Hello, world!', media_type='text/plain')
    await response(scope, receive, send)
```
#### Set Cookie

Starlette provides a `set_cookie` method to allow you to set cookies on the response object.

Signature: `Response.set_cookie(key, value, max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite="lax", partitioned=False)`

* `key` - A string that will be the cookie's key.
* `value` - A string that will be the cookie's value.
* `max_age` - An integer that defines the lifetime of the cookie in seconds. A negative integer or a value of `0` will discard the cookie immediately. `Optional`
* `expires` - Either an integer that defines the number of seconds until the cookie expires, or a datetime. `Optional`
* `path` - A string that specifies the subset of routes to which the cookie will apply. `Optional`
* `domain` - A string that specifies the domain for which the cookie is valid. `Optional`
* `secure` - A bool indicating that the cookie will only be sent to the server if request is made using SSL and the HTTPS protocol. `Optional`
* `httponly` - A bool indicating that the cookie cannot be accessed via JavaScript through `Document.cookie` property, the `XMLHttpRequest` or `Request` APIs. `Optional`
* `samesite` - A string that specifies the samesite strategy for the cookie. Valid values are `'lax'`, `'strict'` and `'none'`. Defaults to `'lax'`. `Optional`
* `partitioned` - A bool that indicates to user agents that these cross-site cookies should only be available in the same top-level context that the cookie was first set in. Only available for Python 3.14+, otherwise an error will be raised. `Optional`

#### Delete Cookie

Conversely, Starlette also provides a `delete_cookie` method to manually expire a set cookie.

Signature: `Response.delete_cookie(key, path='/', domain=None, secure=False, httponly=False, samesite="lax", partitioned=False)`

To delete a partitioned cookie on Python 3.14+:

```python
from starlette.responses import Response

response = Response()
response.delete_cookie("session", secure=True, samesite="none", partitioned=True)
```

Pass `partitioned=True` to expire the cookie in the current partition. It defaults to `False`.
Use the same `path` and `domain` as the original cookie, within the same top-level site context.
For cross-site requests, use `samesite="none"`.

!!! warning "Partitioned cookies require Secure"
    Pass `secure=True` when deleting a partitioned cookie over HTTPS.
    Browsers reject the expiration header if it includes `Partitioned` without `Secure`.


### HTMLResponse

Takes some text or bytes and returns an HTML response.

```python
from starlette.responses import HTMLResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = HTMLResponse('<html><body><h1>Hello, world!</h1></body></html>')
    await response(scope, receive, send)
```

### PlainTextResponse

Takes some text or bytes and returns a plain text response.

```python
from starlette.responses import PlainTextResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)
```

### JSONResponse

Takes some data and returns an `application/json` encoded response.

```python
from starlette.responses import JSONResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = JSONResponse({'hello': 'world'})
    await response(scope, receive, send)
```

#### Custom JSON serialization

If you need fine-grained control over JSON serialization, you can subclass
`JSONResponse` and override the `render` method.

For example, if you wanted to use a third-party JSON library such as
[orjson](https://pypi.org/project/orjson/):

```python
from typing import Any

import orjson
from starlette.responses import JSONResponse


class OrjsonResponse(JSONResponse):
    def render(self, content: Any) -> bytes:
        return orjson.dumps(content)
```

In general you *probably* want to stick with `JSONResponse` by default unless
you are micro-optimising a particular endpoint or need to serialize non-standard
object types.

### RedirectResponse

Returns an HTTP redirect. Uses a 307 status code by default.

```python
from starlette.responses import PlainTextResponse, RedirectResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    if scope['path'] != '/':
        response = RedirectResponse(url='/')
    else:
        response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)
```

### StreamingResponse

Takes an async generator or a normal generator/iterator and streams the response body.

```python
from starlette.responses import StreamingResponse
import asyncio


async def slow_numbers(minimum, maximum):
    yield '<html><body><ul>'
    for number in range(minimum, maximum + 1):
        yield '<li>%d</li>' % number
        await asyncio.sleep(0.5)
    yield '</ul></body></html>'


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    generator = slow_numbers(1, 10)
    response = StreamingResponse(generator, media_type='text/html')
    await response(scope, receive, send)
```

Have in mind that <a href="https://docs.python.org/3/glossary.html#term-file-like-object" target="_blank">file-like</a> objects (like those created by `open()`) are normal iterators. So, you can return them directly in a `StreamingResponse`.

### FileResponse

Asynchronously streams a file as the response.

Takes a different set of arguments to instantiate than the other response types:

* `path` - The filepath to the file to stream.
* `headers` - Any custom headers to include, as a dictionary.
* `media_type` - A string giving the media type. If unset, the filename or path will be used to infer a media type.
* `filename` - If set, this will be included in the response `Content-Disposition`.
* `content_disposition_type` - will be included in the response `Content-Disposition`. Can be set to "attachment" (default) or "inline".

File responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers.

```python
from starlette.responses import FileResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = FileResponse('statics/favicon.ico')
    await response(scope, receive, send)
```

File responses also supports [HTTP range requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests).

The `Accept-Ranges: bytes` header will be included in the response if the file exists. For now, only the `bytes`
range unit is supported.

If the request includes a `Range` header, and the file exists, the response will be a `206 Partial Content` response
with the requested range of bytes. If the range is invalid, the response will be a `416 Range Not Satisfiable` response.

## Third party responses

#### [EventSourceResponse](https://github.com/sysid/sse-starlette)

A response class that implements [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html). It enables event streaming from the server to the client without the complexity of websockets.
</file>

<file path="docs/routing.md">
## HTTP Routing

Starlette has a simple but capable request routing system. A routing table
is defined as a list of routes, and passed when instantiating the application.

```python
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route


async def homepage(request):
    return PlainTextResponse("Homepage")

async def about(request):
    return PlainTextResponse("About")


routes = [
    Route("/", endpoint=homepage),
    Route("/about", endpoint=about),
]

app = Starlette(routes=routes)
```

The `endpoint` argument can be one of:

* A regular function or async function, which accepts a single `request`
argument and which should return a response.
* A class that implements the ASGI interface, such as Starlette's [HTTPEndpoint](endpoints.md#httpendpoint).

## Path Parameters

Paths can use URI templating style to capture path components.

```python
Route('/users/{username}', user)
```
By default this will capture characters up to the end of the path or the next `/`.

You can use convertors to modify what is captured. The available convertors are:

* `str` returns a string, and is the default.
* `int` returns a Python integer.
* `float` returns a Python float.
* `uuid` return a Python `uuid.UUID` instance.
* `path` returns the rest of the path, including any additional `/` characters.

Convertors are used by prefixing them with a colon, like so:

```python
Route('/users/{user_id:int}', user)
Route('/floating-point/{number:float}', floating_point)
Route('/uploaded/{rest_of_path:path}', uploaded)
```

If you need a different converter that is not defined, you can create your own.
See below an example on how to create a `datetime` convertor, and how to register it:

```python
from datetime import datetime

from starlette.convertors import Convertor, register_url_convertor


class DateTimeConvertor(Convertor):
    regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(.[0-9]+)?"

    def convert(self, value: str) -> datetime:
        return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S")

    def to_string(self, value: datetime) -> str:
        return value.strftime("%Y-%m-%dT%H:%M:%S")

register_url_convertor("datetime", DateTimeConvertor())
```

After registering it, you'll be able to use it as:

```python
Route('/history/{date:datetime}', history)
```

Path parameters are made available in the request, as the `request.path_params`
dictionary.

```python
async def user(request):
    user_id = request.path_params['user_id']
    ...
```

## Handling HTTP methods

Routes can also specify which HTTP methods are handled by an endpoint:

```python
Route('/users/{user_id:int}', user, methods=["GET", "POST"])
```

By default function endpoints will only accept `GET` requests, unless specified.

## Submounting routes

In large applications you might find that you want to break out parts of the
routing table, based on a common path prefix.

```python
routes = [
    Route('/', homepage),
    Mount('/users', routes=[
        Route('/', users, methods=['GET', 'POST']),
        Route('/{username}', user),
    ])
]
```

This style allows you to define different subsets of the routing table in
different parts of your project.

```python
from myproject import users, auth

routes = [
    Route('/', homepage),
    Mount('/users', routes=users.routes),
    Mount('/auth', routes=auth.routes),
]
```

You can also use mounting to include sub-applications within your Starlette
application. For example...

```python
# This is a standalone static files server:
app = StaticFiles(directory="static")

# This is a static files server mounted within a Starlette application,
# underneath the "/static" path.
routes = [
    ...
    Mount("/static", app=StaticFiles(directory="static"), name="static")
]

app = Starlette(routes=routes)
```

## Reverse URL lookups

You'll often want to be able to generate the URL for a particular route,
such as in cases where you need to return a redirect response.

* Signature: `url_for(name, **path_params) -> URL`

```python
routes = [
    Route("/", homepage, name="homepage")
]

# We can use the following to return a URL...
url = request.url_for("homepage")
```

URL lookups can include path parameters...

```python
routes = [
    Route("/users/{username}", user, name="user_detail")
]

# We can use the following to return a URL...
url = request.url_for("user_detail", username=...)
```

If a `Mount` includes a `name`, then submounts should use a `{prefix}:{name}`
style for reverse URL lookups.

```python
routes = [
    Mount("/users", name="users", routes=[
        Route("/", user, name="user_list"),
        Route("/{username}", user, name="user_detail")
    ])
]

# We can use the following to return URLs...
url = request.url_for("users:user_list")
url = request.url_for("users:user_detail", username=...)
```

Mounted applications may include a `path=...` parameter.

```python
routes = [
    ...
    Mount("/static", app=StaticFiles(directory="static"), name="static")
]

# We can use the following to return URLs...
url = request.url_for("static", path="/css/base.css")
```

For cases where there is no `request` instance, you can make reverse lookups
against the application, although these will only return the URL path.

```python
url = app.url_path_for("user_detail", username=...)
```

## Host-based routing

If you want to use different routes for the same path based on the `Host` header.

Note that port is removed from the `Host` header when matching.
For example, `Host (host='example.org:3600', ...)` will be processed
even if the `Host` header contains or does not contain a port other than `3600`
(`example.org:5600`, `example.org`).
Therefore, you can specify the port if you need it for use in `url_for`.

There are several ways to connect host-based routes to your application

```python
site = Router(routes=[...])  # Add your `Route` entries here.
api = Router(routes=[...])  # Add your `Route` entries here.
news = Router(routes=[...])  # Add your `Route` entries here.

routes = [
    Host('api.example.org', api, name="site_api")
]

app = Starlette(routes=routes)

app.host('www.example.org', site, name="main_site")

news_host = Host('news.example.org', news)
app.router.routes.append(news_host)
```

URL lookups can include host parameters just like path parameters

```python
routes = [
    Host("{subdomain}.example.org", name="sub", app=Router(routes=[
        Mount("/users", name="users", routes=[
            Route("/", user, name="user_list"),
            Route("/{username}", user, name="user_detail")
        ])
    ]))
]
...
url = request.url_for("sub:users:user_detail", username=..., subdomain=...)
url = request.url_for("sub:users:user_list", subdomain=...)
```

## Route priority

Incoming paths are matched against each `Route` in order.

In cases where more that one route could match an incoming path, you should
take care to ensure that more specific routes are listed before general cases.

For example:

```python
# Don't do this: `/users/me` will never match incoming requests.
routes = [
    Route('/users/{username}', user),
    Route('/users/me', current_user),
]

# Do this: `/users/me` is tested first.
routes = [
    Route('/users/me', current_user),
    Route('/users/{username}', user),
]
```

## Working with Router instances

If you're working at a low-level you might want to use a plain `Router`
instance, rather that creating a `Starlette` application. This gives you
a lightweight ASGI application that just provides the application routing,
without wrapping it up in any middleware.

```python
app = Router(routes=[
    Route('/', homepage),
    Mount('/users', routes=[
        Route('/', users, methods=['GET', 'POST']),
        Route('/{username}', user),
    ])
])
```

## Request body size limits

Use a non-negative `max_body_size` to limit the total number of request body
bytes accepted by an application. The limit includes multipart file data and
multipart encoding overhead. It defaults to `None`, which preserves the existing
unlimited behavior.

```python
app = Starlette(
    routes=[
        Route("/", homepage),
        Route("/upload", upload, methods=["POST"], max_body_size=100 * 1024 * 1024),
    ],
    max_body_size=10 * 1024 * 1024,
)
```

`Router` and `Mount` also accept `max_body_size`. A limit on an inner route,
mount, or router overrides the outer limit after routing. This allows an upload
route to accept a larger body than the rest of the application.

Application middleware runs before routing. If such middleware reads the body,
the application-level limit applies to those bytes before a route can raise the
limit. Keep the application limit large enough for the largest legitimate route
when using body-consuming application middleware.

Starlette counts the actual body bytes received from the ASGI server.
`Content-Length` is used only to reject an oversized request early and is not
trusted to enforce the limit. A reverse proxy request-body limit and a quota on
temporary storage provide additional deployment-level safeguards.

## WebSocket Routing

When working with WebSocket endpoints, you should use `WebSocketRoute`
instead of the usual `Route`.

Path parameters, and reverse URL lookups for `WebSocketRoute` work the same
as HTTP `Route`, which can be found in the HTTP [Route](#http-routing) section above.

```python
from starlette.applications import Starlette
from starlette.routing import WebSocketRoute


async def websocket_index(websocket):
    await websocket.accept()
    await websocket.send_text("Hello, websocket!")
    await websocket.close()


async def websocket_user(websocket):
    name = websocket.path_params["name"]
    await websocket.accept()
    await websocket.send_text(f"Hello, {name}")
    await websocket.close()


routes = [
    WebSocketRoute("/", endpoint=websocket_index),
    WebSocketRoute("/{name}", endpoint=websocket_user),
]

app = Starlette(routes=routes)
```

The `endpoint` argument can be one of:

* An async function, which accepts a single `websocket` argument.
* A class that implements the ASGI interface, such as Starlette's [WebSocketEndpoint](endpoints.md#websocketendpoint).
</file>

<file path="docs/schemas.md">
Starlette supports generating API schemas, such as the widely used [OpenAPI
specification][openapi]. (Formerly known as "Swagger".)

Schema generation works by inspecting the routes on the application through
`app.routes`, and using the docstrings or other attributes on the endpoints
in order to determine a complete API schema.

Starlette is not tied to any particular schema generation or validation tooling,
but includes a simple implementation that generates OpenAPI schemas based on
the docstrings.

```python
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.schemas import SchemaGenerator


schemas = SchemaGenerator(
    {"openapi": "3.0.0", "info": {"title": "Example API", "version": "1.0"}}
)

def list_users(request):
    """
    responses:
      200:
        description: A list of users.
        examples:
          [{"username": "tom"}, {"username": "lucy"}]
    """
    raise NotImplementedError()


def create_user(request):
    """
    responses:
      200:
        description: A user.
        examples:
          {"username": "tom"}
    """
    raise NotImplementedError()


def openapi_schema(request):
    return schemas.OpenAPIResponse(request=request)


routes = [
    Route("/users", endpoint=list_users, methods=["GET"]),
    Route("/users", endpoint=create_user, methods=["POST"]),
    Route("/schema", endpoint=openapi_schema, include_in_schema=False)
]

app = Starlette(routes=routes)
```

We can now access an OpenAPI schema at the "/schema" endpoint.

You can generate the API Schema directly with `.get_schema(routes)`:

```python
schema = schemas.get_schema(routes=app.routes)
assert schema == {
    "openapi": "3.0.0",
    "info": {"title": "Example API", "version": "1.0"},
    "paths": {
        "/users": {
            "get": {
                "responses": {
                    200: {
                        "description": "A list of users.",
                        "examples": [{"username": "tom"}, {"username": "lucy"}],
                    }
                }
            },
            "post": {
                "responses": {
                    200: {"description": "A user.", "examples": {"username": "tom"}}
                }
            },
        },
    },
}
```

You might also want to be able to print out the API schema, so that you can
use tooling such as generating API documentation.

```python
if __name__ == '__main__':
    assert sys.argv[-1] in ("run", "schema"), "Usage: example.py [run|schema]"

    if sys.argv[-1] == "run":
        uvicorn.run("example:app", host='0.0.0.0', port=8000)
    elif sys.argv[-1] == "schema":
        schema = schemas.get_schema(routes=app.routes)
        print(yaml.dump(schema, default_flow_style=False))
```

### Third party packages

#### [starlette-apispec][starlette-apispec]

Easy APISpec integration for Starlette, which supports some object serialization libraries.

[openapi]: https://github.com/OAI/OpenAPI-Specification
[starlette-apispec]: https://github.com/Woile/starlette-apispec
</file>

<file path="docs/server-push.md">
Starlette includes support for HTTP/2 and HTTP/3 server push, making it
possible to push resources to the client to speed up page load times.

### `Request.send_push_promise`

Used to initiate a server push for a resource. If server push is not available
this method does nothing.

Signature: `send_push_promise(path)`

* `path` - A string denoting the path of the resource.

```python
from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.routing import Route, Mount
from starlette.staticfiles import StaticFiles


async def homepage(request):
    """
    Homepage which uses server push to deliver the stylesheet.
    """
    await request.send_push_promise("/static/style.css")
    return HTMLResponse(
        '<html><head><link rel="stylesheet" href="/static/style.css"/></head></html>'
    )

routes = [
    Route("/", endpoint=homepage),
    Mount("/static", StaticFiles(directory="static"), name="static")
]

app = Starlette(routes=routes)
```
</file>

<file path="docs/staticfiles.md">
Starlette also includes a `StaticFiles` class for serving files in a given directory:

### StaticFiles

Signature: `StaticFiles(directory=None, packages=None, html=False, check_dir=True, follow_symlink=False)`

* `directory` - A string or [os.PathLike][pathlike] denoting a directory path.
* `packages` - A list of strings or list of tuples of strings of python packages.
* `html` - Run in HTML mode. Automatically loads `index.html` for directories if such file exist.
* `check_dir` - Ensure that the directory exists upon instantiation. Defaults to `True`.
* `follow_symlink` - A boolean indicating if symbolic links for files and directories should be followed. Defaults to `False`.

You can combine this ASGI application with Starlette's routing to provide
comprehensive static file serving.

```python
from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles


routes = [
    ...
    Mount('/static', app=StaticFiles(directory='static'), name="static"),
]

app = Starlette(routes=routes)
```

Static files will respond with "404 Not found" or "405 Method not allowed"
responses for requests which do not match. In HTML mode if `404.html` file
exists it will be shown as 404 response.

The `packages` option can be used to include "static" directories contained within
a python package. The Python "bootstrap4" package is an example of this.

```python
from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles


routes=[
    ...
    Mount('/static', app=StaticFiles(directory='static', packages=['bootstrap4']), name="static"),
]

app = Starlette(routes=routes)
```

By default `StaticFiles` will look for a `statics` directory in each package,
you can change the default directory by specifying a tuple of strings.

```python
routes=[
    ...
    Mount('/static', app=StaticFiles(packages=[('bootstrap4', 'static')]), name="static"),
]
```

You may prefer to include static files directly inside the "static" directory
rather than using Python packaging to include static files, but it can be useful
for bundling up reusable components.

[pathlike]: https://docs.python.org/3/library/os.html#os.PathLike
</file>

<file path="docs/templates.md">
Starlette is not _strictly_ coupled to any particular templating engine, but
Jinja2 provides an excellent choice.

??? abstract "API Reference"
    ::: starlette.templating.Jinja2Templates
        options:
            parameter_headings: false
            show_root_heading: true
            heading_level: 3
            filters:
                - "__init__"

Starlette provides a simple way to get `jinja2` configured. This is probably
what you want to use by default.

```python
from starlette.applications import Starlette
from starlette.routing import Route, Mount
from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles


templates = Jinja2Templates(directory='templates')

async def homepage(request):
    return templates.TemplateResponse(request, 'index.html')

routes = [
    Route('/', endpoint=homepage),
    Mount('/static', StaticFiles(directory='static'), name='static')
]

app = Starlette(debug=True, routes=routes)
```

Note that the incoming `request` instance must be included as part of the
template context.

The Jinja2 template context will automatically include a `url_for` function,
so we can correctly hyperlink to other pages within the application.

For example, we can link to static files from within our HTML templates:

```html
<link href="{{ url_for('static', path='/css/bootstrap.min.css') }}" rel="stylesheet" />
```

If you want to use [custom filters][jinja2], you will need to update the `env`
property of `Jinja2Templates`:

```python
from commonmark import commonmark
from starlette.templating import Jinja2Templates

def marked_filter(text):
    return commonmark(text)

templates = Jinja2Templates(directory='templates')
templates.env.filters['marked'] = marked_filter
```


## Using custom jinja2.Environment instance

Starlette also accepts a preconfigured [`jinja2.Environment`](https://jinja.palletsprojects.com/en/3.0.x/api/#api) instance. 


```python
import jinja2
from starlette.templating import Jinja2Templates

env = jinja2.Environment(...)
templates = Jinja2Templates(env=env)
```


## Autoescape

When using the `directory` argument, Starlette enables autoescape by default for
`.html`, `.htm`, and `.xml` templates using [`jinja2.select_autoescape()`](https://jinja.palletsprojects.com/en/stable/api/#jinja2.select_autoescape).

This protects against Cross-Site Scripting (XSS) vulnerabilities by escaping
user-provided content before rendering it in the template. For example, if a user
submits `<script>alert('XSS')</script>` as their name, it will be rendered as
`&lt;script&gt;alert('XSS')&lt;/script&gt;` instead of being executed as JavaScript.

## Context processors

A context processor is a function that returns a dictionary to be merged into a template context.
Every function takes only one argument `request` and must return a dictionary to add to the context.

A common use case of template processors is to extend the template context with shared variables.

```python
import typing
from starlette.requests import Request

def app_context(request: Request) -> typing.Dict[str, typing.Any]:
    return {'app': request.app}
```

### Registering context templates

Pass context processors to `context_processors` argument of the `Jinja2Templates` class.

```python
import typing

from starlette.requests import Request
from starlette.templating import Jinja2Templates

def app_context(request: Request) -> typing.Dict[str, typing.Any]:
    return {'app': request.app}

templates = Jinja2Templates(
    directory='templates', context_processors=[app_context]
)
```

!!! info
    Asynchronous functions as context processors are not supported.

## Testing template responses

When using the test client, template responses include `.template` and `.context`
attributes.

```python
from starlette.testclient import TestClient


def test_homepage():
    client = TestClient(app)
    response = client.get("/")
    assert response.status_code == 200
    assert response.template.name == 'index.html'
    assert "request" in response.context
```

## Asynchronous template rendering

Jinja2 supports async template rendering, however as a general rule
we'd recommend that you keep your templates free from logic that invokes
database lookups, or other I/O operations.

Instead we'd recommend that you ensure that your endpoints perform all I/O,
for example, strictly evaluate any database queries within the view and
include the final results in the context.

[jinja2]: https://jinja.palletsprojects.com/en/3.0.x/api/?highlight=environment#writing-filters
[pathlike]: https://docs.python.org/3/library/os.html#os.PathLike
</file>

<file path="docs/testclient.md">
??? abstract "API Reference"
    ::: starlette.testclient.TestClient
        options:
            parameter_headings: false
            show_bases: false
            show_root_heading: true
            heading_level: 3
            filters:
                - "__init__"

The test client allows you to make requests against your ASGI application,
using the `httpx2` library.

!!! note
    The `TestClient` is built on `httpx2`. Plain `httpx` is still supported, but
    deprecated - install `httpx2` (included in `starlette[full]`) instead.

```python
from starlette.responses import HTMLResponse
from starlette.testclient import TestClient


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = HTMLResponse('<html><body>Hello, world!</body></html>')
    await response(scope, receive, send)


def test_app():
    client = TestClient(app)
    response = client.get('/')
    assert response.status_code == 200
```

The test client exposes the same interface as any other `httpx2` session.
In particular, note that the calls to make a request are just standard
function calls, not awaitables.

You can use any of `httpx2` standard API, such as authentication, session
cookies handling, or file uploads.

For example, to set headers on the TestClient you can do:

```python
client = TestClient(app)

# Set headers on the client for future requests
client.headers = {"Authorization": "..."}
response = client.get("/")

# Set headers for each request separately
response = client.get("/", headers={"Authorization": "..."})
```

And for example to send files with the TestClient:

```python
client = TestClient(app)

# Send a single file
with open("example.txt", "rb") as f:
    response = client.post("/form", files={"file": f})

# Send multiple files
with open("example.txt", "rb") as f1:
    with open("example.png", "rb") as f2:
        files = {"file1": f1, "file2": ("filename", f2, "image/png")}
        response = client.post("/form", files=files)
```

For more information you can check the `httpx2` [documentation](https://pydantic.dev/docs/httpx2/advanced/clients/).

By default the `TestClient` will raise any exceptions that occur in the
application. Occasionally you might want to test the content of 500 error
responses, rather than allowing the client to raise the server exception. In this
case you should use `client = TestClient(app, raise_server_exceptions=False)`.

!!! note

    If you want the `TestClient` to run the `lifespan` handler,
    you will need to use the `TestClient` as a context manager. It will
    not be triggered when the `TestClient` is instantiated. You can learn more about it
    [here](lifespan.md#running-lifespan-in-tests).

### HTTP trailers

The `TestClient` supports the ASGI HTTP trailer extension. Read trailing fields from
`response.extensions["http.response.trailers"]` after the request completes.

```python
from starlette.testclient import TestClient
from starlette.types import Receive, Scope, Send


async def app(scope: Scope, receive: Receive, send: Send) -> None:
    await send({
        "type": "http.response.start", "status": 200,
        "headers": [(b"trailer", b"x-result")], "trailers": True,
    })
    await send({"type": "http.response.body", "body": b"hello"})
    await send({"type": "http.response.trailers", "headers": [(b"x-result", b"complete")]})


def test_trailers() -> None:
    response = TestClient(app).get("/", headers={"TE": "trailers"})
    assert response.content == b"hello"
    assert response.extensions["http.response.trailers"] == [(b"x-result", b"complete")]
```

The extension contains a list of raw byte pairs. It preserves field order and duplicates
across multiple trailer messages. Trailers remain separate from `response.headers`.
Responses that do not declare trailers have no trailer extension on the result.

With `raise_server_exceptions=True`, invalid trailer ordering or returning without final
trailers raises an assertion error. With `raise_server_exceptions=False`, the result contains
only the trailers received before the application failed or returned.

The test transport captures ASGI trailers regardless of `TE` negotiation. It does not emulate
HTTP/2 framing or concurrent request and response streaming. Use a real server and client
to verify those transport behaviors.

### Debug information

The `TestClient` supports the ASGI [`http.response.debug`](https://asgi.readthedocs.io/en/latest/extensions.html#debug)
extension. The `info` dictionary sent by the application is available as
`response.extensions["http.response.debug"]`, which allows custom response classes to
expose additional debug information to tests.

This is useful when asserting on the response body would mean parsing it back. Consider
a response class that renders rows into a CSV file. By sending the rows through the
debug extension, tests can assert on the original data instead of the serialized body:

```python
import csv
import io

from starlette.responses import Response


class CSVResponse(Response):
    media_type = "text/csv"

    def __init__(self, rows):
        self.rows = rows
        buffer = io.StringIO()
        csv.writer(buffer).writerows(rows)
        super().__init__(buffer.getvalue())

    async def __call__(self, scope, receive, send):
        if "http.response.debug" in scope.get("extensions", {}):
            await send({"type": "http.response.debug", "info": {"rows": self.rows}})
        await super().__call__(scope, receive, send)


def test_export():
    client = TestClient(app)
    response = client.get("/export")
    rows = response.extensions["http.response.debug"]["rows"]
    assert rows[0] == ("id", "username", "joined")
    assert len(rows) == 101
```

Template responses use the same extension to expose the `.template` and `.context`
response attributes - see [testing template responses](templates.md#testing-template-responses).
The `info` dictionary is always available as `response.extensions["http.response.debug"]`,
even when it carries `template`/`context` keys.

### Change client address

By default, the TestClient will set the client host to `"testclient"` and the port to `50000`.

You can change the client address by setting the `client` attribute of the `TestClient` instance:

```python
client = TestClient(app, client=('localhost', 8000))
```

### Selecting the Async backend

`TestClient` takes arguments `backend` (a string) and `backend_options` (a dictionary).
These options are passed to `anyio.start_blocking_portal()`.
See the [anyio documentation](https://anyio.readthedocs.io/en/stable/basics.html#backend-options)
for more information about the accepted backend options.
By default, `asyncio` is used with default options.

To run `Trio`, pass `backend="trio"`. For example:

```python
def test_app():
    with TestClient(app, backend="trio") as client:
       ...
```

To run `asyncio` with `uvloop`, pass `backend_options={"use_uvloop": True}`.  For example:

```python
def test_app():
    with TestClient(app, backend_options={"use_uvloop": True}) as client:
       ...
```

### Testing WebSocket sessions

You can also test websocket sessions with the test client.

The `httpx2` library will be used to build the initial handshake, meaning you
can use the same authentication options and other headers between both http and
websocket testing.

```python
from starlette.testclient import TestClient
from starlette.websockets import WebSocket


async def app(scope, receive, send):
    assert scope['type'] == 'websocket'
    websocket = WebSocket(scope, receive=receive, send=send)
    await websocket.accept()
    await websocket.send_text('Hello, world!')
    await websocket.close()


def test_app():
    client = TestClient(app)
    with client.websocket_connect('/') as websocket:
        data = websocket.receive_text()
        assert data == 'Hello, world!'
```

The operations on session are standard function calls, not awaitables.

It's important to use the session within a context-managed `with` block. This
ensures that the background thread on which the ASGI application is properly
terminated, and that any exceptions that occur within the application are
always raised by the test client.

#### Establishing a test session

* `.websocket_connect(url, subprotocols=None, **options)` - Takes the same set of arguments as `httpx2.get()`.

May raise `starlette.websockets.WebSocketDisconnect` if the application does not accept the websocket connection.

`websocket_connect()` must be used as a context manager (in a `with` block).

!!! note
    The `params` argument is not supported by `websocket_connect`. If you need to pass query arguments, hard code it
    directly in the URL.

    ```python
    with client.websocket_connect('/path?foo=bar') as websocket:
        ...
    ```

#### Sending data

* `.send_text(data)` - Send the given text to the application.
* `.send_bytes(data)` - Send the given bytes to the application.
* `.send_json(data, mode="text")` - Send the given data to the application. Use `mode="binary"` to send JSON over binary data frames.

#### Receiving data

* `.receive_text()` - Wait for incoming text sent by the application and return it.
* `.receive_bytes()` - Wait for incoming bytestring sent by the application and return it.
* `.receive_json(mode="text")` - Wait for incoming json data sent by the application and return it. Use `mode="binary"` to receive JSON over binary data frames.

May raise `starlette.websockets.WebSocketDisconnect`.

#### Closing the connection

* `.close(code=1000)` - Perform a client-side close of the websocket connection.

### Asynchronous tests

Sometimes you will want to do async things outside of your application.
For example, you might want to check the state of your database after calling your app
using your existing async database client/infrastructure.

For these situations, using `TestClient` is difficult because it creates its own event loop and async
resources (like a database connection) often cannot be shared across event loops.
The simplest way to work around this is to just make your entire test async and use an async client, like [httpx2.AsyncClient].

Here is an example of such a test:

```python
from httpx2 import AsyncClient, ASGITransport
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.requests import Request
from starlette.responses import PlainTextResponse


def hello(request: Request) -> PlainTextResponse:
    return PlainTextResponse("Hello World!")


app = Starlette(routes=[Route("/", hello)])


# if you're using pytest, you'll need to add an async marker like:
# @pytest.mark.anyio  # using https://github.com/agronholm/anyio
# or install and configure pytest-asyncio (https://github.com/pytest-dev/pytest-asyncio)
async def test_app() -> None:
    # note: you _must_ set `base_url` for relative urls like "/" to work
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://testserver") as client:
        r = await client.get("/")
        assert r.status_code == 200
        assert r.text == "Hello World!"
```

!!! warning "A pytest event loop fixture does not configure TestClient"

    Defining an `event_loop` fixture does not make `TestClient` use that loop.
    For synchronous tests, create and close resources in [lifespan](lifespan.md#lifespan-state)
    and use [`TestClient` as a context manager](lifespan.md#running-lifespan-in-tests).

[httpx2.AsyncClient]: https://pydantic.dev/docs/httpx2/advanced/transports/#asgi-transport
</file>

<file path="docs/third-party-packages.md">
Starlette has a rapidly growing community of developers, building tools that integrate into Starlette, tools that depend on Starlette, etc.

Here are some of those third party packages:

## Plugins

### Apitally

<a href="https://github.com/apitally/apitally-py" target="_blank">GitHub</a> |
<a href="https://docs.apitally.io/frameworks/starlette" target="_blank">Documentation</a>

Analytics, request logging and monitoring for REST APIs built with Starlette (and other frameworks).

### Authlib

<a href="https://github.com/authlib/authlib" target="_blank">GitHub</a> |
<a href="https://docs.authlib.org/en/latest/" target="_blank">Documentation</a>

The ultimate Python library in building OAuth and OpenID Connect clients and servers. Check out how to integrate with [Starlette](https://docs.authlib.org/en/stable/oauth2/client/web/starlette.html).

### ChannelBox

<a href="https://github.com/Sobolev5/channel-box" target="_blank">GitHub Repository</a>

ChannelBox is a lightweight solution for WebSocket broadcasting in ASGI applications.
It allows sending messages to named WebSocket channel groups and integrates with Starlette and FastAPI.

### Mangum

<a href="https://github.com/Kludex/mangum" target="_blank">GitHub</a>

Serverless ASGI adapter for AWS Lambda & API Gateway.

### Scout APM

<a href="https://github.com/scoutapp/scout_apm_python" target="_blank">GitHub</a>

An APM (Application Performance Monitoring) solution that can
instrument your application to find performance bottlenecks.

### SpecTree

<a href="https://github.com/0b01001001/spectree" target="_blank">GitHub</a>

Generate OpenAPI spec document and validate request & response with Python annotations. Less boilerplate code(no need for YAML).

### Starlette APISpec

<a href="https://github.com/Woile/starlette-apispec" target="_blank">GitHub</a>

Simple APISpec integration for Starlette.
Document your REST API built with Starlette by declaring OpenAPI (Swagger)
schemas in YAML format in your endpoint's docstrings.

### Starlette Compress

<a href="https://github.com/Zaczero/starlette-compress" target="_blank">GitHub</a>

Starlette-Compress is a fast and simple middleware for compressing responses in Starlette.
It adds ZStd, Brotli, and GZip compression support with sensible default configuration.

### Starlette Context

<a href="https://github.com/tomwojcik/starlette-context" target="_blank">GitHub</a>

Middleware for Starlette that allows you to store and access the context data of a request.
Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.

### Starlette Cramjam

<a href="https://github.com/developmentseed/starlette-cramjam" target="_blank">GitHub</a>

A Starlette middleware that allows **brotli**, **gzip** and **deflate** compression algorithm with a minimal requirements.

### Starlette Prometheus

<a href="https://github.com/perdy/starlette-prometheus" target="_blank">GitHub</a>

A plugin for providing an endpoint that exposes [Prometheus](https://prometheus.io/) metrics based on its [official python client](https://github.com/prometheus/client_python).

### Starlette WTF

<a href="https://github.com/amorey/starlette-wtf" target="_blank">GitHub</a>

A simple tool for integrating Starlette and WTForms. It is modeled on the excellent Flask-WTF library.

### Starlette-Login

<a href="https://github.com/jockerz/Starlette-Login" target="_blank">GitHub</a> |
<a href="https://starlette-login.readthedocs.io/en/stable/" target="_blank">Documentation</a>

User session management for Starlette.
It handles the common tasks of logging in, logging out, and remembering your users' sessions over extended periods of time.


### Starsessions

<a href="https://github.com/alex-oleshkevich/starsessions" target="_blank">GitHub</a>

An alternate session support implementation with customizable storage backends.

### webargs-starlette

<a href="https://github.com/sloria/webargs-starlette" target="_blank">GitHub</a>

Declarative request parsing and validation for Starlette, built on top
of [webargs](https://github.com/marshmallow-code/webargs).

Allows you to parse querystring, JSON, form, headers, and cookies using
type annotations.

### Starception

<a href="https://github.com/alex-oleshkevich/starception" target="_blank">GitHub</a>

Beautiful exception page for Starlette apps.

### Starlette-Admin

<a href="https://github.com/jowilf/starlette-admin" target="_blank">GitHub</a> |
<a href="https://jowilf.github.io/starlette-admin" target="_blank">Documentation</a>

Simple and extensible admin interface framework.

Built with [Tabler](https://tabler.io/) and [Datatables](https://datatables.net/), it allows you
to quickly generate fully customizable admin interface for your models. You can export your data to many formats (*CSV*, *PDF*,
*Excel*, etc), filter your data with complex query including `AND` and `OR` conditions,  upload files, ...

### Vellox

<a href="https://github.com/junah201/vellox" target="_blank">GitHub</a>

Serverless ASGI adapter for GCP Cloud Functions.

### adminsite

<a href="https://github.com/nimaxin/adminsite" target="_blank">GitHub</a> |
<a href="https://nimaxin.github.io/adminsite/" target="_blank">Documentation</a>

An admin panel for SQLAlchemy 2.0 models. It is one ASGI app that you mount into Starlette, FastAPI or
Litestar, with search, filters, actions, permissions down to single rows and an audit log.

## Starlette Bridge

<a href="https://github.com/tarsil/starlette-bridge" target="_blank">GitHub</a> |
<a href="https://starlette-bridge.tarsild.io/" target="_blank">Documentation</a>

With the deprecation of `on_startup` and `on_shutdown`, Starlette Bridge makes sure you can still
use the old ways of declaring events with a particularity that internally, in fact, creates the
`lifespan` for you. This way backwards compatibility is assured for the existing packages out there
while maintaining the integrity of the newly `lifespan` events of `Starlette`.

## Frameworks

### FastAPI

<a href="https://github.com/fastapi/fastapi" target="_blank">GitHub</a> |
<a href="https://fastapi.tiangolo.com/" target="_blank">Documentation</a>

High performance, easy to learn, fast to code, ready for production web API framework.
Inspired by **APIStar**'s previous server system with type declarations for route parameters, based on the OpenAPI specification version 3.0.0+ (with JSON Schema), powered by **Pydantic** for the data handling.

### Flama

<a href="https://github.com/vortico/flama" target="_blank">GitHub</a> |
<a href="https://flama.dev/" target="_blank">Documentation</a>

Flama is a **data-science oriented framework** to rapidly build modern and robust **machine learning** (ML) APIs. The main aim of the framework is to make ridiculously simple the deployment of ML APIs. With Flama, data scientists can now quickly turn their ML models into asynchronous, auto-documented APIs with just a single line of code. All in just few seconds!

Flama comes with an intuitive CLI, and provides an easy-to-learn philosophy to speed up the building of **highly performant** GraphQL, REST, and ML APIs. Besides, it comprises an ideal solution for the development of asynchronous and **production-ready** services, offering **automatic deployment** for ML models.

### Responder

<a href="https://github.com/kennethreitz/responder" target="_blank">GitHub</a> |
<a href="https://responder.kennethreitz.org/" target="_blank">Documentation</a>

Async web service framework. Some Features: flask-style route expression,
yaml support, OpenAPI schema generation, background tasks, graphql.

### Ellar

<a href="https://github.com/python-ellar/ellar" target="_blank">GitHub</a> |
<a href="https://python-ellar.github.io/ellar/" target="_blank">Documentation</a>

Ellar is an ASGI web framework for building fast, efficient and scalable RESTAPIs and server-side applications. It offers a high level of abstraction in building server-side applications and combines elements of OOP (Object Oriented Programming), and FP (Functional Programming) - Inspired by Nestjs.

It is built on 3 core libraries **Starlette**, **Pydantic**, and **injector**.

### Apiman

An extension to integrate Swagger/OpenAPI document easily for Starlette project and provide [SwaggerUI](http://swagger.io/swagger-ui/) and [RedocUI](https://redocly.github.io/redoc/).

<a href="https://github.com/strongbugman/apiman" target="_blank">GitHub</a>

### Starlette-Babel

Provides translations, localization, and timezone support via Babel integration.

<a href="https://github.com/alex-oleshkevich/starlette_babel" target="_blank">GitHub</a>

### Sentry

<a href="https://github.com/getsentry/sentry-python" target="_blank">GitHub</a> |
<a href="https://docs.sentry.io/platforms/python/guides/starlette/" target="_blank">Documentation</a>

Sentry is a software error detection tool. It offers actionable insights for resolving performance issues and errors, allowing users to diagnose, fix, and optimize Python debugging. Additionally, it integrates seamlessly with Starlette for Python application development. Sentry's capabilities include error tracking, performance insights, contextual information, and alerts/notifications.

### Shiny

<a href="https://github.com/posit-dev/py-shiny" target="_blank">GitHub</a> |
<a href="https://shiny.posit.co/py/" target="_blank">Documentation</a>

Leveraging Starlette and asyncio, Shiny allows developers to create effortless Python web applications using the power of reactive programming. Shiny eliminates the hassle of manual state management, automatically determining the best execution path for your app at runtime while simultaneously minimizing re-rendering. This means that Shiny can support everything from the simplest dashboard to full-featured web apps.
</file>

<file path="docs/threadpool.md">
# Thread Pool

Starlette uses a thread pool in several scenarios to avoid blocking the event loop:

- When you create a synchronous endpoint using `def` instead of `async def`
- When serving files with [`FileResponse`](responses.md#fileresponse)
- When handling file uploads with [`UploadFile`](requests.md#request-files)
- When running synchronous background tasks with [`BackgroundTask`](background.md)
- And some other scenarios that may not be documented...

Starlette will run your code in a thread pool to avoid blocking the event loop.
This applies for endpoint functions and background tasks you create, but also for internal Starlette code.

To be more precise, Starlette uses `anyio.to_thread.run_sync` to run the synchronous code.

## Concurrency Limitations

The default thread pool size is only 40 _tokens_. This means that only 40 threads can run at the same time.
This limit is shared with other libraries: for example FastAPI also uses `anyio` to run sync dependencies, which also uses up thread capacity.

If you need to run more threads, you can increase the number of _tokens_:

```py
import anyio.to_thread

limiter = anyio.to_thread.current_default_thread_limiter()
limiter.total_tokens = 100
```

The above code will increase the number of _tokens_ to 100.

Increasing the number of threads may have a performance and memory impact, so be careful when doing so.
</file>

<file path="docs/websockets.md">
Starlette includes a `WebSocket` class that fulfils a similar role
to the HTTP request, but that allows sending and receiving data on a websocket.

### WebSocket

Signature: `WebSocket(scope, receive, send)`

```python
from starlette.websockets import WebSocket


async def app(scope, receive, send):
    websocket = WebSocket(scope=scope, receive=receive, send=send)
    await websocket.accept()
    await websocket.send_text('Hello, world!')
    await websocket.close()
```

WebSockets present a mapping interface, so you can use them in the same
way as a `scope`.

For instance: `websocket['path']` will return the ASGI path.

#### URL

The websocket URL is accessed as `websocket.url`.

The property is actually a subclass of `str`, and also exposes all the
components that can be parsed out of the URL.

For example: `websocket.url.path`, `websocket.url.port`, `websocket.url.scheme`.

#### Headers

Headers are exposed as an immutable, case-insensitive, multi-dict.

For example: `websocket.headers['sec-websocket-version']`

#### Query Parameters

Query parameters are exposed as an immutable multi-dict.

For example: `websocket.query_params['search']`

#### Path Parameters

Router path parameters are exposed as a dictionary interface.

For example: `websocket.path_params['username']`

### Accepting the connection

* `await websocket.accept(subprotocol=None, headers=None)`

### Sending data

* `await websocket.send_text(data)`
* `await websocket.send_bytes(data)`
* `await websocket.send_json(data)`

JSON messages default to being sent over text data frames, from version 0.10.0 onwards.
Use `websocket.send_json(data, mode="binary")` to send JSON over binary data frames.

### Receiving data

* `await websocket.receive_text()`
* `await websocket.receive_bytes()`
* `await websocket.receive_json()`

May raise `starlette.websockets.WebSocketDisconnect()`.

JSON messages default to being received over text data frames, from version 0.10.0 onwards.
Use `websocket.receive_json(data, mode="binary")` to receive JSON over binary data frames.

### Iterating data

* `websocket.iter_text()`
* `websocket.iter_bytes()`
* `websocket.iter_json()`

Similar to `receive_text`, `receive_bytes`, and `receive_json` but returns an
async iterator.

```python hl_lines="7-8"
from starlette.websockets import WebSocket


async def app(scope, receive, send):
    websocket = WebSocket(scope=scope, receive=receive, send=send)
    await websocket.accept()
    async for message in websocket.iter_text():
        await websocket.send_text(f"Message text was: {message}")
    await websocket.close()
```

When `starlette.websockets.WebSocketDisconnect` is raised, the iterator will exit.

### Closing the connection

* `await websocket.close(code=1000, reason=None)`

### Sending and receiving messages

If you need to send or receive raw ASGI messages then you should use
`websocket.send()` and `websocket.receive()` rather than using the raw `send` and
`receive` callables. This will ensure that the websocket's state is kept
correctly updated.

* `await websocket.send(message)`
* `await websocket.receive()`

### Send Denial Response

If you call `websocket.close()` before calling `websocket.accept()` then
the server will automatically send a HTTP 403 error to the client.

If you want to send a different error response, you can use the
`websocket.send_denial_response()` method. This will send the response
and then close the connection.

* `await websocket.send_denial_response(response)`

This requires the ASGI server to support the WebSocket Denial Response
extension. If it is not supported a `RuntimeError` will be raised.

In the context of `Starlette`, you can also use the `HTTPException` to achieve the same result.

```python
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.routing import WebSocketRoute
from starlette.websockets import WebSocket


def is_authorized(subprotocols: list[str]):
    if len(subprotocols) != 2:
        return False
    if subprotocols[0] != "Authorization":
        return False
    # Here we are hard coding the token, in a real application you would validate the token
    # against a database or an external service.
    if subprotocols[1] != "token":
        return False
    return True


async def websocket_endpoint(websocket: WebSocket):
    subprotocols = websocket.scope["subprotocols"]
    if not is_authorized(subprotocols):
        raise HTTPException(status_code=401, detail="Unauthorized")
    await websocket.accept("Authorization")
    await websocket.send_text("Hello, world!")
    await websocket.close()


app = Starlette(debug=True, routes=[WebSocketRoute("/ws", websocket_endpoint)])
```

<!-- Test the above with `npx wscat -c ws://localhost:8000/ws -s Authorization -s token` -->
</file>

<file path="scripts/check">
#!/bin/sh -e

export SOURCE_FILES="starlette tests benchmarks"

set -x

./scripts/sync-version
uv run ruff format --check --diff $SOURCE_FILES
uv run mypy $SOURCE_FILES
uv run ruff check $SOURCE_FILES
</file>

<file path="scripts/docs">
#!/bin/sh -e

set -x

uv run zensical serve
</file>

<file path="scripts/install">
#!/bin/sh -e

set -x

uv sync --frozen
</file>

<file path="scripts/lint">
#!/bin/sh -e

export SOURCE_FILES="starlette tests"

set -x

uv run ruff format $SOURCE_FILES
uv run ruff check --fix $SOURCE_FILES
</file>

<file path="scripts/README.md">
# Development Scripts

* `scripts/install` - Install dependencies in a virtual environment.
* `scripts/test` - Run the test suite.
* `scripts/lint` - Run the automated code linting/formatting tools.
* `scripts/check` - Run the code linting, checking that it passes.
* `scripts/coverage` - Check that code coverage is complete.
* `scripts/build` - Build source and wheel packages.

Styled after GitHub's ["Scripts to Rule Them All"](https://github.com/github/scripts-to-rule-them-all).
</file>

<file path="scripts/sync-version">
#!/bin/sh -e

SEMVER_REGEX="([0-9]+)\.([0-9]+)\.([0-9]+)(-([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?(\+[0-9A-Za-z-]+)?"
CHANGELOG_VERSION=$(grep -o -E $SEMVER_REGEX docs/release-notes.md | head -1)
VERSION=$(grep -o -E $SEMVER_REGEX starlette/__init__.py | head -1)
if [ "$CHANGELOG_VERSION" != "$VERSION" ]; then
    echo "Version in changelog does not match version in starlette/__init__.py!"
    exit 1
fi
</file>

<file path="AGENTS.md">
## AI Policy

Read and follow [AI_POLICY.md](AI_POLICY.md) before contributing.

## Writing Documentation

1. After each heading, always include text explaining the section before any code snippets.
</file>

<file path="AI_POLICY.md">
# AI Policy

You may use AI tools when contributing to Starlette. You remain responsible for every contribution you submit.

Before you open a pull request, search the open and closed pull requests, issues, and discussions. Do not open a pull
request when the same change has already been proposed or is already in progress.

Duplicate pull requests waste maintainer time and create unnecessary review work. Contributors who submit duplicate
pull requests will be banned from the project.
</file>

<file path="LICENSE.md">
Copyright © 2018, [Encode OSS Ltd](https://www.encode.io/).
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</file>

<file path="mkdocs.yml">
site_name: Starlette
site_description: The little ASGI library that shines.
site_url: https://starlette.dev
repo_name: Kludex/starlette
repo_url: https://github.com/Kludex/starlette
edit_uri: edit/main/docs/
strict: true
theme:
  name: "material"
  custom_dir: docs/overrides
  palette:
    - scheme: "default"
      media: "(prefers-color-scheme: light)"
      toggle:
        icon: "material/lightbulb"
        name: "Switch to dark mode"
    - scheme: "slate"
      media: "(prefers-color-scheme: dark)"
      primary: "blue"
      toggle:
        icon: "material/lightbulb-outline"
        name: "Switch to light mode"
  icon:
    repo: fontawesome/brands/github
  features:
    - content.code.copy
    - toc.follow
nav:
  - Introduction: "index.md"
  - Features:
      - Applications: "applications.md"
      - Requests: "requests.md"
      - Responses: "responses.md"
      - WebSockets: "websockets.md"
      - Routing: "routing.md"
      - Endpoints: "endpoints.md"
      - Middleware: "middleware.md"
      - Static Files: "staticfiles.md"
      - Templates: "templates.md"
      - Database: "database.md"
      - GraphQL: "graphql.md"
      - Authentication: "authentication.md"
      - API Schemas: "schemas.md"
      - Lifespan: "lifespan.md"
      - Background Tasks: "background.md"
      - Server Push: "server-push.md"
      - Early Hints: "early-hints.md"
      - Exceptions: "exceptions.md"
      - Configuration: "config.md"
      - Thread Pool: "threadpool.md"
      - Test Client: "testclient.md"
  - Release Notes: "release-notes.md"
  - Community:
      - Third Party Packages: "third-party-packages.md"
      - Contributing: "contributing.md"
extra_css:
  - css/custom.css
extra:
  analytics:
    provider: google
    property: G-Z37GTYBR6M
  social:
    - icon: fontawesome/brands/github-alt
      link: https://github.com/Kludex/starlette
    - icon: fontawesome/brands/discord
      link: https://discord.com/invite/RxKUF5JuHs
    - icon: fontawesome/brands/twitter
      link: https://x.com/marcelotryle
    - icon: fontawesome/brands/linkedin
      link: https://www.linkedin.com/in/marcelotryle
    - icon: fontawesome/solid/globe
      link: https://fastapiexpert.com
markdown_extensions:
  - attr_list
  - admonition
  - pymdownx.highlight
  - pymdownx.superfences
  - pymdownx.details
  - pymdownx.tabbed:
      alternate_style: true
  - pymdownx.emoji:
      emoji_index: !!python/name:material.extensions.emoji.twemoji
      emoji_generator: !!python/name:material.extensions.emoji.to_svg
  - pymdownx.tasklist:
      custom_checkbox: true
watch:
  - starlette
plugins:
  - search
  - mkdocstrings:
      handlers:
        python:
          options:
            docstring_section_style: list
            show_root_toc_entry: false
            members_order: source
            separate_signature: true
            filters: ["!^_"]
            docstring_options:
              ignore_init_summary: true
            merge_init_into_class: true
            parameter_headings: true
            show_signature_annotations: true
            show_source: false
            signature_crossrefs: true
          inventories:
            - url: https://docs.python.org/3/objects.inv
</file>

<file path="README.md">
<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Kludex/starlette/main/docs/img/starlette_dark.svg" width="420px">
    <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/Kludex/starlette/main/docs/img/starlette.svg" width="420px">
    <img alt="starlette-logo" src="https://raw.githubusercontent.com/Kludex/starlette/main/docs/img/starlette.svg">
  </picture>
</p>

<p align="center">
    <em>✨ The little ASGI framework that shines. ✨</em>
</p>

---

[![Build Status](https://github.com/Kludex/starlette/workflows/Test%20Suite/badge.svg)](https://github.com/Kludex/starlette/actions)
[![Package version](https://badge.fury.io/py/starlette.svg)](https://pypi.python.org/pypi/starlette)
[![Supported Python Version](https://img.shields.io/pypi/pyversions/starlette.svg?color=%2334D058)](https://pypi.org/project/starlette)
[![Discord](https://img.shields.io/discord/1051468649518616576?logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/RxKUF5JuHs)

---

**Documentation**: <a href="https://starlette.dev/" target="_blank">https://starlette.dev</a>

**Source Code**: <a href="https://github.com/Kludex/starlette" target="_blank">https://github.com/Kludex/starlette</a>

---

# Starlette

Starlette is a lightweight [ASGI][asgi] framework/toolkit,
which is ideal for building async web services in Python.

It is production-ready, and gives you the following:

* A lightweight, low-complexity HTTP web framework.
* WebSocket support.
* In-process background tasks.
* Startup and shutdown events.
* Test client built on `httpx2`.
* CORS, GZip, Static Files, Streaming responses.
* Session and Cookie support.
* 100% test coverage.
* 100% type annotated codebase.
* Few hard dependencies.
* Compatible with `asyncio` and `trio` backends.
* Great overall performance [against independent benchmarks][techempower].

## Installation

```shell
$ pip install starlette
```

You'll also want to install an ASGI server, such as [uvicorn](https://uvicorn.dev) or any of the [other ASGI server implementations](https://asgi.readthedocs.io/en/latest/implementations.html#servers).

```shell
$ pip install uvicorn
```

## Example

```python title="main.py"
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route


async def homepage(request):
    return JSONResponse({'hello': 'world'})

routes = [
    Route("/", endpoint=homepage)
]

app = Starlette(debug=True, routes=routes)
```

Then run the application using Uvicorn:

```shell
$ uvicorn main:app
```

## Dependencies

Starlette only requires `anyio`, and the following are optional:

* [`httpx2`][httpx2] - Required if you want to use the `TestClient`.
* [`jinja2`][jinja2] - Required if you want to use `Jinja2Templates`.
* [`opentelemetry-api`][opentelemetry-api] - Required for `OpenTelemetryMiddleware`.
* [`python-multipart`][python-multipart] - Required if you want to support form parsing, with `request.form()`.
* [`itsdangerous`][itsdangerous] - Required for `SessionMiddleware` support.
* [`pyyaml`][pyyaml] - Required for `SchemaGenerator` support.

You can install all of these with `pip install starlette[full]`.

## Framework or Toolkit

Starlette is designed to be used either as a complete framework, or as
an ASGI toolkit. You can use any of its components independently.

```python
from starlette.responses import PlainTextResponse


async def app(scope, receive, send):
    assert scope['type'] == 'http'
    response = PlainTextResponse('Hello, world!')
    await response(scope, receive, send)
```

Run the `app` application in `example.py`:

```shell
$ uvicorn example:app
INFO: Started server process [11509]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```

Run uvicorn with `--reload` to enable auto-reloading on code changes.

## Modularity

The modularity that Starlette is designed on promotes building reusable
components that can be shared between any ASGI framework. This should enable
an ecosystem of shared middleware and mountable applications.

The clean API separation also means it's easier to understand each component
in isolation.

---

<p align="center"><i>Starlette is <a href="https://github.com/Kludex/starlette/blob/main/LICENSE.md">BSD licensed</a> code.<br/>Designed & crafted with care.</i></br>&mdash; ⭐️ &mdash;</p>

[asgi]: https://asgi.readthedocs.io/en/latest/
[httpx2]: https://pypi.org/project/httpx2/
[jinja2]: https://jinja.palletsprojects.com/
[opentelemetry-api]: https://opentelemetry.io/docs/languages/python/api/
[python-multipart]: https://multipart.fastapiexpert.com/
[itsdangerous]: https://itsdangerous.palletsprojects.com/
[sqlalchemy]: https://www.sqlalchemy.org
[pyyaml]: https://pyyaml.org/wiki/PyYAMLDocumentation
[techempower]: https://github.com/TechEmpower/FrameworkBenchmarks
</file>

</files>
