Use Cases

Claude Code के साथ API Development को Accelerate करें: Design से Testing तक

Claude Code का उपयोग करके API Development को Accelerate करें। Design से Testing तक। Practical code examples शामिल हैं।

API Development Bottlenecks को खत्म करना

API development में कई repetitive tasks होते हैं — endpoint design, validation, error handling, और test creation। Claude Code इन सभी को quickly और efficiently handle कर सकता है।

Batch Endpoint Generation

Claude Code से सभी CRUD endpoints एक बार में बनाएं।

> निम्नलिखित resource के लिए RESTful API बनाओ।
> Framework: Express + TypeScript.
>
> Resource: Task
> Fields: id, title, description, status, dueDate, createdAt, updatedAt
> Endpoints: GET /tasks, GET /tasks/:id, POST /tasks, PUT /tasks/:id, DELETE /tasks/:id
> Validation: zod use करो
> Response format: { data, meta, error }

Generated Code Example

import { Router, Request, Response } from "express";
import { z } from "zod";

const TaskSchema = z.object({
  title: z.string().min(1).max(200),
  description: z.string().optional(),
  status: z.enum(["todo", "in_progress", "done"]).default("todo"),
  dueDate: z.string().datetime().optional(),
});

const router = Router();

router.get("/tasks", async (req: Request, res: Response) => {
  const page = Number(req.query.page) || 1;
  const limit = Number(req.query.limit) || 20;
  const offset = (page - 1) * limit;

  const tasks = await taskRepository.findAll({ offset, limit });
  const total = await taskRepository.count();

  res.json({
    data: tasks,
    meta: { page, limit, total, totalPages: Math.ceil(total / limit) },
  });
});

router.post("/tasks", async (req: Request, res: Response) => {
  const parsed = TaskSchema.safeParse(req.body);
  if (!parsed.success) {
    return res.status(400).json({
      error: { message: "Validation error", details: parsed.error.issues },
    });
  }

  const task = await taskRepository.create(parsed.data);
  res.status(201).json({ data: task });
});

export default router;

OpenAPI Specs से Generate करना

अगर existing API specification है, तो उसे pass करके implementation generate किया जा सकता है।

> openapi.yaml में definitions के based पर सभी endpoints implement करो।
> Validation को schema definitions से match करो।
> हर endpoint के लिए tests भी बनाओ।

API Tests Auto-Generate करना

Implementation और tests साथ में बनाने से quality ensure होती है।

> POST /tasks endpoint के लिए tests बनाओ।
> Success cases, error cases, और boundary values cover करो।
import request from "supertest";
import { app } from "../app";

describe("POST /tasks", () => {
  it("valid data के साथ 201 return करता है", async () => {
    const res = await request(app)
      .post("/tasks")
      .send({ title: "Test task", status: "todo" });

    expect(res.status).toBe(201);
    expect(res.body.data.title).toBe("Test task");
    expect(res.body.data.id).toBeDefined();
  });

  it("title empty होने पर 400 return करता है", async () => {
    const res = await request(app)
      .post("/tasks")
      .send({ title: "", status: "todo" });

    expect(res.status).toBe(400);
    expect(res.body.error).toBeDefined();
  });

  it("invalid status के लिए 400 return करता है", async () => {
    const res = await request(app)
      .post("/tasks")
      .send({ title: "Task", status: "invalid" });

    expect(res.status).toBe(400);
  });
});

Detailed test design strategies के लिए Complete Testing Strategy Guide देखें।

Middleware Generate करना

Authentication, rate limiting, logging जैसे common middleware भी generate किए जा सकते हैं।

> JWT authentication middleware बनाओ।
> - Authorization header से token extract करो
> - Expiration check करो
> - Decoded user info को req.user पर set करो
> - Error पर appropriate HTTP status return करो
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";

interface AuthRequest extends Request {
  user?: { id: string; email: string; role: string };
}

export function authenticate(
  req: AuthRequest,
  res: Response,
  next: NextFunction
) {
  const header = req.headers.authorization;

  if (!header?.startsWith("Bearer ")) {
    return res.status(401).json({ error: { message: "Authentication required" } });
  }

  try {
    const token = header.slice(7);
    const decoded = jwt.verify(token, process.env.JWT_SECRET!) as AuthRequest["user"];
    req.user = decoded;
    next();
  } catch (err) {
    if (err instanceof jwt.TokenExpiredError) {
      return res.status(401).json({ error: { message: "Token expired" } });
    }
    return res.status(403).json({ error: { message: "Invalid token" } });
  }
}

Unified Error Handling

पूरी API में consistent error responses design करने के लिए Error Handling Design Patterns देखें।

Database Integration

Repository layer और migrations भी simultaneously create किए जा सकते हैं। Database operations automate करने के लिए DB Migration Automation देखें।

Summary

Claude Code के साथ API development की key clear specifications define करना और comprehensive instructions देना है। Repetitive CRUD tasks Claude Code को handle करने दें ताकि आप business logic design पर focus कर सकें।

API best practices के लिए Anthropic Official Documentation और Express Official Guide देखें।

#Claude Code #API development #REST API #Express #backend