Skip to content

Build your first feature: API

Chapter 1 of 3. Generate a Projects API, then add a description field and follow it from the shared schema into SQLite. By the end, you can create a project over HTTP and retrieve it after restarting the app.

ChapterWorking result
1. Build the API (this page)Create and retrieve persisted projects over HTTP
2. Add ownershipEach account can read and change only its own projects
3. Connect the UICreate, list, edit, and delete projects in the browser

Before you start

Continue in the full-stack SQLite app from the quickstart. You should be able to sign in, use Todos, and pass bun beignet check. Keep the starter's authentication and React Query setup. No additional packages are needed.

Run commands from the app root and keep the development server in a separate terminal. This chapter creates a new projects feature; run its generator once, then edit those files through the rest of the tutorial. See Read the examples for how to use the diffs and complete files.

This first chapter is a local API exercise. The generated projects resource has no authorization rules yet; complete Add ownership before making it available to users.

The generator creates the feature's contracts, use cases, ports, and adapters. Your edits in this chapter focus on these files:

FilesChange
features/projects/schemas.tsAdd the description to the response and create input
infra/db/schema/projects.tsStore the description
infra/projects/*-project-repository.tsReturn and persist the field in both adapters
features/projects/tests/projects.test.tsUpdate the existing test data
drizzle/Generate and apply the schema migration

Generate the resource

bash
bun beignet make resource projects --useCaseLayout split

This walkthrough selects separate files to develop ownership and concurrency rules across five workflows. Omit --useCaseLayout split to keep a new resource's use cases together in use-cases.ts.

The generator creates five operations: list, create, read, update, and delete. Each has an HTTP contract and a use case. It also creates shared schemas, a repository interface, database and in-memory implementations, routes, and a starter test. It registers the new pieces in ports/index.ts, infra/port-wiring.ts, infra/db/repositories.ts, and server/routes.ts.

Because the starter persists with Drizzle, create and apply the migration for the new table:

bash
bun beignet db generate
bun beignet db migrate
bun beignet db status

Expect Database migrations are current. Then confirm the routes are registered:

bash
bun beignet routes
txt
METHOD  PATH               CONTRACT       HANDLER
GET     /api/projects      listProjects   app/api/[[...path]]/route.ts:GET
POST    /api/projects      createProject  app/api/[[...path]]/route.ts:POST
DELETE  /api/projects/:id  deleteProject  app/api/[[...path]]/route.ts:DELETE
GET     /api/projects/:id  getProject     app/api/[[...path]]/route.ts:GET
PATCH   /api/projects/:id  updateProject  app/api/[[...path]]/route.ts:PATCH
...

Look for all five Projects endpoints. The output also includes the starter's Todo routes, omitted above. A route's contract describes its HTTP interface; its handler is the Next.js entrypoint that receives the request.

Understand the generated code

Follow a read request through three files: the contract describes its input and response, the use case retrieves the project, and the repository port gives the use case access to persistence.

Read the contract

features/projects/contracts.ts owns the HTTP surface. Each endpoint is a builder chain that names its inputs, catalog errors, and responses:

typescript
// features/projects/contracts.ts (excerpt)
const projects = defineContractGroup()
  .namespace("projects")
  .responses({ 500: ErrorResponseSchema });

export const createProject = projects
  .post("/api/projects")
  .body(CreateProjectInputSchema)
  .responses({ 201: ProjectSchema });

export const getProject = projects
  .get("/api/projects/:id")
  .pathParams(ProjectIdInputSchema)
  .errors({ ProjectNotFound: errors.ProjectNotFound })
  .responses({ 200: ProjectSchema });

The schemas it references live in features/projects/schemas.ts, so use cases, ports, tests, and the client can share them without importing the contract.

Read the use case

Each endpoint binds to a use case in features/projects/use-cases/. The generated get-project.ts is the whole pattern in one file:

typescript
// features/projects/use-cases/get-project.ts (excerpt)
export const getProjectUseCase = useCase
  .query("projects.get")
  .input(ProjectIdInputSchema)
  .output(ProjectSchema)
  .run(async ({ ctx, input }) => {
    const project = await ctx.ports.projects.findById(input.id);
    if (!project) {
      throw appError("ProjectNotFound", {
        details: { id: input.id },
      });
    }

    return project;
  });

Input and output are validated against the same schemas the contract uses. If the project is missing, the use case throws the declared ProjectNotFound error. Otherwise it returns the project. ctx.ports.projects supplies the repository used to look up the data.

Read the port

A port is the interface a use case calls to do work outside its own logic. For Projects, features/projects/ports.ts defines the repository operations:

typescript
// features/projects/ports.ts (excerpt)
export interface ProjectRepository {
  list(query: ListProjectsQuery): Promise<ListProjectsResult>;
  create(input: CreateProjectInput): Promise<Project>;
  findById(id: string): Promise<Project | null>;
  update(input: UpdateProjectInput): Promise<Project | null>;
  delete(id: string): Promise<boolean>;
}

Two adapters implement it: infra/projects/drizzle-project-repository.ts for the real database and infra/projects/in-memory-project-repository.ts for tests. infra/port-wiring.ts wires the Drizzle one into ctx.ports.projects.

features/projects/routes.ts then maps each contract to its use case, and the generator registered that route group in server/routes.ts for you.

Make a change: add a field

Choose files in each explorer to review their changes or copy the complete source for that step.

Projects need a description. Format the generated files and organize their imports before editing so they match the examples:

bash
bunx @biomejs/biome check --write .

First add the field to the response and create input in features/projects/schemas.ts. The response always includes description, which can be null; callers may omit it when creating a project.

features/projects/schemas.ts
Return a nullable description and accept it when creating a project.

Run the typecheck now to find the code that must return this new field:

bash
bun run typecheck

Type errors are expected at this point. The two repository adapters and their test data return the old shape. The next edits add the field there. The contract and use cases already reference the shared schemas, so they do not need another field definition.

Add the nullable database column, return it from both adapters, and persist it when a project is created. Omitting the optional input stores null.

Add a nullable column so SQLite can store the description.

Give the existing test rows a description too:

features/projects/tests/projects.test.ts
Give each existing test project a description.

The TypeScript files describe the new field, but the database still needs its column. Generate the SQL migration, apply it, then check the app:

bash
bun beignet db generate
bun beignet db migrate
bun beignet db status
bun run format
bun run test
bun run lint
bun run typecheck

Expect the migration status to be current and all checks to pass. If you see description type errors, check both repository adapters and all three test rows above. If SQLite reports a missing column, check that you ran the migration against the database selected in .env.local.

See it respond

With bun run dev running, create a project from your second terminal:

bash
curl -s -X POST http://localhost:3000/api/projects \
  -H "content-type: application/json" \
  -d '{"name":"Docs rewrite","description":"Shipped from the tutorial"}'

The response has this shape; your ID and timestamps will differ:

json
{
  "id": "7a8569a5-1248-4c49-b109-20488bd77171",
  "name": "Docs rewrite",
  "description": "Shipped from the tutorial",
  "version": 1,
  "createdAt": "2026-06-11T23:29:58.517Z",
  "updatedAt": "2026-06-11T23:29:58.517Z"
}

Read the project back by filtering the list:

bash
curl -s "http://localhost:3000/api/projects?name=Docs"

Look for the project in the response's items array. The accompanying page object describes pagination. Stop the development server with Ctrl+C, start it again with bun run dev, and repeat the list request. The same project should be there because it was saved in SQLite.

These requests need no session in this chapter. The next chapter adds that requirement and prevents users from reading each other's projects.

Checkpoint: a working API

Before adding ownership, confirm that:

  • Creating a project returns its name, description, ID, and version.
  • Listing projects returns the new record in a paginated response.
  • Restarting bun run dev and listing again returns the same persisted record.
  • The tests, lint, and typecheck above pass.

The description can be supplied during creation. The next chapter also makes it editable, ready for the UI.

Keep this app and its database for the next chapter. Continue with 2. Add ownership to restrict each account to its own projects.