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.
| Chapter | Working result |
|---|---|
| 1. Build the API (this page) | Create and retrieve persisted projects over HTTP |
| 2. Add ownership | Each account can read and change only its own projects |
| 3. Connect the UI | Create, 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:
| Files | Change |
|---|---|
features/projects/schemas.ts | Add the description to the response and create input |
infra/db/schema/projects.ts | Store the description |
infra/projects/*-project-repository.ts | Return and persist the field in both adapters |
features/projects/tests/projects.test.ts | Update the existing test data |
drizzle/ | Generate and apply the schema migration |
Generate the resource
bun beignet make resource projects --useCaseLayout splitThis 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:
bun beignet db generate
bun beignet db migrate
bun beignet db statusExpect Database migrations are current. Then confirm the routes are registered:
bun beignet routesMETHOD 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:
// 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:
// 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:
// 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:
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.
3 unmodified lines4567888 unmodified lines9798991001013 unmodified lines id: z.uuid(), name: z.string().min(1), description: z.string().nullable(), version: z.number().int().min(1), createdAt: z.string().datetime(),88 unmodified linesexport const CreateProjectInputSchema = z.object({ name: z.string().trim().min(1).max(120), description: z.string().max(500).optional(),});
Run the typecheck now to find the code that must return this new field:
bun run typecheckType 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.
3 unmodified lines456783 unmodified lines id: text("id").primaryKey(), name: text("name").notNull(), description: text("description"), version: integer("version").notNull(), createdAt: text("created_at").notNull(),Give the existing test rows a description too:
35 unmodified lines36373839403 unmodified lines44454647483 unmodified lines525354555635 unmodified lines id: "00000000-0000-4000-8000-000000000101", name: "Alpha Project", description: null, version: 1, createdAt: "2024-01-01T00:00:00.000Z",3 unmodified lines id: "00000000-0000-4000-8000-000000000102", name: "Beta Project", description: null, version: 1, createdAt: "2024-01-02T00:00:00.000Z",3 unmodified lines id: "00000000-0000-4000-8000-000000000103", name: "Gamma Project", description: null, version: 1, createdAt: "2024-01-03T00:00:00.000Z",The TypeScript files describe the new field, but the database still needs its column. Generate the SQL migration, apply it, then check the app:
bun beignet db generate
bun beignet db migrate
bun beignet db status
bun run format
bun run test
bun run lint
bun run typecheckExpect 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:
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:
{
"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:
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 devand 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.