# Fix Pydantic V1 Style @validator Validators Are Deprecated in a FastAPI App

Yes. An agent reproduces the PydanticDeprecatedSince20 warning, rewrites each @validator as a field_validator classmethod, re-checks the refusal and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/fix-pydantic-v1-style-validator-deprecated-warning/pydantic/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent clones the repository into its own cloud sandbox and reads the models first. In a small FastAPI service like hektorprofe/curso-gestor-clientes-python, `api.py` imports `BaseModel, constr, validator` from pydantic, defines `ModeloCliente` with three `constr(min_length=..., max_length=...)` fields, and `ModeloCrearCliente` adds `@validator("dni")` at line 18 that calls `helpers.dni_valido(dni, db.Clientes.lista)` and raises `ValueError("Cliente ya existente o DNI incorrecto")`. The routes read and write a CSV through `database.py`, `requirements.txt` pins `pytest==7.1.2`, `fastapi==0.79.0` and `uvicorn==0.18.2` with pydantic unpinned, `config.py` switches the CSV to `tests/clientes_test.csv` under pytest, and `tests/test_database.py` holds six unittest cases for the store.

Then it reproduces both states. With the pinned FastAPI, pip resolves a pydantic 1.10 release and `python -W default -c "import api"` is silent. After `pip install -U fastapi`, pydantic becomes a 2.x release and the same import prints `api.py:18: PydanticDeprecatedSince20: Pydantic V1 style @validator validators are deprecated. You should migrate to Pydantic V2 style @field_validator validators, see the migration guide for more details. Deprecated in Pydantic V2.0 to be removed in V3.0.` The six tests pass either way, because they never import `api.py`, which is exactly why the warning would reach production unseen.

The fix is three lines: import `field_validator` instead of `validator`, decorate with `@field_validator("dni")`, and add `@classmethod` under it, since V2 validators are class methods by contract. `constr` needs no change here. The agent then imports the module under `-W error::DeprecationWarning` to prove the warning is gone, and drives the app with FastAPI's `TestClient`: `GET /clientes/` answers 200 with the list, the first `POST /clientes/crear/` with a new `dni` answers 200, and the same body again answers 422 whose detail reads `Value error, Cliente ya existente o DNI incorrecto`, so the duplicate check still refuses.

It notes one side effect for the pull request without changing it: a successful `POST` writes `clientes.csv` at the repository root, because `database.py` loads the CSV at import and the test switch in `config.py` only applies under pytest. The agent restores the file after its check so the diff holds the model change only.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "This FastAPI app prints \"PydanticDeprecatedSince20: Pydantic V1 style @validator validators are deprecated\" after a dependency upgrade. Read requirements.txt and every file that imports pydantic first, and quote each warning with its file and line by importing the app under python -W default. Rewrite every @validator as @field_validator with @classmethod, keeping the field names, the mode and the error messages exactly, and convert any root_validator the same way. Import the app again under -W error::DeprecationWarning to show the warnings are gone, exercise each changed model through the app with FastAPI's TestClient so the validation still rejects what it rejected before, run the test suite, and open a pull request that quotes the warning before and the passing checks after. Do not change the pinned versions unless the warning cannot be reproduced without it, and say so if you do.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request touching `api.py` and, where the warning only appears on a newer FastAPI, `requirements.txt` with the version that reproduces it: the import changed, one decorator renamed, one `@classmethod` added. The description quotes the `PydanticDeprecatedSince20` line with its file and line, the clean import under `-W error`, the three `TestClient` responses with their status codes and the duplicate-dni detail, and the six passing tests.

A reviewer checks that the validator still refuses the same inputs with the same message, that `@classmethod` sits below `@field_validator` and not above it, and that no other model lost a validator in the rename. The run's record holds every command, so the status codes in the description can be opened as the real calls.

## Run it on every deprecation warning in a CI log

Add an automation to the Project with this prompt and a `webhook` trigger. In the CI job that runs the test suite with `-W default` or `PYTHONWARNINGS=default`, add a step that greps the log for `PydanticDeprecatedSince20` and, on a match, sends the lines to the trigger's URL with `Authorization: Bearer` and the secret Rush showed when the trigger was made. One run starts per such job and opens one pull request on its own branch; a run whose rewrite breaks the tests ends `needs_review` with the output attached.

From your own code, send this body to `POST /o/{org}/sessions` with an API key and a `request_id` that is a UUID v5 of the CI run id, so a retried delivery returns the run already started rather than opening a second pull request.

## Why run it on Rush?

This warning is easy to miss and easy to get wrong. It only prints once the installed pydantic is a 2.x release, which in this repository happens on an unpinned transitive upgrade rather than on any line someone edited, and the test suite is silent because it never imports the API module. The agent reproduces it in a sandbox at the exact versions pip resolves today, rewrites the validator, and proves with real requests that the refusal still fires, with every command kept in the run's record.

It also stops where a rename should stop. `constr`, the routes and the CSV store are untouched, the write side effect is reported rather than silently restored, and the pinned versions change only if that is what makes the warning appear. What comes back is a small pull request with the before and after attached, ready to merge before pydantic V3 turns the warning into an error.

## Frequently asked questions

### Why does field_validator need @classmethod?

Pydantic V2 validators are class methods: the first argument is the model class, not an instance. V1's `@validator` applied `classmethod` for you; `@field_validator` does not, so the decorator order is `@field_validator(...)` on top and `@classmethod` beneath it. The agent writes it that way in every rewrite.

### Does the validator still see the other fields?

A V1 validator could read earlier fields from a `values` dict. In V2 the same information comes from a `ValidationInfo` parameter, `info.data`. This repository's validator only uses the `dni` value and a module-level list, so nothing changes; where a validator reads `values`, the agent switches it to `info.data` and says so.

### What about root_validator and orm_mode?

`@root_validator` becomes `@model_validator(mode=...)`, and `class Config: orm_mode = True` becomes `model_config = ConfigDict(from_attributes=True)`; each prints its own deprecation line. The prompt covers validators; the agent reports any other `PydanticDeprecatedSince20` line it sees with its file so you can start the next run.

### Why not just pin pydantic below 2?

Because FastAPI releases that current security and feature work land on require pydantic 2, so the pin is a dead end. Rewriting the validator takes three lines and keeps the upgrade path open; the agent only touches the pins when the warning cannot be shown without them.

## More Pydantic jobs

- [Migrate a Python Library from Pydantic v1 to v2](https://getrush.ai/run/migrate-to-pydantic-v2/pydantic/)
- [Fix "ForwardRef._evaluate() missing 1 required keyword-only argument: 'recursive_guard'" in Pydantic v1](https://getrush.ai/run/fix-forwardref-evaluate-recursive-guard-type-error/pydantic/)
- [Fix "ValueError: 'not' is not a valid parameter name" in a FastAPI App on Python 3.11 or Later](https://getrush.ai/run/fix-not-is-not-a-valid-parameter-name/pydantic/)

## More jobs like this: Fix a bug from an alert

- [Fix "AttributeError: cython_sources" When Installing PyYAML 5.4.1](https://getrush.ai/run/fix-pyyaml-cython-sources-attribute-error/pyyaml/)
- [Fix "LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy"](https://getrush.ai/run/fix-query-get-legacy-api-warning/flask-sqlalchemy/)
- [Fix Quoted References Are Deprecated Warnings in a Terraform AWS Module](https://getrush.ai/run/fix-quoted-references-are-deprecated-warning/terraform/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
