AI agents

AI-Powered API Development: The Future is Here

Where AI coding assistants help when building an API (spec drafts, handlers, tests, docs), where they fail, and how to verify what they produce.

By the APIStack team··Updated ·8 min read

A small humanoid robot with a white head sitting on a wooden bench, looking at a tablet

AI coding assistants can now draft an API specification, write the handlers, generate tests and keep documentation in step with the code. They are quick at all four. They are also wrong often enough that the output cannot be trusted without checks. This article describes a workflow that gets the speed and keeps the checks.

It is for developers who build HTTP APIs and are deciding where an assistant fits into that work.

What an assistant is good at

An assistant is most reliable when the task is well specified and the result can be checked mechanically. Translating a written description into an OpenAPI document, implementing a handler against a schema, writing test cases for a documented contract and producing reference documentation all fit that description.

It is least reliable where the right answer depends on things it cannot see: your traffic, your data volumes, your threat model, and the reasons behind earlier decisions. Authorization rules, performance work and schema migrations need a person who understands the system, even when the assistant writes the first draft.

That division suggests the workflow. Put the contract first and have a person review it. Let the assistant work from it, and verify everything against it automatically.

Draft the contract first

Ask for the specification before any code. A prompt that states the resources, the operations and the rules will produce a usable OpenAPI draft, and a reviewer can read a specification far faster than the same decisions spread across handlers.

This excerpt shows what a reviewed draft should pin down for one operation: the request schema, every response status and a shared error shape.

YAML
openapi: 3.1.0
info:
  title: Users API
  version: 1.0.0
paths:
  /users:
    post:
      operationId: createUser
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewUser'
      responses:
        '201':
          description: User created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          $ref: '#/components/responses/ValidationError'
        '409':
          description: A user with this email already exists
components:
  schemas:
    NewUser:
      type: object
      required: [name, email]
      additionalProperties: false
      properties:
        name: { type: string, minLength: 1, maxLength: 200 }
        email: { type: string, format: email }
    User:
      type: object
      required: [id, name, email]
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        email: { type: string, format: email }
  responses:
    ValidationError:
      description: The request body failed validation
      content:
        application/json:
          schema:
            type: object
            required: [error]
            properties:
              error: { type: string }

Review the draft for the things assistants tend to leave out: error responses, length and range limits on inputs, pagination on list endpoints, and what happens on a duplicate or a conflict. A linter such as Spectral catches structural problems and enforces your naming rules on every change.

Generate code against the contract

With the specification settled, implementation is a well-bounded task. Give the assistant the specification, the conventions of your codebase and one existing handler as a model, and ask for one operation at a time. A small request yields a diff short enough to review properly.

Read generated handlers with a specific list in mind:

  • Input validation matches the schema, including the rejection of unknown fields.
  • Every database query is parameterised.
  • Authentication and authorization checks are present on every route, not only the ones the prompt mentioned.
  • Errors return the documented shape and do not leak stack traces or internal identifiers.
  • Any library the assistant introduced exists, is maintained and is one you intend to depend on.

The last point matters because assistants sometimes produce package names that do not exist, or call functions that an older version of a library provided. Check new dependencies against the registry before installing them.

Generate tests, then check that they test something

Test generation is where assistants save the most typing, because a contract implies many cases that are tedious to write by hand. The example below is the kind of suite to ask for. It uses Vitest and Faker and runs against a local server, taking the base URL from the environment.

JavaScript
import { describe, test, expect } from 'vitest'
import { faker } from '@faker-js/faker'

const BASE_URL = process.env.API_URL ?? 'http://localhost:3000'

function createUser(body) {
    return fetch(`${BASE_URL}/users`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
    })
}

describe('POST /users', () => {
    test('creates users concurrently without errors', async () => {
        const requests = Array.from({ length: 20 }, () =>
            createUser({ name: faker.person.fullName(), email: faker.internet.email() })
        )
        const responses = await Promise.all(requests)
        expect(responses.every(r => r.status === 201)).toBe(true)
    })

    test.each([
        ['missing email', { name: 'Ada' }],
        ['empty name', { name: '', email: 'ada@example.com' }],
        ['malformed email', { name: 'Ada', email: 'not-an-email' }],
        ['unknown field', { name: 'Ada', email: 'ada@example.com', role: 'admin' }]
    ])('rejects %s with 400', async (_label, body) => {
        const response = await createUser(body)
        expect(response.status).toBe(400)
        expect((await response.json()).error).toBeDefined()
    })

    test('rejects a duplicate email with 409', async () => {
        const user = { name: 'Ada', email: faker.internet.email() }
        expect((await createUser(user)).status).toBe(201)
        expect((await createUser(user)).status).toBe(409)
    })
})

Generated tests fail in a characteristic way: they assert what the code does, not what it should do. When the assistant writes the handler and the tests in the same session, a bug in the handler can be reproduced faithfully in the test. Two habits guard against that. Generate the tests from the specification before the implementation exists, or in a separate session that cannot see it. And confirm that each test can fail by breaking the behaviour it covers and watching the test go red.

Schema-driven tools complement hand-reviewed cases. Schemathesis reads an OpenAPI document and generates requests, including malformed ones, then checks every response against the documented schema. It needs no model and finds a different class of problem.

Documentation and review

Reference documentation generated from the specification stays accurate, because the same file drives the tests. Assistants add value in the prose around it: a quick-start, a worked example for each operation and a changelog entry written from a diff. Run every generated example against the real API before publishing it. An example that does not work costs more trust than a missing one.

Assistants are also useful as a first reviewer. Asked to review a pull request against the specification, one can pick up a missing status code, an unvalidated field or an inconsistent name. Treat that as an addition to human review and not a replacement. It will not catch a design that is wrong for your system.

Give the assistant real context

Much of an assistant's unreliability comes from guessing at things it could have looked up, such as your database schema, the response an upstream API actually returns, or today's date. The Model Context Protocol lets coding assistants connect to tools that supply these facts. Claude Code, Cursor and VS Code all support it.

APIStack's APIs are available this way on every plan. During development an assistant can call them to validate an IBAN in a fixture, check which days are public holidays for a scheduling test, or convert a currency at the reference rate, where it would otherwise invent a plausible value. The facts server at https://apistack.online/api/mcp/facts needs no key for 50 calls a day:

Shell
claude mcp add --transport http apistack-facts https://apistack.online/api/mcp/facts

Other clients and the full-catalogue endpoint are covered on the MCP page. In your own code the same APIs are REST endpoints under https://apistack.online, called with your key in the x-api-key header. The free plan includes 1,000 calls a month.

What still needs a person

Some claims made for AI in API development do not hold up. An assistant does not tune your database from a prompt: index and query changes need measurements from your own workload, and a suggestion made without them is a hypothesis to test. Systems that change production behaviour without review are a risk, whatever they are called.

Three areas stay with the team. Design decisions, such as resource boundaries, versioning and what the API promises, outlive any implementation. Security review comes next, because generated code can reproduce insecure patterns from the code the model learned from. The last is operations, where the cost of a confident wrong answer is highest.

Summary

  • Use assistants where the task is well specified and the result can be checked: specification drafts, handlers, tests and documentation.
  • Write and review the OpenAPI contract first, then generate code and tests against it one operation at a time.
  • Review generated handlers for validation, authorization, parameterised queries, error shape and dependencies that actually exist.
  • Make sure generated tests can fail, and add schema-driven testing that does not depend on a model.
  • Connect the assistant to real data sources through MCP so that it looks facts up, and keep design, security and operations decisions with people.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading