Migrate data outside of routes¶
migrate_request() and migrate_response() migrate requests and responses outside of routes, e.g. for webhooks, messages in queues, workers, or an API that isn't built with FastAPI. They run the same migrations by schema as routes, so the version changes that you've written for your routes give the same data either way. Migrations outside of routes describes them. This guide is for the code that migrates data outside of routes in other ways.
From migrate_response_body()¶
migrate_response_body() keeps working as before, so you can move at your own pace. Where you have
from cadwyn import migrate_response_body
from versions import User, versions
user = User(full_name="John")
body = migrate_response_body(
versions, User, latest_body=user.model_dump(), version="2000-01-01"
)
use
from cadwyn import migrate_response
from versions import User, versions
user = User(full_name="John")
body = migrate_response(versions, User, body=user, version="2000-01-01").body
Here's what changes:
- The body argument is
bodyinstead oflatest_body, and you get the body from thebodyof the result. - You can pass objects of your HEAD models, which can fail in
migrate_response_body(). They become data with all their fields by their aliases before the migrations run, as in routes. Migrations always get data, so the ones that turn the object into data themselves can stop doing it. If you pass a dict that you've dumped in another way, e.g. without aliases or withmode="json", migrations keep getting what they got before. - The migrated body is validated as FastAPI validates responses: by the attributes of objects too, and without your overrides of
model_validate(). - The status code and the headers are part of the result, so the headers and the cookies that migrations set are no longer thrown away. Pass
status_codeandheadersif your migrations need them. - If a migration turns the response into an error, you get the error body and its status code, while
migrate_response_body()fails to validate the error body as your model.
From your own migration loop¶
If you call the migrations of your version changes yourself, e.g. by walking VersionBundle.versions and calling the instructions in alter_request_by_schema_instructions and alter_response_by_schema_instructions, you can use migrate_request() and migrate_response() instead. For example, to bring a message of an older version up to HEAD:
from cadwyn import migrate_request
from versions import User, versions
message = {"name": "John"}
user = migrate_request(versions, User, body=message, version="2000-01-01").body
They also do what routes do around the migrations, which a loop of your own usually doesn't:
migrate_request()validates the body of the older version first, and migrates only the fields that it has set, by their aliases.migrate_response()validates the result of the migrations with the model of the older version.- They give the HEAD the members of its own enums instead of the members of the copies of enums that older versions have.
- They restore the validation aliases that the migrated body needs, and, in requests, the
Json[...]values. - Once a migration turns a response into an error, they only run the migrations that set
migrate_http_errors=True. - They take dates and pick the closest older version, as
migrate_response_body()does. - They migrate between any two versions: pass
to_versiontomigrate_request()orfrom_versiontomigrate_response()if your loop doesn't start or end at HEAD.
Validating requests first means that the older data has to fit that version's model. If your version changes have no schema instructions for a model, every version has HEAD's fields and validators for it, so an older request can't have what HEAD rejects, and a migration can't rename or remove it. Describe how the older version differed with schema instructions, e.g. schema(User).field("full_name").had(name="name") or schema(User).validator(check_name).didnt_exist. Request migrations also get the validated data, e.g. with coerced values, rather than exactly what you passed. Response migrations get body as you passed it, with its models turned into data.
If a request doesn't fit its version, or a migrated response doesn't fit the version you migrate it to, you get Pydantic's ValidationError. If a migrated request doesn't fit the model that it's migrated to, HEAD's or to_version's, migrate_request() raises CadwynHeadRequestValidationError, which means that a migration is wrong. It's a CadwynError, not a ValueError like ValidationError, so catch it separately if your loop catches ValueError.
If you send the result as JSON, e.g. in a message, dump it as routes do: migrate_response(...).body.model_dump(mode="json", by_alias=True).
Your loop keeps working too: the attributes that it uses are part of the supported API.
Without FastAPI¶
To use versions, version changes, data migrations, and versioned models without FastAPI and Starlette, install cadwyn-core instead of cadwyn. It only needs Pydantic:
uv add cadwyn-core
Import everything from cadwyn_core instead of cadwyn, and the errors from cadwyn_core.exceptions:
from pydantic import BaseModel
from cadwyn_core import (
RequestInfo,
Version,
VersionBundle,
VersionChange,
convert_request_to_next_version_for,
migrate_request,
schema,
)
class User(BaseModel):
full_name: str
class RenameNameToFullName(VersionChange):
description = "'name' is now called 'full_name'"
instructions_to_migrate_to_previous_version = (
schema(User).field("full_name").had(name="name"),
)
@convert_request_to_next_version_for(User)
def rename_name_to_full_name(request: RequestInfo):
request.body["full_name"] = request.body.pop("name")
versions = VersionBundle(
Version("2001-01-01", RenameNameToFullName),
Version("2000-01-01"),
)
user = migrate_request(
versions, User, body={"name": "John"}, version="2000-01-01"
).body
cadwyn installs cadwyn-core in the same version and exports the same objects, with SchemaGenerator in cadwyn.schema_generation and the errors in cadwyn.exceptions, so version changes that import from cadwyn_core work in a FastAPI app too. migrate_response_body() is only in cadwyn: use migrate_response() instead.
cadwyn-core only works with the cadwyn of the same version: import cadwyn_core fails with an ImportError if another version of cadwyn is installed, including cadwyn 9.0 and older, which don't use cadwyn-core. So if one package of your project requires cadwyn-core and another requires cadwyn, e.g. a worker and an API server, require at least the same version of cadwyn there as of cadwyn-core, e.g. cadwyn>=9.1 next to cadwyn-core>=9.1, so that the resolver picks a cadwyn that installs the same cadwyn-core. A release candidate needs its own version in both, e.g. >=9.1.0rc1, because >=9.1 excludes it.
Headers need Starlette. Without it, the results have headers=None, and migrate_request() and migrate_response() raise CadwynError if you pass headers or a migration uses them.