# Add a REST API to a CodeIgniter 4 App

Yes. An agent adds a JSON resource API to your CodeIgniter 4 app with a migration, a model, a ResourceController, resource routes and feature tests, and opens a PR.

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

## What the agent does

The agent starts from what the starter actually contains, because the framework already ships the REST pieces and the job is wiring them. In an app laid out like codeigniter4/appstarter, `composer.json` requires `php ^8.2` and `codeigniter4/framework ^4.7`, with `phpunit ^10.5.16`, `fakerphp/faker` and `mikey179/vfsstream` for development. `app/Config/Routes.php` holds one line, `$routes->get('/', 'Home::index')`, and `app/Config/Routing.php` sets `defaultNamespace` to `App\Controllers` with `translateURIDashes` off. `app/Models`, `app/Database/Migrations` and `app/Database/Seeds` are empty apart from `.gitkeep` files. `app/Config/Format.php` already lists `application/json`, `application/xml` and `text/xml` as `$supportedResponseFormats` with `JSONFormatter` and `XMLFormatter` behind them, and `app/Config/Filters.php` declares a `cors` alias backed by `CodeIgniter\Filters\Cors` but applies nothing globally except `forcehttps`, `pagecache`, `performance` and `toolbar`. `app/Config/Database.php` points `default` at MySQLi with an empty database name, while its `tests` group is SQLite3 on `:memory:` with a `db_` prefix, and the constructor switches to that group whenever `ENVIRONMENT` is `testing`.

The API is one resource built with the framework's own generators, so every file lands where the user guide says it should. `php spark make:migration CreateTasks` produces a timestamped class under `app/Database/Migrations/` whose `up()` uses `$this->forge->addField()` for `id`, `title`, `done`, `created_at` and `updated_at` and creates the `tasks` table; `php spark make:entity Task` and `php spark make:model TaskModel --return entity` produce `app/Entities/Task.php` and `app/Models/TaskModel.php` with `$table`, `$allowedFields`, `$useTimestamps` and `$validationRules` that require a `title` of at most 255 characters; and `php spark make:controller Api/Tasks --restful` produces a class extending `CodeIgniter\RESTful\ResourceController` with `$modelName = 'App\Models\TaskModel'` and `$format = 'json'`, so a response is always JSON rather than negotiated from the `Accept` header. The controller fills in `index()`, `show($id)`, `create()`, `update($id)` and `delete($id)` with the `API\ResponseTrait` helpers the base class already mixes in: `respond()` for a list or a single row, `respondCreated()` for 201, `respondDeleted()` after a delete, `failNotFound()` for an unknown id and `failValidationErrors($this->model->errors())` when the model's rules reject a body. Bodies arrive as JSON, read with `$this->request->getJSON(true)`, and the error body keeps the trait's shape of `status`, `code` and `messages`.

Routing is one line in `app/Config/Routes.php` inside an `api` group: `$routes->resource('tasks', ['controller' => 'Api\Tasks', 'except' => 'new,edit', 'placeholder' => '(:num)'])`, which generates `GET /api/tasks`, `GET /api/tasks/(:num)`, `POST /api/tasks`, `PUT` and `PATCH /api/tasks/(:num)` and `DELETE /api/tasks/(:num)` while leaving out the HTML form routes `new` and `edit`, and refuses a non-numeric id before the controller runs. The group carries `['filter' => 'cors']`, so the `Cors` filter the starter already aliases applies only to `/api/*`, with `app/Config/Cors.php` filled in with `allowedOrigins`, `allowedMethods` and `allowedHeaders` instead of its empty arrays. The agent leaves `csrf` out of the API routes on purpose, since the starter does not enable it globally and a token-less JSON client cannot send one, and says in the pull request that authentication is the next step rather than part of this one.

Tests follow the starter's `tests/` layout and its `tests` database group. A `tests/feature/TasksApiTest.php` class uses `FeatureTestTrait` with `DatabaseTestTrait`, `$migrate = true` and `$namespace = 'App'` so the new migration runs against SQLite in memory with the `db_` prefix the config insists on. It posts a task with `withBodyFormat('json')`, which sets the `Content-Type` and encodes the array, and asserts 201 and a JSON fragment with the title; lists and asserts 200; posts an empty body and asserts 400 with the validation message; and requests `/api/tasks/999` to assert 404. The agent runs `vendor/bin/phpunit` the way `.github/workflows/phpunit.yml` does and notes that this workflow only fires on pull requests to a `develop` branch, so a repository that merges to `master` runs no CI on this change unless the branch filter is widened.

## 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 tasks resource to this CodeIgniter 4 app. Read composer.json, app/Config/Routes.php, app/Config/Routing.php, app/Config/Filters.php, app/Config/Cors.php, app/Config/Format.php, app/Config/Database.php, the tests directory and .github/workflows/phpunit.yml first. Use the spark generators: a migration creating a tasks table with id, title, done and timestamps, a TaskModel with allowedFields, timestamps and validation rules requiring a title, and an Api/Tasks controller generated with --restful that extends ResourceController with modelName and format json. Implement index, show, create, update and delete with the ResponseTrait helpers (respondCreated, respondDeleted, failNotFound, failValidationErrors) and read bodies with getJSON. Route it with $routes->resource inside an api group filtered by cors, excluding new and edit and using a (:num) placeholder, and fill in the Cors config. Write a feature test using FeatureTestTrait and DatabaseTestTrait with the tests database group covering create, list, validation failure and not found, run vendor/bin/phpunit, and open a pull request that quotes the test output and lists the routes.",
  "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 a migration under `app/Database/Migrations/`, `app/Models/TaskModel.php`, `app/Entities/Task.php`, `app/Controllers/Api/Tasks.php` and `tests/feature/TasksApiTest.php`, and changes `app/Config/Routes.php` and `app/Config/Cors.php`. Its description lists the six routes `php spark routes` prints for the resource, quotes the PHPUnit summary from the `tests` SQLite group, and shows one `curl` exchange per verb against `php spark serve` with the JSON that came back, including the `status`, `code` and `messages` body of a rejected create.

A reviewer checks the `allowedFields` list against what a client may set, that `done` is cast to a boolean in the entity so the JSON does not carry `"0"` strings, and whether `allowedOrigins` in `Cors.php` should name their front end's host or stay a wildcard until deployment. They also decide whether to keep `$format = 'json'` fixed or drop it to let `Format.php` negotiate XML for clients that ask.

The home route, the `Home` controller and the existing health and database example tests are untouched, and the migration is the only step a deployment has to run.

## Run it on every new resource in the backlog

A team that grows its API one resource at a time can start this job from a short script on its own server: for each resource a planning issue names, send this body to `POST /o/{org}/sessions` with the resource name and its fields appended to the prompt and the repository in `resources`, and a `request_id` that is a UUID v5 of the issue id so a rerun returns the run already started. Each run opens one pull request with its migration, model, controller, routes and tests, and the key's `webhook_url` receives `run.completed` for each.

An automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` can run read-only with a prompt that checks any new controller under `app/Controllers/Api/` extends `ResourceController`, is routed with `$routes->resource`, and has a feature test, and comments when one is missing. The trigger adds the event after the prompt and fills in no placeholder.

## Why run it on Rush?

CodeIgniter's REST support is a set of conventions spread over the user guide: the generator flag, the `resource()` options, the trait's status helpers, the `tests` database group that keeps PHPUnit off the live database. The agent reads the starter's config files to see which of those are already in place, generates the pieces with `spark` so they match the framework's own layout, and runs the suite in its sandbox against the in-memory SQLite group, with the commands and their output kept in the run's record.

It also tells the reviewer what it did not do. No authentication filter, no CSRF on the API group, no change to the CI branch filter: each is named in the pull request as a decision for the team, so the first resource ships small and the next one can copy it.

## Frequently asked questions

### Why a ResourceController and not plain controller methods?

`ResourceController` already mixes in `API\ResponseTrait`, loads the model named in `$modelName`, and pairs with `$routes->resource()`, which generates the seven standard routes in one line. A plain controller would need the same routes written by hand and the trait added separately; the generator's `--restful` flag exists for exactly this case.

### Does the API negotiate XML?

Not as written. The controller sets `$format = 'json'`, which bypasses negotiation so every client gets JSON. Removing that property makes the trait read the `Accept` header against `$supportedResponseFormats` in `app/Config/Format.php`, which already lists `application/xml` and `text/xml`, so XML is one deleted line away.

### Which database do the tests use?

The `tests` group in `app/Config/Database.php`: SQLite3 on `:memory:` with a `db_` prefix, which the config switches to whenever `ENVIRONMENT` is `testing`. `DatabaseTestTrait` with `$migrate = true` runs the new migration there before each test, so the suite needs no MySQL and touches no live data.

### Is CSRF protection applied to the API?

No. The starter leaves `csrf` out of its global filters, and a JSON client has no form to carry a token in. The `api` route group gets the `cors` filter only; the pull request says that an authentication filter, such as a token check, is the right next step before the API is public.

### Why does the pull request mention the CI branch?

`.github/workflows/phpunit.yml` runs only on `pull_request` events whose base branch is `develop`. In a repository that merges to `master`, the new tests never run in CI. The agent points this out and leaves the filter alone, since changing it is a workflow decision rather than part of the API.

## More CodeIgniter jobs

- [Add Security Headers to a CodeIgniter 4 App](https://getrush.ai/run/add-security-headers/codeigniter/)
- [Add Database Seeders to a CodeIgniter 4 App](https://getrush.ai/run/add-seed-data/codeigniter/)
- [Add User Registration to a CodeIgniter App](https://getrush.ai/run/add-user-registration/codeigniter/)

## The same job on other stacks

- [Add a REST API to a Spring Boot App from a Linear Issue](https://getrush.ai/run/add-rest-api/spring-boot/)
- [Add a REST API to a Yii2 App](https://getrush.ai/run/add-rest-api/yii/)
- [Add a JSON REST API to a CakePHP App](https://getrush.ai/run/add-rest-api/cakephp/)

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