# Add a REST API to a Yii2 App

Yes. An agent adds a JSON resource API to a Yii2 basic app: migration, ActiveRecord model, ActiveController, URL rules, bearer auth and Codeception tests, in one PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-rest-api/yii/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

Yii2 ships a REST layer, so the job is wiring it into an app that was generated without one. The agent reads what the template gives it. In an app laid out like yiisoft/yii2-app-basic, `composer.json` requires `yiisoft/yii2` `~2.0.54` on PHP 8.2 or later. `config/web.php` has the `urlManager` component commented out, with `enablePrettyUrl`, `showScriptName` and an empty `rules` array inside the comment. The only controller is `SiteController`. There is no ActiveRecord class and no `migrations` directory, and `config/db.php` points at `mysql:host=localhost;dbname=yii2basic` as `root` with an empty password. One piece is already in place: `models/User.php` implements `findIdentityByAccessToken` over its hardcoded users, whose tokens are `100-token` and `101-token`.

It builds one resource end to end with the framework's own classes. `php yii migrate/create create_post_table` with a `--fields` option writes a migration under a new `migrations/` directory, and `models/Post.php` extends `yii\db\ActiveRecord` with `rules()` requiring a title and a `fields()` method that names exactly what the API exposes. `controllers/api/PostController.php` extends `yii\rest\ActiveController` with `$modelClass` set, which provides index, view, create, update, delete and options actions, JSON or XML chosen from the `Accept` header, and pagination reported in `X-Pagination-*` headers. In `config/web.php` the agent uncomments `urlManager`, adds a `yii\rest\UrlRule` for `api/post` so the routes read `/api/posts` and `/api/posts/<id>`, and registers `yii\web\JsonParser` for `application/json` under the `request` component so JSON bodies populate the model. The test application has its own file, `config/test.php`, whose `urlManager` sets only `showScriptName`, so the rule and the parser go into one small file that both configs require.

Authentication reuses what the template has. The controller's `behaviors()` adds `yii\filters\auth\HttpBearerAuth`, which calls `findIdentityByAccessToken`, so `Authorization: Bearer 100-token` authenticates as `admin` with no new code in the identity class, and the controller turns off session use for its requests so the API stays stateless beside the cookie login the site pages keep. The agent watches one trap in this repository. `composer install` runs `yii\composer\Installer::postInstall`, whose `generateCookieValidationKey` step writes a random secret into `config/web.php`. The agent stages its own hunks of that file and leaves the generated key out of the commit.

Tests need a database, and the template's test config, `config/test_db.php`, expects a MySQL database named `yii2basic_test` on localhost. The agent installs MariaDB in its sandbox with `apt-get`, creates that database, and applies the migration through `tests/Support/bin/yii`, the console entry that merges `config/console.php` with the test connection. It adds `codeception/module-rest` to `require-dev`, enables the `REST` module with `depends: Yii2` in a new `tests/Api.suite.yml`, and runs `vendor/bin/codecept build`, as the comments in the suite files instruct after a module change. The Cest file covers a list with and without a token, a create that returns 201 with a `Location` header, a validation failure that returns 422 with field errors, and an unknown id that returns a JSON 404. Then it runs `composer tests`, `composer static` for PHPStan at level 5 and `composer cs` for the Yii2 coding standard, and says in the pull request that `.github/workflows/build.yml` calls a shared workflow whose database setup it could not see from this repository.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a JSON REST API for a posts resource to this Yii2 basic application. Read composer.json, config/web.php, config/console.php, config/db.php, config/test.php, config/test_db.php, models/User.php, controllers/SiteController.php, codeception.yml, the three suite files under tests, tests/Support/bin/yii, phpstan.neon, phpcs.xml.dist and the workflows under .github first. Install PHP 8.2 or later with the pdo_mysql, dom, gd and intl extensions, Composer and MariaDB if the sandbox lacks them, run composer install, and create the yii2basic_test database. Do not commit the cookie validation key that composer install writes into config/web.php. Create a migration for a post table with id, title, body, created_at and updated_at using yii migrate/create, an ActiveRecord model with validation rules and a fields() method, and controllers/api/PostController.php extending yii\\rest\\ActiveController. Enable urlManager with pretty URLs and a yii\\rest\\UrlRule for the controller, register the JSON request parser, share both with config/test.php through one required file, and protect the controller with HttpBearerAuth using the existing findIdentityByAccessToken, leaving OPTIONS requests open. Keep the site pages and their session login working. Add codeception/module-rest, an Api suite that depends on the Yii2 module, run codecept build, and write Cest tests for list, view, create, update, delete, a missing token, a validation error and an unknown id. Apply the migration to the test database with tests/Support/bin/yii. Run composer tests, composer static and composer cs and fix what they report in the files you added. Open a pull request that lists the routes, quotes the three command outputs and names anything CI will need that you could not verify.",
  "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

The pull request adds `migrations/` with one migration, `models/Post.php`, `controllers/api/PostController.php`, `tests/Api.suite.yml` and a Cest class, and changes `config/web.php` and `composer.json`. Its description lists the routes the URL rule creates, shows one request and response per verb, including the 401 without a token and the 422 body with its `field` and `message` pairs, and quotes the output of `composer tests`, `composer static` and `composer cs`.

A reviewer reads `config/web.php` first, since it is the one shared file. Pretty URLs change every link the site generates, so they check that the acceptance tests for the home, about, contact and login pages still pass in the quoted output, that the rule file is required by both `config/web.php` and `config/test.php`, and that `cookieValidationKey` is still empty in the diff. They check `fields()` in the model against what a client should see, and they read the note about authentication: the tokens come from the hardcoded array in `models/User.php`, which is fine for a first endpoint and not for production.

The description ends with what the team has to decide. CI needs a database for the new suite, and the shared workflow that `build.yml` calls is defined in another repository, so the agent states that it ran the suite against MariaDB in its sandbox and did not verify the hosted run.

## Run it on every new resource in the backlog

The first resource sets the pattern and the next ones repeat it. From a script on your own server, send this body to `POST /o/{org}/sessions` once per resource, with the resource's name and columns appended to the prompt, the repository in `resources`, and a `request_id` that is a UUID v5 of the repository and resource name so a retry returns the run already started. Each run opens one pull request with its migration, model, controller, rule and tests.

To keep later endpoints consistent, add an automation on the Project with a `github` trigger on `pull_request.opened`, marked read only, whose prompt says to check any new class under `controllers/api/` in the pull request named in the event for an authenticator, a URL rule and a Cest file, and to comment when one is missing.

## Why run it on Rush?

The API is not done when the classes exist. It is done when a request with a bearer token gets JSON back from a migrated database and the template's three static and test commands pass. A Rush run has a sandbox of its own where the agent installs PHP and MariaDB, applies the migration and runs Codeception against a real connection, and each command with its output stays in the run's transcript, so the responses quoted in the pull request can be traced to the run that produced them.

It also keeps the setup off a laptop. Nobody has to create a throwaway MySQL database or let Composer rewrite their local `config/web.php` to try this, and when a reviewer wants a change, a follow-up message wakes the same sandbox with the database and dependencies still in place.

## Frequently asked questions

### Does enabling pretty URLs break the existing site pages?

It changes how their URLs look, from `index.php?r=site/about` to `/site/about`, and the views build links through route arrays such as `['/site/about']`, so they follow the new format without edits. A web server in front of the app needs a rewrite to `index.php`; the template's `web/.htaccess` is where that belongs for Apache. The agent also requests a site page from the built-in server with the web config and reports the status it got.

### Is CSRF validation a problem for API clients?

No. Controllers that extend `yii\rest\Controller` turn CSRF validation off for their own requests, because a token-authenticated client has no form to carry the token in. The site's form pages keep CSRF protection as before.

### Can it use SQLite for the tests instead of MySQL?

Yes, if the prompt asks. `config/test_db.php` overrides only the DSN, so pointing it at a SQLite file under `runtime/` removes the need for a server in the test run. The agent stays with MySQL by default because that is what `config/db.php` names, and a migration that passes on SQLite can still fail on MySQL.

## More Yii jobs

- [Move Yii2 Users From a Hardcoded Array to a Database Table](https://getrush.ai/run/move-users-to-database/yii/)
- [Write Codeception Tests for a Yii2 App](https://getrush.ai/run/write-codeception-tests/yii/)
- [Add Role-Based Access Control (RBAC) to a Yii2 App](https://getrush.ai/run/add-rbac/yii/)

## The same job on other stacks

- [Add a JSON REST API to a CakePHP App](https://getrush.ai/run/add-rest-api/cakephp/)
- [Add a JSON REST API Over D1 to a Cloudflare Worker](https://getrush.ai/run/add-rest-api/cloudflare-workers/)
- [Add a REST API to a CodeIgniter 4 App](https://getrush.ai/run/add-rest-api/codeigniter/)

## 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/)
