Use Cases (अपडेट: 3/6/2026)

Claude Code से OpenAPI 3.1 गाइड: Swagger वैलिडेशन और TypeScript जनरेशन

Claude Code से OpenAPI 3.1 spec बनाएं, Swagger वैलिडेशन करें और TypeScript client जनरेट करें।

Claude Code से OpenAPI 3.1 गाइड: Swagger वैलिडेशन और TypeScript जनरेशन

Claude Code से OpenAPI फाइल बनवाना तेज है, लेकिन बिना जांच के उस फाइल को API contract मान लेना जोखिम भरा है। मॉडल UI label देखकर field मान सकता है, database में न होने वाला enum जोड़ सकता है, या हर endpoint के लिए अलग error format बना सकता है।

इस गाइड में Claude Code को schema का अंतिम निर्णायक नहीं, बल्कि API contract को बनाए रखने वाला सहायक माना गया है। हम OpenAPI 3.1 specification बनाएंगे, उसे validate करेंगे, TypeScript client और server stub generate करेंगे, और AI द्वारा बनाए गए गलत या अनुमानित schema पकड़ने के लिए छोटा local check जोड़ेंगे। OpenAPI REST endpoints, request, response, authentication और errors को machine-readable format में लिखने का तरीका है। Swagger उन tools का ecosystem है जिनसे ऐसी specs edit, preview और review की जाती हैं।

Masa ने यह workflow एक छोटी orders API पर आजमाया। पहले prompt में सिर्फ “repo पढ़कर OpenAPI बनाओ” कहा गया था। Claude Code ने cancelled status जोड़ दिया, जबकि domain model में वह था ही नहीं। बेहतर परिणाम तब मिला जब prompt में पढ़ने वाली files, अनुमान न लगाने का नियम, validation command और open questions को schema से बाहर रखने का तरीका साफ लिखा गया।

काम करते समय official docs देखें। 3 जून 2026 को जांचने पर OpenAPI Specification latest 3.2.0 है, लेकिन इस लेख के examples generator compatibility के लिए openapi: 3.1.0 पर रखे गए हैं। 3.1 details के लिए OpenAPI Specification 3.1.2, preview/editing के लिए Swagger Editor documentation, और generation के लिए OpenAPI Generator usage, typescript-fetch generator और typescript-nestjs-server generator देखें। OpenAPI 3.1 preview के लिए current Swagger docs में Swagger Editor Next support भी जांचें।

संबंधित पढ़ाई के लिए API development guide, API testing guide, security best practices और CLAUDE.md best practices देखें।

flowchart LR
  A["Implementation, DB, tests"] --> B["Claude Code OpenAPI draft"]
  B --> C["Swagger और CLI validation"]
  C --> D["TypeScript client"]
  C --> E["Contract tests"]
  C --> F["Security review"]
  D --> G["Frontend या partner integration"]
  E --> H["CI publish gate"]
  F --> H

वास्तविक उपयोग

उपयोगClaude Code क्या करेइंसान क्या तय करे
मौजूदा API document करनाroutes, models, status codes, auth boundary निकालनाpublic fields, compatibility, naming
contract-first APIOpenAPI 3.1 draft, examples, commandsbusiness rules, error policy, release scope
frontend integrationTypeScript client, call examples, type diffUX, retry, user messages
contract testsoperationId, 4xx responses, enums, auth checkbreaking change policy और exceptions
security reviewpublic schemas, auth, PII candidates, internal IDslegal risk, audit, partner promises
partner API publish करनाSwagger descriptions, samples, auth notescontracts, rate limits, support

मुख्य नियम: code, database, tests या product decision से साबित न होने वाली चीज public schema में नहीं जानी चाहिए।

Copy-paste setup

Node.js 20+ इस्तेमाल करें। OpenAPI Generator code generation के लिए Java इस्तेमाल करता है।

mkdir openapi-claude-demo
cd openapi-claude-demo
npm init -y
npm install -D @openapitools/openapi-generator-cli js-yaml
mkdir specs generated scripts

package.json:

{
  "type": "module",
  "scripts": {
    "validate:openapi": "openapi-generator-cli validate -i specs/openapi.yaml",
    "lint:contract": "node scripts/check-openapi-rules.mjs",
    "test:contract": "node --test scripts/contract.test.mjs",
    "generate:client": "openapi-generator-cli generate -i specs/openapi.yaml -g typescript-fetch -o generated/client --additional-properties=supportsES6=true,npmName=@example/orders-client,npmVersion=0.1.0",
    "generate:server": "openapi-generator-cli generate -i specs/openapi.yaml -g typescript-nestjs-server -o generated/server",
    "contract": "npm run validate:openapi && npm run lint:contract && npm run test:contract && npm run generate:client"
  },
  "devDependencies": {
    "@openapitools/openapi-generator-cli": "latest",
    "js-yaml": "latest"
  }
}

specs/openapi.yaml:

openapi: 3.1.0
info:
  title: Orders API
  version: 0.1.0
  description: Contract-first sample API for order intake.
servers:
  - url: https://api.example.com/v1
paths:
  /orders:
    post:
      operationId: createOrder
      summary: Create an order
      tags: [orders]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateOrderRequest"
      responses:
        "201":
          description: Order created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Order"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
  responses:
    BadRequest:
      description: Invalid request
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ErrorResponse"
    Unauthorized:
      description: Missing or invalid token
  schemas:
    CreateOrderRequest:
      type: object
      additionalProperties: false
      required: [customerEmail, items]
      properties:
        customerEmail:
          type: string
          format: email
        note:
          type: [string, "null"]
        items:
          type: array
          minItems: 1
          items:
            $ref: "#/components/schemas/OrderItemInput"
    OrderItemInput:
      type: object
      additionalProperties: false
      required: [sku, quantity]
      properties:
        sku:
          type: string
        quantity:
          type: integer
          minimum: 1
    Order:
      type: object
      additionalProperties: false
      required: [id, customerEmail, status, items, createdAt]
      properties:
        id:
          type: string
          format: uuid
        customerEmail:
          type: string
          format: email
        status:
          type: string
          enum: [pending, paid]
        items:
          type: array
          items:
            $ref: "#/components/schemas/OrderItemInput"
        createdAt:
          type: string
          format: date-time
    ErrorResponse:
      type: object
      additionalProperties: false
      required: [code, message]
      properties:
        code:
          type: string
          enum: [invalid_request, unauthorized]
        message:
          type: string

Local contract check:

import { readFileSync } from "node:fs";

const spec = readFileSync("specs/openapi.yaml", "utf8");
const forbidden = [
  { pattern: /\bTBD\b|\bTODO\b|placeholder/i, reason: "unfinished placeholder" },
  { pattern: /nullable:\s*true/, reason: "OpenAPI 3.1 should use JSON Schema null types" },
  { pattern: /password|secret|clientSecret|apiKey/i, reason: "review sensitive fields before publishing" }
];

const errors = forbidden.filter((rule) => rule.pattern.test(spec)).map((rule) => `- ${rule.reason}`);
if (!spec.includes("additionalProperties: false")) errors.push("- schemas should explicitly decide additionalProperties");
if (errors.length > 0) {
  console.error("Contract review failed:\n" + errors.join("\n"));
  process.exit(1);
}
console.log("Contract review passed.");

CI में चलाने के लिए contract test भी जोड़ें। यह real server की पूरी integration test नहीं है; यह public contract की shape जांचता है: stable operationId, mutating operations में security, shared 4xx responses और current Order.status enum।

// scripts/contract.test.mjs
import { readFileSync } from "node:fs";
import assert from "node:assert/strict";
import test from "node:test";
import { load } from "js-yaml";

const doc = load(readFileSync("specs/openapi.yaml", "utf8"));
const httpMethods = new Set(["get", "put", "post", "delete", "patch", "options", "head", "trace"]);

function operations() {
  return Object.entries(doc.paths ?? {}).flatMap(([path, pathItem]) =>
    Object.entries(pathItem)
      .filter(([method]) => httpMethods.has(method))
      .map(([method, operation]) => ({ path, method, operation }))
  );
}

test("operationId is unique and camelCase", () => {
  const ids = operations().map(({ operation }) => operation.operationId);
  assert.equal(new Set(ids).size, ids.length);
  for (const id of ids) assert.match(id, /^[a-z][A-Za-z0-9]*$/);
});

test("mutating operations require security", () => {
  for (const { path, method, operation } of operations()) {
    if (["get", "head", "options"].includes(method)) continue;
    assert.ok(operation.security?.length, `${method.toUpperCase()} ${path} must declare security`);
  }
});

test("client-visible 4xx responses reuse shared components", () => {
  for (const { path, method, operation } of operations()) {
    for (const [status, response] of Object.entries(operation.responses ?? {})) {
      if (!status.startsWith("4")) continue;
      assert.ok(response.$ref?.startsWith("#/components/responses/"), `${method.toUpperCase()} ${path} ${status}`);
    }
  }
});

test("Order status enum matches the current implementation decision", () => {
  const status = doc.components.schemas.Order.properties.status;
  assert.deepEqual(status.enum, ["pending", "paid"]);
});

Run करें:

npm run validate:openapi
npm run lint:contract
npm run test:contract
npm run generate:client
npm run generate:server

Claude Code prompt

Orders API के लिए OpenAPI 3.1 contract बनाएं।
पहले src/routes/orders.ts, src/domain/order.ts, prisma/schema.prisma और tests/orders.test.ts पढ़ें।
Code, schema, tests या product note से साबित न होने वाले fields, enums या error codes न बनाएं।
Unresolved questions को x-claude-review में रखें, public schemas में नहीं।
nullable: true न इस्तेमाल करें। operationId stable camelCase में रखें।
Protected operations में security declare करें। Internal fields, PII और possible secrets को public schema से पहले x-claude-review में अलग रखें।
npm run validate:openapi, npm run lint:contract और npm run test:contract चलाएं, फिर failures ठीक करें।
Diff, TypeScript client call example, security review notes और human review questions लौटाएं।

Contract tests और security review

SaaS या partner API में OpenAPI review सिर्फ copy edit नहीं है। इसे चार हिस्सों में बांटें: spec review, generated client review, contract tests और security review। Spec review paths, methods, schemas, status codes और examples देखता है। Generated client review typescript-fetch types और null/optional handling देखता है। Contract tests missing auth, changing error shape और broken enum रोकते हैं। Security review public fields, PII, internal IDs, server URLs और possible secrets देखता है।

Claude Code diff list, test draft और review table बना सकता है। लेकिन कौन से fields publish होंगे, rate limit/SLA कैसे promise होंगे, legal risk क्या है और audit evidence कितना रखना है, यह team को तय करना होगा।

आम गलतियां

पहली गलती hallucinated schema है: cancelled, refunded या adminNote जैसे fields अच्छे लगते हैं लेकिन implementation में नहीं होते। दूसरी गलती inconsistent error response है। तीसरी गलती OpenAPI 3.1 में nullable: true जैसे पुराने 3.0 pattern का इस्तेमाल है। चौथी गलती generated client या server stub को हाथ से edit करना है। पांचवीं गलती सिर्फ Swagger preview देखकर review खत्म कर देना है।

Training और consultation CTA

OpenAPI cleanup training और consulting के लिए अच्छा विषय है, क्योंकि deliverables साफ होते हैं: spec, TypeScript client, server stub, contract test, validation और CI checklist। Solo builders ClaudeCodeLab products से prompts और review templates ले सकते हैं। Teams जो real repository, CLAUDE.md, API tests और security review तक standardize करना चाहते हैं, वे Claude Code training और consultation से शुरू कर सकते हैं।

हाथों-हाथ जांच का परिणाम

Masa के test में free prompt ने unimplemented statuses जोड़े और error shape बदल दी। जब required files, “guess मत करो” rule, openapi-generator-cli validate, local script और node --test contract checks जोड़े गए, तो human review चार decisions पर केंद्रित रहा: कौन से fields public हैं, enum future में कैसे बढ़ेगा, auth error text क्या होगा, और कहीं internal data schema में तो नहीं आया। OpenAPI सबसे अच्छा तब काम करता है जब वह AI और team के बीच shared contract हो, न कि AI को सौंपा हुआ unchecked document।

#Claude Code #OpenAPI #Swagger #API design #REST
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.