Build an API with AI: spec, schema, tests, auth and deploy in 7 steps

Build an API with AI: spec, schema, tests, auth and deploy in 7 steps

To build an API with AI, you write the contract (an OpenAPI spec and a data model) yourself, let a coding agent implement it one endpoint at a time against tests, and review authorization and deployment by hand. This guide walks through the seven steps with prompts, code and the security checks agents most often miss.

In shortTL;DR
  • Start with an OpenAPI spec and a data model you have reviewed; a coding agent writes far better endpoints against a contract than from a one-line request.
  • Have the agent write a failing test for each endpoint before the code, including a test that one user cannot read another user's data.
  • Broken object level authorization is number one on the OWASP API Security Top 10 (2023), and it is the bug agents add most quietly: check ownership in every handler that takes an ID.
  • Run a schema-based fuzzer such as Schemathesis against the running API to catch crashes and responses that drift from the spec.
  • Deploy with secrets in environment variables, migrations as a separate step, a health check, rate limits and consistent error responses.

How do you build an API with AI?

You build an API with AI by deciding the contract yourself (endpoints, data model, auth rules), then having a coding agent such as Claude Code, Codex or Cursor implement it endpoint by endpoint against tests. Your job shifts from typing handlers to writing the spec, reviewing diffs and checking security.

The workflow in this guide has seven steps. The split of work matters more than the tool:

StepYou decideThe agent does
1. SpecResources, endpoints, errors, versioningDrafts the OpenAPI file from your notes
2. Project setupLanguage, framework, conventionsScaffolds the project, writes CLAUDE.md commands
3. Data modelEntities, constraints, ownershipWrites migrations and validation models
4. EndpointsOrder of work, acceptance criteriaWrites failing tests, then the handlers
5. AuthWho may do whatImplements auth middleware and ownership checks
6. Contract testsWhat "correct" meansRuns fuzzing, fixes failures
7. DeployHosting, secrets, limitsWrites Dockerfile, health check, CI

Throughout this guide the example is a small bookmarks API: users sign up, save links with tags, and list or delete their own bookmarks. It is small enough to finish and has the same security problem as most real APIs, which is keeping each user's data private.

Step 1: Why write an OpenAPI spec before any code?

An OpenAPI spec is a machine-readable contract for an HTTP API: every path, method, parameter, request body, response and error. Writing it first gives the agent an unambiguous target and gives your tests something to check against.

The OpenAPI Specification is at version 3.2.1 as of November 2026; 3.1 is still widely used, so check that your framework and tools support the version you choose. Our guide to spec-driven development covers the general method; for APIs, the OpenAPI file is the spec.

Let the agent draft the file from plain notes, then edit it yourself:

prompt
Draft an OpenAPI 3.1 spec in openapi.yaml for a bookmarks API.Resources: users, bookmarks (url, title, tags, created_at).Endpoints: POST /v1/auth/signup, POST /v1/auth/login,GET/POST /v1/bookmarks, GET/PATCH/DELETE /v1/bookmarks/{id}.Rules:- All bookmark endpoints require a bearer token.- A user can only see and change their own bookmarks.- List endpoint: cursor pagination, max 100 items, filter by tag.- Errors use application/problem+json (RFC 9457).- Give every operation an operationId, summary and example.Do not write any server code yet.

When you review the draft, check four things the agent tends to get vague about: pagination limits, which fields are read-only (id, created_at), what happens on duplicates, and which status code each error returns. A section of the result might look like this:

openapi.yaml
paths:  /v1/bookmarks/{id}:    get:      operationId: getBookmark      summary: Get one of the current user's bookmarks      security:        - bearerAuth: []      parameters:        - name: id          in: path          required: true          schema: { type: string, format: uuid }      responses:        "200":          description: The bookmark          content:            application/json:              schema: { $ref: "#/components/schemas/Bookmark" }        "404":          description: Not found, or owned by another user          content:            application/problem+json:              schema: { $ref: "#/components/schemas/Problem" }

Returning 404 rather than 403 for another user's bookmark is a deliberate choice: it does not confirm that the ID exists. Decisions like this belong in the spec, where the agent and every reviewer can see them.

Step 2: How do you set up the project for a coding agent?

Pick a framework you can read fluently, scaffold the project, and write a short instructions file with the exact commands to run tests, lint and start the server. The agent follows those commands on every task, so they must be correct.

Popular frameworks with lots of public examples give the best results, because the model has seen them many times:

StackStrengths for AI-built APIsWatch out for
Python + FastAPITyped request and response models; serves interactive docs at /docs and the spec at /openapi.jsonSync database calls inside async handlers
TypeScript + Hono or FastifySame language as a web frontend; schema validation with Zod or JSON SchemaAgents mixing validation libraries
TypeScript + ExpressHuge number of examplesNo validation or typing by default; you must add it
Go (net/http or a light router)Explicit code, easy to reviewMore boilerplate for the agent to get wrong

The FastAPI tutorial shows how the automatic docs and spec work. If you write the spec first with FastAPI, compare the generated /openapi.json with your committed openapi.yaml in CI so drift fails the build.

In Claude Code, run /init to generate a starting CLAUDE.md, then trim it to what Claude cannot discover itself (memory docs). For an API, the rules that matter most:

CLAUDE.md
## Commands- Run all tests: uv run pytest -q- Run one file: uv run pytest tests/test_bookmarks.py -q- Lint: uv run ruff check .- Start dev server: uv run fastapi dev app/main.py## API rules- openapi.yaml is the contract. Change it first, in a separate commit, and say so.- Every handler that loads a row by ID must filter by the current user's id.- Never return password hashes, tokens or internal fields in a response.- Errors use application/problem+json via app/errors.py. No ad hoc error dicts.- New endpoint = failing test first, then implementation.

More on what belongs in this file in CLAUDE.md best practices.

Step 3: How do you design the database schema with AI?

Design the entities and their constraints yourself, then let the agent write the migrations and the validation models from that design. The database should enforce what must always be true: required fields, uniqueness and ownership.

For the bookmarks API, the decisions are small but real: a bookmarks.user_id foreign key that is never null, a unique constraint on (user_id, url) if duplicates are not allowed, an index on (user_id, created_at) for the list endpoint, and tags as a separate table or an array column.

Ask the agent to propose, not to decide:

prompt
Read openapi.yaml. Propose a PostgreSQL schema for it as a table:table, columns, types, constraints, indexes, and why.Point out every place where the spec is ambiguous about the data.Do not write migrations until I approve the schema.

Then have it write one migration and the matching request and response models. Keep request models (what clients may send) separate from database models, so a client cannot set user_id or id by adding fields to the body. That mass-assignment bug is part of API3 in the OWASP list below. Our guide to AI database design goes further on schemas, indexes and migrations.

Step 4: How do you implement endpoints with a coding agent?

Implement one endpoint, or one small group, per task: the agent writes a failing test from the spec, then the handler, then runs the tests until they pass. Small tasks keep diffs reviewable and stop the agent from inventing behavior the spec does not describe.

Use plan mode for the first endpoint so you can correct the approach before any file changes. In Claude Code, start with claude --permission-mode plan or press Shift+Tab until the status bar shows plan mode (docs).

prompt
Implement GET /v1/bookmarks/{id} exactly as in openapi.yaml.1. Write tests first in tests/test_bookmarks.py:   - owner gets 200 with the documented fields only   - another user gets 404   - no token gets 401   - malformed id gets 422 or 400 as the spec says2. Run them and show they fail.3. Implement the handler. Do not change openapi.yaml.4. Run the full test file and the linter. Stop when both pass.

The tests that matter most are the unhappy paths. A cross-user test like this one catches the most common API vulnerability:

tests/test_bookmarks.py
def test_user_cannot_read_another_users_bookmark(client, make_user, make_bookmark):    alice = make_user("alice@example.com")    bob = make_user("bob@example.com")    bobs_bookmark = make_bookmark(owner=bob, url="https://example.com")    response = client.get(        f"/v1/bookmarks/{bobs_bookmark.id}",        headers={"Authorization": f"Bearer {alice.token}"},    )    assert response.status_code == 404    assert response.headers["content-type"].startswith("application/problem+json")

Read the tests before the implementation. Agents sometimes write tests that assert whatever the code happens to return, which proves nothing. Our guide to writing tests with AI shows how to spot those.

A laptop screen showing code in a dark editor
Keep each agent task to one endpoint so the diff fits on one screen.

Step 5: How do you add authentication and authorization safely?

Use a proven library or identity provider for authentication, and write authorization checks yourself or review them line by line. Authentication answers "who is this?"; authorization answers "may this user touch this object?", and the second one is where AI-written APIs most often fail.

The OWASP API Security Top 10 (2023) lists the risks. Five of them map directly to instructions you can give an agent:

OWASP riskWhat it looks like in AI-written codeWhat to require
API1 Broken Object Level Authorizationdb.get(Bookmark, id) with no owner filterFilter every lookup by the current user; cross-user tests
API2 Broken AuthenticationHand-rolled token signing, no expiryUse a maintained auth library or provider; short-lived tokens
API3 Broken Object Property Level AuthorizationReturning the whole ORM object, accepting any fieldSeparate request and response models
API4 Unrestricted Resource ConsumptionNo page size limit, no rate limitMax page size from the spec; rate limits on login and writes
API5 Broken Function Level AuthorizationAdmin routes guarded only by an unlinked URLRole checks on the route, tested

The ownership check itself is short. The point is that it appears in every handler that takes an ID:

app/routes/bookmarks.py
@router.get("/v1/bookmarks/{bookmark_id}", response_model=BookmarkOut)def get_bookmark(    bookmark_id: UUID,    user: User = Depends(current_user),    db: Session = Depends(get_db),):    bookmark = db.get(Bookmark, bookmark_id)    # Same 404 for "missing" and "not yours", so IDs can't be probed.    if bookmark is None or bookmark.user_id != user.id:        raise not_found("Bookmark not found")    return bookmark

If you store passwords, the OWASP Password Storage Cheat Sheet recommends Argon2id, with scrypt, bcrypt or PBKDF2 as alternatives; never a fast hash such as SHA-256. Check that the agent used the library's recommended function rather than writing its own.

Warning

Review every diff that touches auth middleware, token handling or a database query that takes an ID from the request. Do not let an agent auto-merge these.

Step 6: How do you test the API against its contract?

Run a schema-based testing tool against the running server so it sends thousands of generated requests based on your spec and reports crashes and responses that don't match. This catches what hand-written tests miss: odd strings, huge numbers, missing fields and undocumented status codes.

Schemathesis reads an OpenAPI or GraphQL schema, generates requests and checks the responses. It supports OpenAPI 2.0 through 3.2. Against a local server:

terminal
uv run fastapi dev app/main.py &uvx schemathesis run ./openapi.yaml --url http://localhost:8000

Each failure comes with a curl command to reproduce it. Hand the output to the agent:

prompt
Here is the Schemathesis output. For each failure:1. Decide if the bug is in the code or the spec, and explain why.2. Add a regression test that reproduces it.3. Fix it. Only change openapi.yaml if the spec was wrong, in a separate commit.

Add the same run to CI so every pull request is checked against the contract. Use a consistent error format while you are at it: RFC 9457 defines application/problem+json with fields such as type, title, status and detail, so clients can handle every error the same way.

Step 7: How do you deploy an AI-built API?

Deploy it like any other API: a container or managed runtime, secrets in environment variables, database migrations as their own step, a health check, logs and rate limits. Have the agent write the deployment files, then check each item yourself.

A deploy checklist for the agent's work:

  1. Dockerfile builds a small image, runs as a non-root user and starts the server with production settings, not the dev server.
  2. Configuration comes from environment variables; nothing secret is committed, and .env is in .gitignore.
  3. Migrations run as a separate release step before the new version starts, not on every container boot.
  4. Health check endpoint (for example GET /healthz) returns 200 without touching user data.
  5. Rate limits on login, signup and write endpoints, and a maximum request body size.
  6. CORS allows only the origins that need browser access.
  7. Logging records request IDs and errors, never tokens, passwords or full request bodies.
  8. CI runs lint, tests and the contract tests on every pull request before deploy.

Ask the agent to confirm each item with evidence (the file and line, or a command and its output) rather than a summary. Coding agents tend to report "done" for steps they only partly completed.

What mistakes do AI agents make when building APIs?

The most common mistakes are missing ownership checks, responses that leak internal fields, quietly changing the spec to match the code, and tests that only cover the happy path. Each one has a cheap guard.

MistakeHow you noticeGuard
No owner filter on lookupsCross-user test fails, or there is noneRule in CLAUDE.md plus a test per endpoint
Whole database row returnedpassword_hash or internal flags in JSONExplicit response models
Spec edited to match buggy codeopenapi.yaml in a diff you didn't expectSpec changes only in separate commits
Unbounded list endpointsSlow responses as data growsMax page size in spec and code
Invented dependenciesUnknown packages in the lockfileReview dependency changes in every PR
Inconsistent error shapesClients parse errors differently per routeOne error helper, RFC 9457 format
Tests that mirror the codeTests pass after you break the logicRead tests before code; mutate a line and rerun

A second reviewer helps. Running a separate AI code review pass on each pull request, with a prompt focused on authorization and data exposure, catches a share of these before you read the diff; see AI code review for a setup.

How to start building your API today

Start small: one resource, full auth, real tests, deployed. A finished small API teaches you more about working with an agent than a half-built large one.

  • Write five lines of notes on resources, users and the one rule that keeps data private.
  • Have the agent draft openapi.yaml; edit it until every error and limit is explicit.
  • Scaffold the project and write CLAUDE.md with test, lint and run commands plus the API rules.
  • Approve the schema, then implement one endpoint per task, tests first.
  • Add authentication with a maintained library and a cross-user test for every ID-based route.
  • Run Schemathesis locally, then in CI.
  • Deploy with the checklist above and review the auth diffs one more time.

Agent sessions for steps 4 to 6 can run long. If you want them to continue after you close your laptop, Orkio runs Claude Code and Codex on an always-on cloud box that pushes branches and opens pull requests, so you can review the next endpoint from your phone.

Frequently asked questions

Can AI build a whole API for me?

A coding agent can write most of the code for a typical CRUD API, including models, handlers, validation and tests. It cannot decide what your API should do, who may access which data, or which trade-offs fit your product. Treat the agent as a fast implementer and keep design, authorization and review for yourself.

Which framework is best for building an API with AI?

Pick a popular, well-documented framework you can read, because agents write better code for stacks with lots of public examples and you must review the result. FastAPI for Python and Express, Fastify or Hono for TypeScript are common choices. Stability and your own familiarity matter more than benchmarks.

Should I write the OpenAPI spec first or generate it from code?

Write it first when other teams, mobile apps or customers will call the API, because the spec becomes the contract that the agent and the tests check against. Generating it from code is fine for small internal APIs. Either way, commit the spec and fail CI when the implementation drifts from it.

How do I stop an AI agent from adding security holes to my API?

Give it explicit rules in the project instructions file, such as checking ownership on every object lookup and never returning password hashes, then enforce them with tests for cross-user access. Review every diff that touches authentication or authorization yourself. Add rate limits and a fuzzing step in CI.

How long does it take to build an API with AI?

A small CRUD API with authentication and tests can go from spec to deployed in a day or two with a coding agent, if the spec is clear and you review as you go. Most of the time goes into design decisions, reviewing authorization and fixing edge cases the tests uncover. Rushing the spec costs more time later than it saves.

SOURCES

  1. OpenAPI Specification (latest version)
  2. OWASP API Security Top 10, 2023 edition
  3. OWASP Password Storage Cheat Sheet
  4. RFC 9457: Problem Details for HTTP APIs
  5. Schemathesis documentation: Quick start
  6. FastAPI tutorial: First steps
  7. Claude Code docs: Common workflows (plan mode)
  8. Claude Code docs: How Claude remembers your project (CLAUDE.md)
  • #api
  • #openapi
  • #ai coding
  • #claude code
  • #testing
Orkio team

The team building Orkio. We write about putting AI to work: coding agents that run overnight, always-on boxes and pull requests ready by morning.

Keep reading

All posts

07:06 · YOU MERGED #128

Go to sleep. Wake up to pull requests.

Start for $19 a month
© 2026 Orkio · Hosted in Europe TürkçeStatus