#claude-code#api#backend#rest#nextjs#fastapi#tutorial

Claude Code for API Development: Ship Production APIs in Hours, Not Weeks

Building a production API means routes, validation, auth, error handling, rate limiting, docs, and tests. Claude Code handles all of it from a single prompt. Here's the playbook.

AI Builder ClubApril 12, 20263 min read

A "production API" isn't one endpoint that returns JSON. It's routes, input validation, authentication, authorization, error handling, rate limiting, pagination, documentation, logging, and tests. For every endpoint.

That's why API development takes weeks even when the business logic is simple. The boilerplate-to-logic ratio is brutal.

Claude Code flips this. You describe the API — endpoints, auth rules, validation — and it generates the entire production surface. You write the business logic that's unique to your product.


Use Case 1: Full CRUD API with Auth

Build a REST API for managing projects. Each user can have multiple projects.

Endpoints:
- POST /api/projects — create a project (name required, description optional)
- GET /api/projects — list the authenticated user's projects (paginated, 20 per page)
- GET /api/projects/[id] — get a single project (only if the user owns it)
- PATCH /api/projects/[id] — update a project (only if the user owns it)
- DELETE /api/projects/[id] — soft delete (set deleted_at timestamp)

Requirements:
- All routes require authentication (check Supabase session)
- Input validation with zod on POST and PATCH
- Proper error responses: 400, 401, 403, 404, 500
- Pagination: return { data: [], meta: { page, per_page, total, total_pages } }
- Add the database migration and RLS

Follow our existing API patterns in app/api/stripe/checkout/route.ts.

What you get: 5 route files, a migration, zod schemas, typed responses, proper HTTP status codes, pagination logic, and soft delete — all following your existing patterns.


Use Case 2: Webhook Handler with Idempotency

Build a webhook handler at app/api/webhook/[provider]/route.ts:

1. Stripe webhooks (/api/webhook/stripe):
   - Verify signature using STRIPE_WEBHOOK_SECRET
   - Handle: checkout.session.completed, customer.subscription.updated,
     customer.subscription.deleted, invoice.payment_failed

2. Resend webhooks (/api/webhook/resend):
   - Handle: email.delivered, email.bounced, email.complained

Shared requirements:
- Idempotency: store processed event IDs in a webhook_events table.
  If already processed, return 200 immediately.
- Always return 200 to the provider (even if processing fails internally)
- Log every event with: provider, event_type, event_id, processing_status

Use Case 3: API Rate Limiting and Security

Add rate limiting and security hardening to all API routes:

1. Rate limiter (lib/rate-limit.ts):
   - Sliding window algorithm
   - Configurable per route: default 60/min, auth routes 10/min, webhooks 100/min
   - Return 429 with Retry-After header when limited

2. Security middleware:
   - CORS: only allow our domain and localhost in dev
   - Input sanitization: strip HTML from all string inputs
   - Request size limit: 1MB for regular routes, 10MB for uploads
   - Security headers: X-Content-Type-Options, X-Frame-Options

Use Case 4: API Documentation Generation

Read all API routes in app/api/ and generate:

1. An OpenAPI 3.0 spec at public/openapi.yaml
2. A developer-friendly API reference page at app/docs/api/page.tsx:
   - Left sidebar with endpoint groups
   - Each endpoint: method badge, path, request/response examples
   - Code examples in curl, JavaScript, and Python

Read the actual route files — don't make up endpoints.

Use Case 5: Test Suite Generation

Generate a comprehensive test suite for all API routes in app/api/:

For each route, test:
1. Happy path — valid input, authenticated user
2. Authentication — no auth token returns 401
3. Authorization — another user's resource returns 403
4. Validation — invalid/missing fields return 400 with field errors
5. Not found — non-existent resource returns 404
6. Edge cases — empty strings, SQL injection attempts, XSS payloads

Create test utilities: createTestUser(), createTestProject(), cleanupTestData().
Run the full suite after generating and fix any failures.

Time saved: Writing thorough API tests for 5 endpoints is a full day. Claude Code generates them in minutes.


The API Development CLAUDE.md

## API Conventions
- Routes: app/api/[resource]/route.ts for collections,
  app/api/[resource]/[id]/route.ts for items
- Validation: zod schemas defined inline in route files
- Auth: check Supabase session, return 401 if missing
- Errors: { error: string, details?: object } format
- Pagination: { data: T[], meta: { page, per_page, total, total_pages } }
- Reference implementation: app/api/stripe/checkout/route.ts

If you're building APIs with Claude Code, join AI Builder Club. We share real API architectures, testing strategies, and optimization techniques.

Get the free AI Builder Newsletter

Weekly deep-dives on AI tools, automation workflows, and builder strategies. Join 5,000+ readers.

No spam. Unsubscribe anytime.

Go deeper with AI Builder Club

Join 1,000+ ambitious professionals and builders learning to use AI at work.

  • Expert-led courses on Cursor, MCP, AI agents, and more
  • Weekly live workshops with industry builders
  • Private community for feedback, collaboration, and accountability