Moving to Kipchak

Moving to Kipchak from Laravel

Move a Laravel JSON API to Kipchak, step by step, and know what your clients will notice

Who this page is for

You have a JSON API in Laravel and you are moving it to Kipchak. This page takes one small API, a bookshelf, as a Laravel developer would write it, and moves it to Kipchak one part at a time: routes, validation, the database, responses, errors, the OpenAPI document, tests and running it. It starts with what you gain, and for each part says what maps directly, what changes, and what your API's clients will notice.

Both versions of the bookshelf are complete, and pass the same black-box test suite of 47 checks over HTTP and their own framework's tests. The versions used:

Version
Laravellaravel/laravel 13.11.0 (framework 13.40.0), dedoc/scramble 0.13, PHP 8.5
Kipchakstarter 4.6 (core 3.19, Error middleware 1.36, Doctrine driver 1.55), PHP 8.5 on FrankenPHP in worker mode

Every statement about Laravel on this page links to the Laravel 13 documentation and was checked against the running Laravel version.

What Kipchak gives you

Kipchak is built for one thing, JSON APIs, and makes the API's contract the centre of the code. Each point below is shown from the Kipchak bookshelf, with the command or output that proves it.

One class is the contract. In the Laravel bookshelf, the rules live in a form request, the response shape in an API resource, and the document is inferred from both by Scramble. In Kipchak one DTO is all three: the rules in its Field attributes are enforced on request bodies and written into the OpenAPI document, so they cannot drift apart. The Book schema the Kipchak bookshelf generates, from the DTO below:

"title": { "description": "The title of the book.", "type": "string", "example": "Middlemarch", "maxLength": 200, "minLength": 1 },
"year":  { "description": "The year of the book, from 1450 to the current year.", "type": "integer", "example": 1871, "nullable": true, "minimum": 1450 }

A document you can check. The CLI checks the generated document against the OpenAPI specification and against the routes the API registers: a route with no operation, an operation with no route or an undeclared path parameter is an error, and the command exits with 1, so it can gate a release in CI (openapi:validate):

$ vendor/bin/kipchak openapi:validate --strict
The document is valid. 0 errors, 0 warnings.

One shape for every response. Successes, validation errors, 404s and 405s all arrive as {"code", "status", "data"}, so a client parses one shape. The Laravel bookshelf answers in three: {"data"} from a resource, {"message"} from an exception, and {"message", "errors"} from validation (see Errors).

A whole resource, tested and documented, in one command. make:resource writes the DTO, model, controller, routes and tests in the starter's conventions. Run on the bookshelf, it added an Authors resource whose seven tests pass and whose operations are in the document:

$ vendor/bin/kipchak make:resource Authors --crud --fields='id:int,name:string,born:?int'
Created api/DataTransferObjects/v1/Author.php
Created api/Models/Authors.php
Created api/Controllers/v1/Authors.php
Created routes/v1/authors.php
Created tests/AuthorsTest.php
$ vendor/bin/phpunit
OK (32 tests, 80 assertions)
$ vendor/bin/kipchak openapi:validate --strict
The document is valid. 0 errors, 0 warnings.

Middleware that installs itself in the right place. kipchak add installs a Kipchak middleware, copies its configuration and initialises it where it must go, between the two Error middleware. Adding JWT validation against an identity provider's keys (auth-jwks, with issuer and audience checks) and rate limiting (Subashi, which answers 429) to the bookshelf:

$ vendor/bin/kipchak add auth-jwks
Created config/kipchak.auth.jwks.php
Modified middlewares/middlewares.php
$ vendor/bin/kipchak add subashi
Created config/kipchak.subashi.php
Modified drivers/drivers.php
Modified middlewares/middlewares.php

The application stays in memory. Kipchak runs on FrankenPHP in worker mode from the first request: the API boots once and serves many requests, as Laravel does with Octane. There is nothing to add.

Only what your API uses. The bookshelf's Kipchak project has the Doctrine driver and the Error middleware, because it uses them, and nothing for sessions, views, queues or mail.

The bookshelf

Method and pathSuccessErrors
GET /v1/books200, the books ordered by ID; optional ?author= filter400 if author is empty
GET /v1/books/{id}200, the book404 if no book has the ID, or the ID is not an integer
POST /v1/books201, the book as created, with a Location headeran invalid body (see Validation)
DELETE /v1/books/{id}204, no body404 if no book has the ID
GET /openapi.json200, an OpenAPI 3 document generated from the code

A book has id (set by the server), title (1 to 200 characters), author (1 to 100 characters) and year (optional; from 1450 to the current year). The data lives in SQLite.

Start the Kipchak project

Where Laravel starts with laravel new or composer create-project laravel/laravel, Kipchak starts from its starter project:

composer create-project kipchak/starter bookshelf
cd bookshelf
vendor/bin/kipchak add doctrine

The starter comes with the Kipchak CLI. kipchak add doctrine installs the Doctrine driver, copies its configuration to config/kipchak.doctrine.php and initialises it in drivers/drivers.php. Laravel ships with its database layer; Kipchak installs only what the API uses, and each driver is a Composer package.

The parts of a Laravel app map to the starter's folders like this:

LaravelKipchak
routes/api.phproutes/v1/books.php, one file per resource and version
app/Http/Controllers/BookController.phpapi/Controllers/v1/Books.php
app/Http/Requests/StoreBookRequest.php and app/Http/Resources/BookResource.phpapi/DataTransferObjects/v1/Book.php, one DTO for both
app/Models/Book.php (Eloquent)api/Entities/Doctrine/Primary/Book.php (the table) and api/Models/Books.php (the queries)
database/migrations/migrations/database/, plain SQL
config/*.php and .envconfig/kipchak.*.php, which read the environment with env()
bootstrap/app.php (middleware, exceptions)middlewares/middlewares.php and drivers/drivers.php

Routes

In Laravel, the bookshelf's routes are one line:

// routes/api.php
Route::prefix('v1')->group(function () {
    Route::apiResource('books', BookController::class)->only(['index', 'show', 'store', 'destroy']);
});

Kipchak's router is Slim's, and each route is written out:

// routes/v1/books.php
$app->group('/v1', function (RouteCollectorProxy $group) {
    $group->get('/books', [Controllers\v1\Books::class, 'list']);
    $group->get('/books/{id:[0-9]+}', [Controllers\v1\Books::class, 'get']);
    $group->post('/books', [Controllers\v1\Books::class, 'create']);
    $group->delete('/books/{id:[0-9]+}', [Controllers\v1\Books::class, 'delete']);
});

What changes:

  • No route model binding. Laravel's implicit binding turns {book} into a Book model and answers 404 when there is none. In Kipchak the route gives the controller the id, the controller asks the model for the book, and throws HttpNotFoundException when there is none (see Controllers).
  • The ID's type is part of the route. {id:[0-9]+} means /v1/books/abc matches no route, and Kipchak answers 404, as Laravel does when binding finds no model.
  • No api prefix to undo. Laravel 13 serves routes/api.php under /api (API routes) unless apiPrefix is changed in bootstrap/app.php; the Laravel bookshelf sets it to '' to serve /v1/books. Kipchak's paths are the ones you write.

vendor/bin/kipchak routes lists every route, as php artisan route:list does.

The request and its validation

Laravel validates the body with a form request:

class StoreBookRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'min:1', 'max:200'],
            'author' => ['required', 'string', 'min:1', 'max:100'],
            'year' => ['nullable', 'integer', 'min:1450', 'max:'.date('Y')],
        ];
    }
}

In Kipchak the rules live on the DTO, the typed class that describes a book. Each Field states a rule once: it is enforced on request bodies and appears in the OpenAPI document. A rule that is not a simple limit is a Check:

#[OA\Schema(schema: 'Book', description: 'A book.', required: ['title', 'author'])]
final readonly class Book
{
    public function __construct(
        #[OA\Property(description: 'Identifier of the book.', readOnly: true, example: 1)]
        public int $id,

        #[Field(description: 'The title of the book.', maxLength: 200, minLength: 1, example: 'Middlemarch')]
        public string $title,

        #[Field(description: 'The author of the book.', maxLength: 100, minLength: 1, example: 'George Eliot')]
        public string $author,

        #[Field(description: 'The year of the book, from 1450 to the current year.', minimum: 1450, nullable: true, example: 1871)]
        #[Check([self::class, 'notInTheFuture'])]
        public ?int $year = null,
    ) {}

    public static function notInTheFuture(int $year): ?string
    {
        return $year > (int) date('Y') ? 'Must not be in the future.' : null;
    }
}

The controller reads the body into the DTO with Input::from(), giving id the value the server will replace:

$book = (new BooksModel())->create(Input::from($request, Book::class, ['id' => 0]));

What changes:

  • One class for the request and the response. Laravel splits them into a form request and an API resource. Kipchak's DTO is both, and the OpenAPI schema too, so the three cannot disagree.
  • Types are strict. Laravel's integer rule accepts the string "1871", and the Laravel bookshelf stores it as the integer 1871. Kipchak maps the body onto typed properties, so "year": "1871" is refused. If your clients send numbers as strings, they will need to send numbers.
  • Empty strings stay strings. Laravel's ConvertEmptyStringsToNull middleware (a note on optional fields) turns "title": "" into null, so the error says the title is required. Kipchak keeps the empty string and says it is too short.
  • An invalid body is 400, not 422. See What your clients will notice.

Both report every problem at once, field by field.

The database

Laravel's migration uses the schema builder; Kipchak's Doctrine driver runs plain SQL files, with the rollback after a -- Down line:

-- migrations/database/20261108000000_create_books.sql
CREATE TABLE books (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title VARCHAR(200) NOT NULL,
    author VARCHAR(100) NOT NULL,
    year INTEGER NULL
);

-- Down
DROP TABLE books;
php vendor/bin/doctrine migrations:up --em=primary

The Laravel bookshelf's seed books come from a seeder (php artisan migrate --seed). Kipchak has no seeders: the Kipchak bookshelf inserts its three seed books in the migration itself.

Eloquent's model is both the table and the queries. Doctrine separates them. The entity maps the table:

#[ORM\Entity]
#[ORM\Table(name: 'books')]
class Book
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer')]
    #[ORM\GeneratedValue]
    public private(set) int $id;

    public function __construct(
        #[ORM\Column(type: 'string', length: 200)]
        public private(set) string $title,

        #[ORM\Column(type: 'string', length: 100)]
        public private(set) string $author,

        #[ORM\Column(type: 'integer', nullable: true)]
        public private(set) ?int $year = null,
    ) {}
}

and a model class in api/Models/ holds the queries, and answers in DTOs:

final class Books
{
    private EntityManagerInterface $em;

    public function __construct()
    {
        $this->em = Doctrine::get('entitymanager.primary');
    }

    /** @return list<Book> */
    public function all(?string $author = null): array
    {
        $query = $this->em->createQueryBuilder()->select('b')->from(BookEntity::class, 'b')
            ->orderBy('b.id', \SortDirection::Ascending);
        if ($author !== null) {
            $query->where('b.author = :author')->setParameter('author', $author);
        }

        return array_map($this->dto(...), $query->getQuery()->getResult());
    }

    public function find(int $id): ?Book
    {
        $book = $this->em->find(BookEntity::class, $id);

        return $book === null ? null : $this->dto($book);
    }

    // create() persists and flushes; delete() removes and flushes.

    private function dto(BookEntity $book): Book
    {
        return new Book($book->id, $book->title, $book->author, $book->year);
    }
}
EloquentDoctrine in Kipchak
Book::query()->where('author', $author)->orderBy('id')->get()the query builder above
Book::findOrFail($id) / route model binding$em->find(BookEntity::class, $id), then 404 if null
Book::create($validated)new BookEntity(...), $em->persist(), $em->flush()
$book->delete()$em->remove($book), $em->flush()
#[Fillable([...])]not needed: the DTO decides what a request may set

If you would rather write SQL, the driver also gives you Doctrine DBAL connections without the ORM.

Controllers and responses

The Laravel controller returns API resources, and Laravel serialises them:

public function store(StoreBookRequest $request): JsonResponse
{
    $book = Book::create($request->validated());

    return (new BookResource($book))
        ->response()
        ->setStatusCode(201)
        ->header('Location', "/v1/books/{$book->id}");
}

A Kipchak controller action takes the PSR-7 request and response, and returns a response:

public function create(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{
    $book = (new BooksModel())->create(Input::from($request, Book::class, ['id' => 0]));

    return Http\Response::json($response->withHeader('Location', "/v1/books/{$book->id}"), $book, 201);
}

public function get(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{
    $book = (new BooksModel())->find((int) $args['id']);
    if ($book === null) {
        throw new HttpNotFoundException($request, "No book has the ID {$args['id']}.");
    }

    return Http\Response::json($response, $book, 200);
}

public function delete(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{
    if (!(new BooksModel())->delete((int) $args['id'])) {
        throw new HttpNotFoundException($request, "No book has the ID {$args['id']}.");
    }

    return $response->withStatus(204);
}

Http\Response::json() writes Kipchak's envelope: the status as a number and as a name, and the data.

LaravelKipchak
GET /v1/books/1 → {"data": {"id": 1, "title": "Middlemarch", "author": "George Eliot", "year": 1871}}{"code": 200, "status": "OK", "data": {"id": 1, "title": "Middlemarch", "author": "George Eliot", "year": 1871}}
abort_if(..., 400, 'author must not be empty.')throw new HttpBadRequestException($request, 'author must not be empty.')
response()->noContent()$response->withStatus(204)

The Error middleware turns each Http*Exception into a response in the same envelope (see Errors).

Errors

Laravel renders exceptions as JSON for API requests once shouldRenderJsonWhen says so in bootstrap/app.php (rendering exceptions), with a message, and for validation errors an errors object (the response format). In Kipchak, the Error middleware, initialised in middlewares/middlewares.php, does this for every route, in the envelope of every other response.

The same requests, answered by both:

GET /v1/books/99, Laravel:

{ "message": "No query results for model [App\\Models\\Book] 99" }

Kipchak:

{ "code": 404, "status": "RESOURCE_NOT_FOUND", "data": "No book has the ID 99." }

POST /v1/books with {"title": "", "year": 1449}, Laravel answers 422:

{
  "message": "The title field is required. (and 2 more errors)",
  "errors": {
    "title": ["The title field is required."],
    "author": ["The author field is required."],
    "year": ["The year field must be at least 1450."]
  }
}

Kipchak answers 400:

{
  "code": 400,
  "status": "BAD_REQUEST",
  "meta": {
    "errors": {
      "title": ["Must be at least 1 character."],
      "author": ["This field is required."],
      "year": ["Must be at least 1450."]
    }
  },
  "data": "The book is not valid: title: Must be at least 1 character. author: This field is required. year: Must be at least 1450."
}

A client reading Laravel's errors reads Kipchak's meta.errors: the same keys, one array of messages per field.

The OpenAPI document

The Laravel bookshelf uses Scramble, which infers the document from routes, form requests and resources. Kipchak builds it from swagger-php attributes on the controllers and DTOs, and serves it at /openapi.json. The Field rules on the DTO are already in it; each operation states its path, parameters and responses:

#[OA\Get(
    path: '/v1/books/{id}',
    operationId: 'getBook',
    summary: 'Get one book',
    tags: ['Books'],
    parameters: [
        new OA\Parameter(name: 'id', in: 'path', required: true, schema: new OA\Schema(type: 'integer', example: 1)),
    ],
    responses: [
        new OA\Response(response: 200, description: 'The book.', content: new OA\JsonContent(ref: '#/components/schemas/Book')),
        new OA\Response(response: 404, description: 'No book has that ID.'),
    ],
)]

A response declares only its data; the starter adds the envelope, and the error envelope for a 4xx, to the document. vendor/bin/kipchak openapi:validate checks the document. The path parameter is {id}, where Scramble names it after the route's {book}.

Tests

The Laravel bookshelf's feature tests use RefreshDatabase and the JSON helpers (testing JSON APIs):

$this->postJson('/v1/books', ['title' => '', 'year' => 1449])
    ->assertUnprocessable()
    ->assertJsonValidationErrors(['title', 'author', 'year']);

The starter's tests are PHPUnit tests on ApiTestCase, which boots the API once, as a FrankenPHP worker does, and sends it PSR-7 requests with no web server. The Kipchak bookshelf's setUp() puts the three seed books back before each test:

public function testEveryProblemIsReportedAtOnceByField(): void
{
    $response = $this->send(['title' => '', 'year' => 1449]);

    self::assertSame(400, $response->getStatusCode());
    self::assertSame(['errors' => [
        'title' => ['Must be at least 1 character.'],
        'author' => ['This field is required.'],
        'year' => ['Must be at least 1450.'],
    ]], $this->json($response)['meta']);
}

Run them with vendor/bin/phpunit.

Running it

php artisan serve boots the application for each request, and Octane keeps it in memory between requests. Kipchak runs on FrankenPHP in worker mode by default: the API boots once and each worker serves many requests. The starter's Dockerfile and compose.yaml run it:

docker compose up --watch

If your Laravel API already runs on Octane, you know the rule that matters here: nothing that belongs to one request may stay in a static property or a long-lived service. If it does not, read Caddy and FrankenPHP before you move code that keeps state.

What your clients will notice

Laravel bookshelfKipchak bookshelf
A success{"data": ...}{"code": 200, "status": "OK", "data": ...}
An invalid body422, {"message", "errors"}400, {"code", "status", "meta": {"errors"}, "data"}
A missing book404, {"message"}404, {"code", "status", "data"}
"year": "1871"taken as 1871refused, 400
"title": """The title field is required.""Must be at least 1 character."
CORS headersnone on /v1: Laravel's CORS settings cover api/* by defaultnone until the origins are listed in CORS_ALLOWED_ORIGINS; the starter then answers preflight requests (CORS)

Everything else is the same: the paths, the methods, the fields and their rules, 201 with Location, 204, and 404. If your clients cannot change when you move, tell them which of these shapes change, or bring the change in under a new version of the API (see Versioning).

Trade-offs

Kipchak is more explicit than Laravel: you write each route, each lookup's 404 and each operation's attributes, where apiResource, route model binding and Scramble infer them. Laravel also brings seeders, factories and its schema builder, which a Kipchak project replaces with SQL migrations and its own test setup. In return, what you write is the contract, and the CLI checks it.

Next steps

Previous
Overview