Moving to Kipchak

Moving to Kipchak from FastAPI

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

Who this page is for

You have a JSON API in FastAPI and you are moving it to Kipchak, which means from Python to PHP. Much of what you rely on in FastAPI has a counterpart: typed request and response models, validation from those types, an OpenAPI document generated from the code, and an app that stays in memory between requests. This page takes one small API, a bookshelf, as a FastAPI developer would write it, and moves it to Kipchak one part at a time. 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 are complete, and pass the same black-box test suite of 47 checks over HTTP and their own tests (pytest and PHPUnit). The versions used:

Version
FastAPIfastapi 0.162.2, pydantic 2.14.3, sqlmodel 0.0.48, uvicorn 0.54.0, Python 3.13
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 FastAPI on this page links to the FastAPI, Pydantic or Starlette documentation and was checked against the running FastAPI version.

What Kipchak gives you

What you value in FastAPI comes with you: a typed class validates the request and describes it in the OpenAPI document, from one set of rules. The Book schema the Kipchak bookshelf generates, from its DTO's Field attributes (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 }

Kipchak adds to it. Each point below is shown from the Kipchak bookshelf.

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 FastAPI bookshelf answers with the model itself, {"detail": "..."} for an exception, and {"detail": [...]} for 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.

Drivers and middleware, configured and in order. Databases, caches, queues and identity come as drivers and middleware, each with its configuration file, and kipchak add installs one, copies its configuration and initialises it in the right place. 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

A long-lived app, with no async to manage. Like uvicorn, FrankenPHP keeps the app in memory between requests. Each worker serves one request at a time, so Kipchak code is plain PHP, with no choice to make between def and async def and nothing to await.

Your assistant knows the conventions. The starter includes an AGENTS.md that describes the project to coding assistants, and the Kipchak agent skill teaches them Kipchak's conventions.

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 a FastAPI project starts with a virtual environment and pip install, a Kipchak project starts from the starter project, with Composer, PHP's package manager:

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. composer.json and composer.lock play the parts of requirements.in and requirements.txt.

The FastAPI bookshelf is one file, main.py. The starter gives each part its own folder:

FastAPI bookshelfKipchak
app = FastAPI(...) and the @app.get(...) decoratorsroutes/v1/books.php
the path operation functionsapi/Controllers/v1/Books.php
BookInput and BookOutput (Pydantic models)api/DataTransferObjects/v1/Book.php, one DTO for both
Book(..., table=True) (SQLModel table)api/Entities/Doctrine/Primary/Book.php (the table) and api/Models/Books.php (the queries)
create_engine(...) and Depends(get_session)the Doctrine driver, configured in config/
seed() in lifespana migration in migrations/database/
os.environ.get(...)env() in config/*.php

Routes

FastAPI declares a route with a decorator on the function that handles it:

@app.get("/v1/books/{id:int}", response_model=BookOutput)
def get_book(id: int, session: SessionDep):
    ...

Kipchak's router is Slim's, and the routes are listed in one file, each pointing at a controller method:

// 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']);
});

The FastAPI bookshelf uses Starlette's :int path convertor, so that /v1/books/abc misses the route and is a 404. Kipchak's {id:[0-9]+} does the same with a regular expression. The route gives the controller the id as a string in $args, and the controller casts it. vendor/bin/kipchak routes lists every route.

The request and its validation

The FastAPI bookshelf validates with Pydantic, through SQLModel:

class BookInput(SQLModel):
    title: str = Field(min_length=1, max_length=200)
    author: str = Field(min_length=1, max_length=100)
    year: int | None = None

    @field_validator("year")
    @classmethod
    def year_in_range(cls, year: int | None) -> int | None:
        if year is not None and not 1450 <= year <= date.today().year:
            raise ValueError(f"year must be from 1450 to {date.today().year}")
        return year

A Kipchak DTO is the same idea in PHP: a typed class, whose Field attributes state the rules once, enforce them on request bodies and put them in the OpenAPI document. A rule that is not a simple limit is a Check, where Pydantic has a field_validator:

#[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;
    }
}

FastAPI validates the body because the function's parameter is typed BookInput. In Kipchak the controller asks for it, giving id the value the server will replace:

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

What changes:

  • One class for input and output. The FastAPI bookshelf has BookInput and BookOutput (which adds id). The Kipchak DTO has id too, read-only in the document, and Input::from() is given its value.
  • Types are strict. Pydantic's default (lax) mode converts the string "1871" to the integer 1871 (conversion table), and the FastAPI bookshelf stores it. Kipchak refuses "year": "1871", as Pydantic's strict mode would. If your clients send numbers as strings, they will need to send numbers.
  • An invalid body is 400, not 422. See Errors.

Both report every problem at once.

The database

The FastAPI bookshelf's table is a SQLModel class, created with SQLModel.metadata.create_all() and seeded when the app starts. In Kipchak, the Doctrine driver runs SQL migrations, with the rollback after a -- Down line; the Kipchak bookshelf's migration creates the table and inserts the three seed books:

-- 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
);
INSERT INTO books (title, author, year) VALUES
    ('Middlemarch', 'George Eliot', 1871),
    ('Emma', 'Jane Austen', 1815),
    ('The Thousand and One Nights', 'Anonymous', NULL);

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

SQLModel's table=True class maps to a Doctrine entity:

#[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,
    ) {}
}

The FastAPI bookshelf gets a session in each function through a dependency (dependencies), SessionDep. In Kipchak, a model class asks the driver for the entity manager, Doctrine's session, and answers in DTOs:

SQLModelDoctrine in Kipchak
session.exec(select(Book).order_by(Book.id)).all()$em->createQueryBuilder()->select('b')->from(BookEntity::class, 'b')->orderBy('b.id', \SortDirection::Ascending)
session.get(Book, id)$em->find(BookEntity::class, $id)
session.add(book), session.commit(), session.refresh(book)$em->persist($book), $em->flush()
session.delete(book), session.commit()$em->remove($book), $em->flush()
final class Books
{
    private EntityManagerInterface $em;

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

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

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

    // all(), create() and delete() in the same way

    private function dto(BookEntity $book): Book
    {
        return new Book($book->id, $book->title, $book->author, $book->year);
    }
}

Controllers and responses

A FastAPI path operation returns a value, and response_model shapes it. A Kipchak controller action takes the PSR-7 request and response, and returns a response:

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 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);
}
FastAPIKipchak
raise HTTPException(status_code=404, detail=...)throw new HttpNotFoundException($request, ...)
status_code=201 on the decoratorthe status passed to Http\Response::json()
response.headers["Location"] = ...$response->withHeader('Location', ...)
status_code=204 and returning Nonereturn $response->withStatus(204)

Http\Response::json() writes Kipchak's envelope:

FastAPI bookshelfKipchak bookshelf
{"title": "Middlemarch", "author": "George Eliot", "year": 1871, "id": 1}{"code": 200, "status": "OK", "data": {"id": 1, "title": "Middlemarch", "author": "George Eliot", "year": 1871}}

The FastAPI bookshelf puts id last because BookOutput adds it to BookInput; Kipchak writes the DTO's properties in their order.

Errors

FastAPI answers an HTTPException with {"detail": ...}, and an invalid request with 422 and a list of the problems (handling errors). In Kipchak, the Error middleware answers every error in the envelope of every other response.

GET /v1/books/99, FastAPI:

{ "detail": "No book has the ID 99" }

Kipchak:

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

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

{
  "detail": [
    { "type": "string_too_short", "loc": ["body", "title"], "msg": "String should have at least 1 character", "input": "", "ctx": { "min_length": 1 } },
    { "type": "missing", "loc": ["body", "author"], "msg": "Field required", "input": { "title": "", "year": 1449 } },
    { "type": "value_error", "loc": ["body", "year"], "msg": "Value error, year must be from 1450 to 2026", "input": 1449, "ctx": { "error": {} } }
  ]
}

Kipchak answers 400, with each field's problems in meta.errors:

{
  "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 that reads FastAPI's detail list by loc reads Kipchak's meta.errors by field name. A body that is not JSON is 422 json_invalid from FastAPI, and 400 "The body is not valid JSON." from Kipchak.

The OpenAPI document

FastAPI generates the document from the path operations and the Pydantic models, and serves interactive documentation at /docs (interactive API docs). Kipchak builds the document from swagger-php attributes on the controllers and DTOs, and serves it at /openapi.json. The Field rules are already in it; each operation states its path, parameters and responses, which FastAPI reads from the function's signature:

#[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.'),
    ],
)]

The starter adds the envelope, and the error envelope for a 4xx, to the document. It serves no interactive page: point the OpenAPI viewer of your choice at /openapi.json. vendor/bin/kipchak openapi:validate checks the document.

Tests

The FastAPI bookshelf tests with pytest and TestClient (testing), with a fixture that recreates and seeds the database for each test:

def test_refuses_an_invalid_book(client, body):
    assert client.post("/v1/books", json=body).status_code == 422

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

uvicorn runs the FastAPI app as a long-lived process, and its workers serve request after request (server workers). Kipchak works the same way: FrankenPHP in worker mode boots the API once, and each worker serves many requests. The starter's Dockerfile and compose.yaml run it:

docker compose up --watch

What you know from FastAPI carries over: anything kept at module level in Python, or in a static property in PHP, outlives the request and is shared with the next one. One difference: the FastAPI bookshelf's functions are plain def, which FastAPI runs in a thread pool (path operation functions). Kipchak's workers are threads too, each serving one request at a time, and PHP code needs no async or await.

What your clients will notice

FastAPI bookshelfKipchak bookshelf
A successthe book, id last{"code": 200, "status": "OK", "data": ...}
An error{"detail": "..."}{"code", "status", "data"}
An invalid body422, {"detail": [{"type", "loc", "msg", "input"}]}400, {"code", "status", "meta": {"errors": {field: [messages]}}, "data"}
A body that is not JSON422, json_invalid400, "The body is not valid JSON."
"year": "1871"taken as 1871refused, 400
Interactive documentationat /docsnone: the document is at /openapi.json
CORS headersnone unless CORSMiddleware is addednone 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

FastAPI reads each operation from the function's signature and serves interactive documentation at /docs; Kipchak asks you to state each operation in attributes, and to bring your own viewer for /openapi.json. And the move is a change of language, from Python to PHP. In return, the document is checked against your routes, and every response has one shape.

Next steps

Previous
From Slim
Next
Config