Skip to content

Automated API Governance

This guide covers setting up a fully automated API design workflow where AI generates OpenAPI specifications, api-style-spec enforces standards, and humans only review—never manually create specs.

Overview

Traditional API design requires humans to write OpenAPI specs, which leads to:

  • Inconsistent style across teams
  • Time-consuming manual reviews
  • Style violations discovered late in the process
  • Knowledge silos around API best practices

The automated approach flips this:

Requirements → AI Generates Spec → Automated Validation → Human Review → Merge
                    ↑                      ↓
                    └──── Fix & Retry ─────┘

Key principles:

  1. AI creates, humans review - No manual spec writing
  2. Validation is blocking - Invalid specs cannot proceed
  3. Style is codified - Rules defined once, enforced everywhere
  4. Feedback is immediate - AI fixes issues in real-time

Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        Developer Workflow                        │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  1. Requirements    2. AI Generation    3. Validation          │
│  ┌───────────┐     ┌───────────────┐   ┌─────────────────┐     │
│  │ "Add user │────▶│ Claude Code   │──▶│ api-style-spec  │     │
│  │ endpoint" │     │ generates     │   │ lints spec      │     │
│  └───────────┘     │ openapi.yaml  │   └────────┬────────┘     │
│                    └───────────────┘            │               │
│                           ▲                     ▼               │
│                           │              ┌──────────────┐       │
│                           └──────────────│ Violations?  │       │
│                              Fix         └──────┬───────┘       │
│                                                 │ No            │
│  4. Commit         5. Pre-commit        6. PR Review            │
│  ┌───────────┐     ┌───────────────┐   ┌─────────────────┐     │
│  │ git add   │────▶│ Hook validates│──▶│ Human approves  │     │
│  │ git commit│     │ staged files  │   │ design decisions│     │
│  └───────────┘     └───────────────┘   └─────────────────┘     │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Setup

1. Install Tools

# Install api-style-spec CLI
go install github.com/plexusone/api-style-spec/cmd/api-style@latest

# Install MCP server for AI integration
go install github.com/plexusone/api-style-spec/cmd/mcp-api-style@latest

# Verify installation
api-style version

2. Configure Project

Create .api-style.yaml in your repository root:

# .api-style.yaml
profile: azure          # Or: default, google, zalando
level: silver           # Conformance level: bronze, silver, gold

include:
  - "api/**/*.yaml"
  - "openapi.yaml"

exclude:
  - "**/generated/**"
  - "**/vendor/**"

# Exceptions require documented justification
exceptions: []

# No severity downgrades by default - enforce all rules
severity-overrides: {}

3. Generate Spectral Ruleset

Export rules to Spectral format for editor integration:

api-style generate spectral --profile azure --output .spectral.yaml

This creates a standalone Spectral ruleset that works with:

  • VS Code Spectral extension
  • JetBrains OpenAPI plugin
  • Any Spectral-compatible tool

4. Install Pre-Commit Hook

api-style hooks init --profile azure --level silver

This blocks commits containing API style violations.

5. Configure AI Assistant

For Claude Code, add MCP server to .claude/settings.json:

{
  "mcpServers": {
    "api-style": {
      "command": "mcp-api-style",
      "args": ["serve"]
    }
  }
}

Or generate auto-lint hooks:

api-style hooks --format claude --auto-lint

Workflow: AI-Generated API Design

Step 1: Express Requirements in Natural Language

Instead of writing OpenAPI YAML, describe what you need:

Create a REST API endpoint for user registration.

Requirements:
- POST /users endpoint
- Request body: email, password, name (all required)
- Response: user object with id, email, name, createdAt
- Error responses for validation failures and duplicates
- Follow Azure API guidelines

Step 2: AI Generates the Spec

Claude Code (or your AI assistant) generates the OpenAPI spec:

# Generated by AI - openapi.yaml
openapi: "3.1.0"
info:
  title: User Service API
  version: "1.0.0"
paths:
  /users:
    post:
      operationId: createUser
      summary: Register a new user
      description: Creates a new user account with the provided details.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateUserRequest'
      responses:
        "201":
          description: User created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        "400":
          description: Validation error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProblemDetails'
        "409":
          description: User already exists
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProblemDetails'
# ... components defined below

Step 3: Automatic Validation

When the AI writes the file, api-style-spec validates it immediately:

[15:32:01] File changed: openapi.yaml
openapi.yaml: PASS (errors: 0, warnings: 0)

If there are violations, the AI sees them instantly:

[15:32:01] File changed: openapi.yaml
openapi.yaml: FAIL (errors: 2, warnings: 1)
  - [URI-001] Use plural resource names
  - [DOC-001] Operation must have a description

The AI then fixes the issues without human intervention.

Step 4: Commit with Pre-Commit Validation

git add openapi.yaml
git commit -m "feat(api): add user registration endpoint"

The pre-commit hook runs:

Linting staged OpenAPI specifications...
  Checking openapi.yaml... OK
All OpenAPI specifications passed linting
[main abc1234] feat(api): add user registration endpoint

If violations exist, the commit is blocked:

Linting staged OpenAPI specifications...
  Checking openapi.yaml... FAILED
  - [URI-001] Use plural resource names
    $.paths['/user']

Pre-commit hook failed: API style violations found
Fix the issues above or use 'git commit --no-verify' to skip

Step 5: Human Review (Design Decisions Only)

The PR contains:

  • AI-generated OpenAPI spec (validated)
  • No style violations (enforced by automation)

Human reviewers focus on:

  • Does the API meet business requirements?
  • Are the resource names semantically correct?
  • Is the data model appropriate?
  • Are there security considerations?

They do NOT review:

  • Plural vs singular naming (automated)
  • HTTP method correctness (automated)
  • Response code consistency (automated)
  • Documentation completeness (automated)

Advanced: Continuous Governance

Watch Mode for Development

Run continuous validation during development:

api-style lint api/ --recursive --watch

Output:

Starting watch mode...
Watching 5 file(s). Press Ctrl+C to stop.

api/users.yaml: PASS (errors: 0, warnings: 0)
api/orders.yaml: PASS (errors: 0, warnings: 1)
api/products.yaml: PASS (errors: 0, warnings: 0)

Watching for changes...

[15:45:12] File changed: api/users.yaml
api/users.yaml: PASS (errors: 0, warnings: 0)

CI/CD Pipeline Integration

Add to your GitHub Actions workflow:

# .github/workflows/api-lint.yaml
name: API Style Check

on:
  pull_request:
    paths:
      - 'api/**/*.yaml'
      - 'openapi.yaml'

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install api-style
        run: go install github.com/plexusone/api-style-spec/cmd/api-style@latest

      - name: Lint OpenAPI specs
        run: api-style lint api/ --recursive --format sarif --output results.sarif

      - name: Upload SARIF results
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: results.sarif

Multi-File Project Structure

For larger projects:

api/
├── .api-style.yaml          # Project config
├── users/
│   └── openapi.yaml         # User service API
├── orders/
│   └── openapi.yaml         # Order service API
├── products/
│   └── openapi.yaml         # Product service API
└── shared/
    └── components.yaml      # Shared schemas

Lint all at once:

api-style lint api/ --recursive

Conformance Level Progression

Start with bronze, progress to gold:

# .api-style.yaml - Start here
level: bronze   # Minimum: uri-design, http-methods

As the API matures:

# .api-style.yaml - Production ready
level: silver   # Adds: naming, errors, pagination

For public APIs:

# .api-style.yaml - Exemplary
level: gold     # Adds: security, documentation, versioning

AI Prompting Best Practices

Effective Prompts for API Generation

Good prompt:

Create an OpenAPI 3.1 spec for a product catalog API.

Endpoints needed:
- GET /products - list with pagination (cursor-based)
- GET /products/{id} - get single product
- POST /products - create product (admin only)
- PATCH /products/{id} - update product (admin only)
- DELETE /products/{id} - delete product (admin only)

Product fields: id, name, description, price, category, createdAt, updatedAt

Follow Azure API guidelines. Use RFC 7807 for errors.
Include proper security schemes (OAuth2 + API key).

Why it works:

  • Specifies OpenAPI version
  • Lists all endpoints with methods
  • Defines the data model
  • References the style guide
  • Mentions error format
  • Includes security requirements

Let AI Fix Violations

When violations occur, tell the AI:

The linter found these issues:
- [URI-001] Use plural resource names at $.paths['/product']
- [DOC-002] Missing operation description at $.paths['/products'].get

Fix these violations in the OpenAPI spec.

The AI will correct the issues and the lint will re-run automatically.

Troubleshooting

Pre-commit Hook Not Running

  1. Verify hook exists:

    ls -la .git/hooks/pre-commit
    

  2. Check it's executable:

    chmod +x .git/hooks/pre-commit
    

  3. Verify api-style is in PATH:

    which api-style
    

AI Not Seeing Lint Results

  1. Check MCP server is configured:

    mcp-api-style serve --help
    

  2. Or verify auto-lint hooks exist:

    cat .claude/settings.json | jq '.hooks'
    

Spectral Extension Not Using Rules

  1. Regenerate the ruleset:

    api-style generate spectral --profile azure --output .spectral.yaml
    

  2. Restart your editor

  3. Check .spectral.yaml is in the project root

Summary

Component Purpose Command
.api-style.yaml Project governance config (manual creation)
Pre-commit hook Block invalid commits api-style hooks init
Auto-lint hooks Real-time AI feedback api-style hooks --format claude
Watch mode Continuous validation api-style lint --watch
Spectral ruleset Editor integration api-style generate spectral
CI/CD integration PR validation api-style lint --format sarif

The result: 100% automated style enforcement with humans reviewing only design decisions, not style compliance.

Next Steps