--- title: "Build your first feature: API" description: "Start the three-chapter Projects tutorial: generate the API, add a description field, migrate SQLite, and verify persisted records over HTTP." url: "https://www.beignetjs.com/build-first-resource" markdown_url: "https://www.beignetjs.com/markdown/build-first-resource.md" framework_version: "0.0.65" documentation_scope: "current-checkout" source_revision: "e5b4771b262efbdd036e3a40a514c08d1508316c" source_modified: true --- # 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](https://www.beignetjs.com/markdown/build-first-resource/ownership.md) | Each account can read and change only its own projects | | [3. Connect the UI](https://www.beignetjs.com/markdown/build-first-resource/ui.md) | Create, list, edit, and delete projects in the browser | ## Before you start Continue in the full-stack SQLite app from the [quickstart](https://www.beignetjs.com/markdown/getting-started.md). 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](https://www.beignetjs.com/markdown/learn.md#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](https://www.beignetjs.com/markdown/build-first-resource/ownership.md) 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 ```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; create(input: CreateProjectInput): Promise; findById(id: string): Promise; update(input: UpdateProjectInput): Promise; delete(id: string): Promise; } ``` 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. ```diff --- a/features/projects/schemas.ts +++ b/features/projects/schemas.ts @@ -4,4 +4,5 @@ id: z.uuid(), name: z.string().min(1), + description: z.string().nullable(), version: z.number().int().min(1), createdAt: z.string().datetime(), @@ -96,4 +97,5 @@ export 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: ```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`. ```diff --- a/infra/db/schema/projects.ts +++ b/infra/db/schema/projects.ts @@ -4,4 +4,5 @@ id: text("id").primaryKey(), name: text("name").notNull(), + description: text("description"), version: integer("version").notNull(), createdAt: text("created_at").notNull(), --- a/infra/projects/drizzle-project-repository.ts +++ b/infra/projects/drizzle-project-repository.ts @@ -18,4 +18,5 @@ id: row.id, name: row.name, + description: row.description, version: row.version, createdAt: row.createdAt, @@ -104,4 +105,5 @@ id: crypto.randomUUID(), name: input.name, + description: input.description ?? null, version: 1, createdAt: now, --- a/infra/projects/in-memory-project-repository.ts +++ b/infra/projects/in-memory-project-repository.ts @@ -13,4 +13,5 @@ id: project.id, name: project.name, + description: project.description, version: project.version, createdAt: project.createdAt, @@ -92,4 +93,5 @@ id: crypto.randomUUID(), name: input.name, + description: input.description ?? null, version: 1, createdAt: now, ``` Give the existing test rows a description too: ```diff --- a/features/projects/tests/projects.test.ts +++ b/features/projects/tests/projects.test.ts @@ -36,4 +36,5 @@ id: "00000000-0000-4000-8000-000000000101", name: "Alpha Project", + description: null, version: 1, createdAt: "2024-01-01T00:00:00.000Z", @@ -43,4 +44,5 @@ id: "00000000-0000-4000-8000-000000000102", name: "Beta Project", + description: null, version: 1, createdAt: "2024-01-02T00:00:00.000Z", @@ -50,4 +52,5 @@ 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: ```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](https://www.beignetjs.com/markdown/build-first-resource/ownership.md) to restrict each account to its own projects.